Skip to content
Snippets Groups Projects
Commit 93b954f8 authored by Pierre-Jean Vardanega's avatar Pierre-Jean Vardanega
Browse files

Insert data in start goal instead of in a new goal

parent 1ab82235
No related branches found
No related tags found
No related merge requests found
...@@ -116,6 +116,12 @@ ...@@ -116,6 +116,12 @@
<version>4.11</version> <version>4.11</version>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>1.10.8</version>
<scope>test</scope>
</dependency>
</dependencies> </dependencies>
<profiles> <profiles>
......
...@@ -19,9 +19,9 @@ import java.io.File; ...@@ -19,9 +19,9 @@ import java.io.File;
import java.io.FileNotFoundException; import java.io.FileNotFoundException;
import java.net.UnknownHostException; import java.net.UnknownHostException;
import java.util.Scanner; import java.util.Scanner;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException; import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugin.logging.Log;
import com.mongodb.CommandResult; import com.mongodb.CommandResult;
import com.mongodb.DB; import com.mongodb.DB;
import com.mongodb.MongoClient; import com.mongodb.MongoClient;
...@@ -32,93 +32,73 @@ import com.mongodb.MongoException; ...@@ -32,93 +32,73 @@ import com.mongodb.MongoException;
* to add data. * to add data.
* *
* You should use the same javascript syntax that you would use in the mongo client. * You should use the same javascript syntax that you would use in the mongo client.
*
* @goal init-data
* @phase pre-integration-test
*/ */
public class InitDataMongoMojo extends AbstractMojo { public class DataInitializer {
/**
* Folder that contains all scripts to execute.
* @parameter
* @required
*/
private File dataFolder;
/** private File initDirectory;
* Optional. Specify the port only if you want have a different one from the default value.
* Default value is 27017.
* @parameter
*/
private int port; private int port;
/**
* The name of the database where data will be stored.
* @parameter
* @required
*/
private String databaseName; private String databaseName;
private Log logger;
@Override public DataInitializer(File initDirectory, int port, String databaseName, Log logger) {
public void execute() throws MojoExecutionException, MojoFailureException { this.initDirectory = initDirectory;
DB db = getConnectToMongoAndGetDatabase(); this.port = port;
this.databaseName = databaseName;
this.logger = logger;
}
if (dataFolder.isDirectory()) { public void insertData() throws MojoExecutionException, MojoFailureException {
if (initDirectory.isDirectory()) {
Scanner scanner = null; Scanner scanner = null;
StringBuilder instructions = new StringBuilder(); StringBuilder instructions = new StringBuilder();
File[] files = dataFolder.listFiles(); File[] files = initDirectory.listFiles();
getLog().info("Folder " + dataFolder.getAbsolutePath() + " contains " + files.length + " file(s):"); if (files != null && files.length > 0) {
for (File file : files) { logger.info("Folder " + initDirectory.getAbsolutePath() + " contains " + files.length + " file(s):");
try { DB db = getConnectToMongoAndGetDatabase();
scanner = new Scanner(file); for (File file : files) {
while (scanner.hasNextLine()) { try {
instructions.append(scanner.nextLine()).append("\n"); scanner = new Scanner(file);
while (scanner.hasNextLine()) {
instructions.append(scanner.nextLine()).append("\n");
}
} catch (FileNotFoundException e) {
throw new MojoExecutionException("Unable to find file with name '" + file.getName() + "'", e);
} finally {
if (scanner != null) {
scanner.close();
}
} }
} catch (FileNotFoundException e) { CommandResult result;
throw new MojoExecutionException("Unable to find file with name '" + file.getName() + "'", e); try {
} finally { result = db.doEval("(function() {" + instructions.toString() + "})();", new Object[0]);
if (scanner != null) { } catch (MongoException e) {
scanner.close(); throw new MojoExecutionException("Unable to execute file with name '" + file.getName() + "'", e);
} }
if (!result.ok()) {
logger.error("- file " + file.getName() + " parsed with error: " + result.getErrorMessage());
throw new MojoExecutionException("Error while executing instructions from file '"+file.getName()+"': " + result.getErrorMessage(), result.getException());
}
logger.info("- file " + file.getName() + " parsed successfully");
} }
CommandResult result; logger.info("Data initialized with success");
try { } else {
result = db.doEval("(function() {" + instructions.toString() + "})();", new Object[0]); logger.info("No data to initialize");
} catch (MongoException e) {
throw new MojoExecutionException("Unable to execute file with name '" + file.getName() + "'", e);
}
if (!result.ok()) {
getLog().error("- file " + file.getName() + " parsed with error: " + result.getErrorMessage());
throw new MojoExecutionException("Error while executing instructions from file '"+file.getName()+"': " + result.getErrorMessage(), result.getException());
}
getLog().info("- file " + file.getName() + " parsed successfully");
} }
getLog().info("Data initialized with success");
} }
} }
private DB getConnectToMongoAndGetDatabase() throws MojoExecutionException { DB getConnectToMongoAndGetDatabase() throws MojoExecutionException {
if (databaseName == null || databaseName.trim().length() == 0) { if (databaseName == null || databaseName.trim().length() == 0) {
throw new MojoExecutionException("Database name is missing"); throw new MojoExecutionException("Database name is missing");
} }
MongoClient mongoClient; MongoClient mongoClient;
try { try {
mongoClient = new MongoClient("localhost", port == 0 ? 27017 : port); mongoClient = new MongoClient("localhost", port);
} catch (UnknownHostException e) { } catch (UnknownHostException e) {
throw new MojoExecutionException("Unable to connect to mongo instance", e); throw new MojoExecutionException("Unable to connect to mongo instance", e);
} }
getLog().info("Connected to MongoDB"); logger.info("Connected to MongoDB");
return mongoClient.getDB(databaseName); return mongoClient.getDB(databaseName);
} }
protected InitDataMongoMojo setDataFolder(File dataFolder) {
this.dataFolder = dataFolder;
return this;
}
protected InitDataMongoMojo setDatabaseName(String databaseName) {
this.databaseName = databaseName;
return this;
}
} }
...@@ -211,6 +211,20 @@ public class StartEmbeddedMongoMojo extends AbstractMojo { ...@@ -211,6 +211,20 @@ public class StartEmbeddedMongoMojo extends AbstractMojo {
*/ */
private boolean skip; private boolean skip;
/**
* The name of the database where data will be stored.
* @parameter
* @required
*/
private String databaseName;
/**
* Folder that contains all scripts to execute.
* @parameter
* @required
*/
private File initDirectory;
@Override @Override
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public void execute() throws MojoExecutionException, MojoFailureException { public void execute() throws MojoExecutionException, MojoFailureException {
...@@ -284,6 +298,8 @@ public class StartEmbeddedMongoMojo extends AbstractMojo { ...@@ -284,6 +298,8 @@ public class StartEmbeddedMongoMojo extends AbstractMojo {
} catch (IOException e) { } catch (IOException e) {
throw new MojoExecutionException("Unable to start the mongod", e); throw new MojoExecutionException("Unable to start the mongod", e);
} }
new DataInitializer(initDirectory, port, databaseName, getLog()).insertData();
} }
/** /**
......
...@@ -16,19 +16,31 @@ ...@@ -16,19 +16,31 @@
package com.github.joelittlejohn.embedmongo; package com.github.joelittlejohn.embedmongo;
import static org.junit.Assert.fail; import static org.junit.Assert.fail;
import static org.mockito.BDDMockito.given;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.mock;
import java.io.BufferedWriter; import java.io.BufferedWriter;
import java.io.File; import java.io.File;
import java.io.FileWriter; import java.io.FileWriter;
import java.io.IOException; import java.io.IOException;
import java.net.UnknownHostException;
import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException; import org.apache.maven.plugin.MojoFailureException;
import org.junit.Ignore; import org.apache.maven.plugin.logging.Log;
import org.apache.maven.plugin.logging.SystemStreamLog;
import org.junit.Rule; import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.rules.ExpectedException; import org.junit.rules.ExpectedException;
import org.junit.rules.TemporaryFolder; import org.junit.rules.TemporaryFolder;
import org.junit.runner.RunWith;
import org.mockito.Matchers;
import org.mockito.runners.MockitoJUnitRunner;
import com.mongodb.CommandResult;
import com.mongodb.DB;
import com.mongodb.EmbedMongoDB;
public class InitDataMongoMojoTest { @RunWith(MockitoJUnitRunner.class)
public class DataInitializerTest {
@Rule @Rule
public TemporaryFolder createSchemaFolder = new TemporaryFolder(); public TemporaryFolder createSchemaFolder = new TemporaryFolder();
...@@ -36,37 +48,44 @@ public class InitDataMongoMojoTest { ...@@ -36,37 +48,44 @@ public class InitDataMongoMojoTest {
@Rule @Rule
public ExpectedException thrown = ExpectedException.none(); public ExpectedException thrown = ExpectedException.none();
private final static int PORT = 27017;
private final static Log LOGGER = new SystemStreamLog();
private File rootFolder; private File rootFolder;
private File rootFolderWithError; private File rootFolderWithError;
@Ignore("Need an instance of MongoDB to pass")
@Test public void @Test public void
should_execute_instructions() throws MojoFailureException, MojoExecutionException, IOException { should_execute_instructions() throws MojoFailureException, MojoExecutionException, IOException {
initFolder(); initFolder();
try { try {
new InitDataMongoMojo().setDatabaseName("myDB").setDataFolder(rootFolder).execute(); new DataInitializerForTest(rootFolder, PORT, "myDB", LOGGER).insertData();
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace();
fail("Should not fail!"); fail("Should not fail!");
} }
} }
@Test public void @Test public void
should_fail_when_database_name_is_not_provided() throws MojoFailureException, MojoExecutionException { should_fail_when_database_name_is_not_provided() throws MojoFailureException, MojoExecutionException, IOException {
initFolder();
thrown.expect(MojoExecutionException.class); thrown.expect(MojoExecutionException.class);
thrown.expectMessage("Database name is missing"); thrown.expectMessage("Database name is missing");
new InitDataMongoMojo().execute(); new DataInitializer(rootFolder, PORT, null, LOGGER).insertData();
} }
@Ignore("Need an instance of MongoDB to pass")
@Test public void @Test public void
should_fail_to_execute_instruction_with_error() throws IOException, MojoFailureException, MojoExecutionException { should_fail_to_execute_instruction_with_error() throws IOException, MojoFailureException, MojoExecutionException {
DB database = mock(DB.class);
initFolderWithError(); initFolderWithError();
CommandResult result = new EmbedMongoDB("myDB").notOkErrorResult("Error while executing instructions from file '" + rootFolderWithError.listFiles()[0].getName());
given(database.doEval(anyString(), Matchers.<Object>anyVararg())).willReturn(result);
thrown.expect(MojoExecutionException.class); thrown.expect(MojoExecutionException.class);
thrown.expectMessage("Error while executing instructions from file '" + rootFolderWithError.listFiles()[0].getName()); thrown.expectMessage("Error while executing instructions from file '" + rootFolderWithError.listFiles()[0].getName());
new InitDataMongoMojo().setDatabaseName("myDB").setDataFolder(rootFolderWithError).execute(); new DataInitializerForTest(rootFolderWithError, PORT, "myDB", LOGGER, database).insertData();
} }
private void initFolder() throws IOException { private void initFolder() throws IOException {
...@@ -87,16 +106,35 @@ public class InitDataMongoMojoTest { ...@@ -87,16 +106,35 @@ public class InitDataMongoMojoTest {
private void initFolderWithError() throws IOException { private void initFolderWithError() throws IOException {
File instructionsFile = createSchemaFolder.newFile(); File instructionsFile = createSchemaFolder.newFile();
BufferedWriter out = null; BufferedWriter reader = null;
try { try {
out = new BufferedWriter(new FileWriter(instructionsFile)); reader = new BufferedWriter(new FileWriter(instructionsFile));
out.write("db.unknownInstruction();\n"); reader.write("db.unknownInstruction();\n");
} finally { } finally {
if (out != null) { if (reader != null) {
out.close(); reader.close();
} }
} }
rootFolderWithError = instructionsFile.getParentFile(); rootFolderWithError = instructionsFile.getParentFile();
rootFolderWithError.mkdir(); rootFolderWithError.mkdir();
} }
static class DataInitializerForTest extends DataInitializer {
private final DB database;
public DataInitializerForTest(File dataFolder, int port, String databaseName, Log logger) throws UnknownHostException {
this(dataFolder, port, databaseName, logger, new EmbedMongoDB("myDB"));
}
public DataInitializerForTest(File dataFolder, int port, String databaseName, Log logger, DB database) {
super(dataFolder, port, databaseName, logger);
this.database = database;
}
@Override
DB getConnectToMongoAndGetDatabase() throws MojoExecutionException {
return database;
}
}
} }
...@@ -22,7 +22,6 @@ import java.util.concurrent.CountDownLatch; ...@@ -22,7 +22,6 @@ import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executors; import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import org.junit.After; import org.junit.After;
import org.junit.Test; import org.junit.Test;
......
/**
* Copyright © 2012 Joe Littlejohn
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.mongodb;
import java.net.UnknownHostException;
public class EmbedMongoClient extends MongoClient {
public EmbedMongoClient() throws UnknownHostException {
}
}
/**
* Copyright © 2012 Joe Littlejohn
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.mongodb;
import java.net.UnknownHostException;
import java.util.Set;
public class EmbedMongoDB extends DB {
public EmbedMongoDB(String name) throws UnknownHostException {
super(new EmbedMongoClient(), name);
}
public CommandResult notOkErrorResult(String message) {
try {
CommandResult commandResult = new CommandResult(new ServerAddress("localhost"));
commandResult.put("errmsg", message);
commandResult.put("ok", 0);
return commandResult;
} catch (UnknownHostException e) {
return null;
}
}
@Override
public CommandResult doEval(String code, Object... args) {
CommandResult commandResult;
try {
commandResult = new CommandResult(new ServerAddress("localhost"));
commandResult.put("ok", 1.0);
commandResult.put("retval", "null");
} catch (UnknownHostException e) {
return notOkErrorResult(e.getMessage());
}
return commandResult;
}
@Override
public void requestStart() {
}
@Override
public void requestDone() {
}
@Override
public void requestEnsureConnection() {
}
@Override
protected DBCollection doGetCollection(String name) {
return null;
}
@Override
public Set<String> getCollectionNames() {
return null;
}
@Override
CommandResult doAuthenticate(MongoCredential credentials) {
return null;
}
@Override
public void cleanCursors(boolean force) {
}
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment