diff --git a/pom.xml b/pom.xml index 089b5fb8ed7d34fb08a7d168150953e0d778bede..5449eaa3b896f5f4a1e06d0cb05845ef7afda4cb 100644 --- a/pom.xml +++ b/pom.xml @@ -116,12 +116,6 @@ <version>4.11</version> <scope>test</scope> </dependency> - <dependency> - <groupId>org.mockito</groupId> - <artifactId>mockito-core</artifactId> - <version>1.10.8</version> - <scope>test</scope> - </dependency> </dependencies> <profiles> diff --git a/src/main/java/com/github/joelittlejohn/embedmongo/DataInitializer.java b/src/main/java/com/github/joelittlejohn/embedmongo/DataInitializer.java deleted file mode 100644 index 17a3c4c6e58ad3fdabca8fc2f4f289c38325ed07..0000000000000000000000000000000000000000 --- a/src/main/java/com/github/joelittlejohn/embedmongo/DataInitializer.java +++ /dev/null @@ -1,104 +0,0 @@ -/** - * 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.github.joelittlejohn.embedmongo; - -import java.io.File; -import java.io.FileNotFoundException; -import java.net.UnknownHostException; -import java.util.Scanner; -import org.apache.maven.plugin.MojoExecutionException; -import org.apache.maven.plugin.MojoFailureException; -import org.apache.maven.plugin.logging.Log; -import com.mongodb.CommandResult; -import com.mongodb.DB; -import com.mongodb.MongoClient; -import com.mongodb.MongoException; - -/** - * When invoked, this goal connects to an instance of mongo and execute some instructions - * to add data. - * - * You should use the same javascript syntax that you would use in the mongo client. - */ -public class DataInitializer { - - private File initDirectory; - private int port; - private String databaseName; - private Log logger; - - public DataInitializer(File initDirectory, int port, String databaseName, Log logger) { - this.initDirectory = initDirectory; - this.port = port; - this.databaseName = databaseName; - this.logger = logger; - } - - public void insertData() throws MojoExecutionException, MojoFailureException { - if (initDirectory.isDirectory()) { - Scanner scanner = null; - StringBuilder instructions = new StringBuilder(); - File[] files = initDirectory.listFiles(); - if (files != null && files.length > 0) { - logger.info("Folder " + initDirectory.getAbsolutePath() + " contains " + files.length + " file(s):"); - DB db = getConnectToMongoAndGetDatabase(); - for (File file : files) { - try { - 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(); - } - } - CommandResult result; - try { - result = db.doEval("(function() {" + instructions.toString() + "})();", new Object[0]); - } catch (MongoException e) { - 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"); - } - logger.info("Data initialized with success"); - } else { - logger.info("No data to initialize"); - } - } - } - - DB getConnectToMongoAndGetDatabase() throws MojoExecutionException { - if (databaseName == null || databaseName.trim().length() == 0) { - throw new MojoExecutionException("Database name is missing"); - } - - MongoClient mongoClient; - try { - mongoClient = new MongoClient("localhost", port); - } catch (UnknownHostException e) { - throw new MojoExecutionException("Unable to connect to mongo instance", e); - } - logger.info("Connected to MongoDB"); - return mongoClient.getDB(databaseName); - } -} diff --git a/src/main/java/com/github/joelittlejohn/embedmongo/InitDataMongoMojo.java b/src/main/java/com/github/joelittlejohn/embedmongo/InitDataMongoMojo.java new file mode 100644 index 0000000000000000000000000000000000000000..f20db308c965a03517d3d1e4397fd6cf4d3b1b65 --- /dev/null +++ b/src/main/java/com/github/joelittlejohn/embedmongo/InitDataMongoMojo.java @@ -0,0 +1,124 @@ +/** + * 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.github.joelittlejohn.embedmongo; + +import java.io.File; +import java.io.FileNotFoundException; +import java.net.UnknownHostException; +import java.util.Scanner; +import org.apache.maven.plugin.AbstractMojo; +import org.apache.maven.plugin.MojoExecutionException; +import org.apache.maven.plugin.MojoFailureException; +import com.mongodb.CommandResult; +import com.mongodb.DB; +import com.mongodb.MongoClient; +import com.mongodb.MongoException; + +/** + * When invoked, this goal connects to an instance of mongo and execute some instructions + * to add data. + * + * 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 { + + /** + * Folder that contains all scripts to execute. + * @parameter + * @required + */ + private File dataFolder; + + /** + * Optional. Specify the port only if you want have a different one from the default value. + * Default value is 27017. + * @parameter + */ + private int port; + + /** + * The name of the database where data will be stored. + * @parameter + * @required + */ + private String databaseName; + + @Override + public void execute() throws MojoExecutionException, MojoFailureException { + DB db = getConnectToMongoAndGetDatabase(); + + if (dataFolder.isDirectory()) { + Scanner scanner = null; + StringBuilder instructions = new StringBuilder(); + File[] files = dataFolder.listFiles(); + getLog().info("Folder " + dataFolder.getAbsolutePath() + " contains " + files.length + " file(s):"); + for (File file : files) { + try { + 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(); + } + } + CommandResult result; + try { + result = db.doEval("(function() {" + instructions.toString() + "})();", new Object[0]); + } 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 { + if (databaseName == null || databaseName.trim().length() == 0) { + throw new MojoExecutionException("Database name is missing"); + } + + MongoClient mongoClient; + try { + mongoClient = new MongoClient("localhost", port == 0 ? 27017 : port); + } catch (UnknownHostException e) { + throw new MojoExecutionException("Unable to connect to mongo instance", e); + } + getLog().info("Connected to MongoDB"); + return mongoClient.getDB(databaseName); + } + + protected InitDataMongoMojo setDataFolder(File dataFolder) { + this.dataFolder = dataFolder; + return this; + } + + protected InitDataMongoMojo setDatabaseName(String databaseName) { + this.databaseName = databaseName; + return this; + } +} diff --git a/src/main/java/com/github/joelittlejohn/embedmongo/StartEmbeddedMongoMojo.java b/src/main/java/com/github/joelittlejohn/embedmongo/StartEmbeddedMongoMojo.java index fb0ac3778bb48c2a8fb9be3492fd5efd45a90b69..d18124876fbd486e38ed736794d43dea87cde3bd 100644 --- a/src/main/java/com/github/joelittlejohn/embedmongo/StartEmbeddedMongoMojo.java +++ b/src/main/java/com/github/joelittlejohn/embedmongo/StartEmbeddedMongoMojo.java @@ -211,20 +211,6 @@ public class StartEmbeddedMongoMojo extends AbstractMojo { */ 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 @SuppressWarnings("unchecked") public void execute() throws MojoExecutionException, MojoFailureException { @@ -298,8 +284,6 @@ public class StartEmbeddedMongoMojo extends AbstractMojo { } catch (IOException e) { throw new MojoExecutionException("Unable to start the mongod", e); } - - new DataInitializer(initDirectory, port, databaseName, getLog()).insertData(); } /** diff --git a/src/test/java/com/github/joelittlejohn/embedmongo/DataInitializerTest.java b/src/test/java/com/github/joelittlejohn/embedmongo/InitDataMongoMojoTest.java similarity index 56% rename from src/test/java/com/github/joelittlejohn/embedmongo/DataInitializerTest.java rename to src/test/java/com/github/joelittlejohn/embedmongo/InitDataMongoMojoTest.java index ae7da20a23c483d91e6f725016de3a1048291972..c537e242b95e93bd117f14d6b7d02ff06b7dd40f 100644 --- a/src/test/java/com/github/joelittlejohn/embedmongo/DataInitializerTest.java +++ b/src/test/java/com/github/joelittlejohn/embedmongo/InitDataMongoMojoTest.java @@ -16,31 +16,19 @@ package com.github.joelittlejohn.embedmongo; 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.File; import java.io.FileWriter; import java.io.IOException; -import java.net.UnknownHostException; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; -import org.apache.maven.plugin.logging.Log; -import org.apache.maven.plugin.logging.SystemStreamLog; +import org.junit.Ignore; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; 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; -@RunWith(MockitoJUnitRunner.class) -public class DataInitializerTest { +public class InitDataMongoMojoTest { @Rule public TemporaryFolder createSchemaFolder = new TemporaryFolder(); @@ -48,44 +36,37 @@ public class DataInitializerTest { @Rule public ExpectedException thrown = ExpectedException.none(); - private final static int PORT = 27017; - private final static Log LOGGER = new SystemStreamLog(); private File rootFolder; private File rootFolderWithError; + @Ignore("Need an instance of MongoDB to pass") @Test public void should_execute_instructions() throws MojoFailureException, MojoExecutionException, IOException { initFolder(); try { - new DataInitializerForTest(rootFolder, PORT, "myDB", LOGGER).insertData(); + new InitDataMongoMojo().setDatabaseName("myDB").setDataFolder(rootFolder).execute(); } catch (Exception e) { - e.printStackTrace(); fail("Should not fail!"); } } @Test public void - should_fail_when_database_name_is_not_provided() throws MojoFailureException, MojoExecutionException, IOException { - initFolder(); - + should_fail_when_database_name_is_not_provided() throws MojoFailureException, MojoExecutionException { thrown.expect(MojoExecutionException.class); thrown.expectMessage("Database name is missing"); - new DataInitializer(rootFolder, PORT, null, LOGGER).insertData(); + new InitDataMongoMojo().execute(); } + @Ignore("Need an instance of MongoDB to pass") @Test public void should_fail_to_execute_instruction_with_error() throws IOException, MojoFailureException, MojoExecutionException { - DB database = mock(DB.class); 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.expectMessage("Error while executing instructions from file '" + rootFolderWithError.listFiles()[0].getName()); - new DataInitializerForTest(rootFolderWithError, PORT, "myDB", LOGGER, database).insertData(); + new InitDataMongoMojo().setDatabaseName("myDB").setDataFolder(rootFolderWithError).execute(); } private void initFolder() throws IOException { @@ -106,35 +87,16 @@ public class DataInitializerTest { private void initFolderWithError() throws IOException { File instructionsFile = createSchemaFolder.newFile(); - BufferedWriter reader = null; + BufferedWriter out = null; try { - reader = new BufferedWriter(new FileWriter(instructionsFile)); - reader.write("db.unknownInstruction();\n"); + out = new BufferedWriter(new FileWriter(instructionsFile)); + out.write("db.unknownInstruction();\n"); } finally { - if (reader != null) { - reader.close(); + if (out != null) { + out.close(); } } rootFolderWithError = instructionsFile.getParentFile(); 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; - } - } } diff --git a/src/test/java/com/github/joelittlejohn/embedmongo/PortUtilsTest.java b/src/test/java/com/github/joelittlejohn/embedmongo/PortUtilsTest.java index 63afc42bbc35d7e150d8acf3181a56ab159801d3..fcb9198a7d2208641ac6ffd93a77c4a9bb870885 100644 --- a/src/test/java/com/github/joelittlejohn/embedmongo/PortUtilsTest.java +++ b/src/test/java/com/github/joelittlejohn/embedmongo/PortUtilsTest.java @@ -22,6 +22,7 @@ import java.util.concurrent.CountDownLatch; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; + import org.junit.After; import org.junit.Test; diff --git a/src/test/java/com/mongodb/EmbedMongoClient.java b/src/test/java/com/mongodb/EmbedMongoClient.java deleted file mode 100644 index 9011c26bc4fb95c07a27b32a0fcdfd37aab691e2..0000000000000000000000000000000000000000 --- a/src/test/java/com/mongodb/EmbedMongoClient.java +++ /dev/null @@ -1,24 +0,0 @@ -/** - * 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 { - } -} diff --git a/src/test/java/com/mongodb/EmbedMongoDB.java b/src/test/java/com/mongodb/EmbedMongoDB.java deleted file mode 100644 index 73143464003100d29dda0d13f7ba5e998a5a170f..0000000000000000000000000000000000000000 --- a/src/test/java/com/mongodb/EmbedMongoDB.java +++ /dev/null @@ -1,85 +0,0 @@ -/** - * 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) { - - } -}