diff --git a/.gitignore b/.gitignore
index 467ead37593a032e199b82af8af39a8522da4129..527df7695964f22e1d0158194faa361e4ec475b5 100644
--- a/.gitignore
+++ b/.gitignore
@@ -8,6 +8,10 @@
.project
.settings
+# IntelliJ Idea files #
+*.iml
+.idea/
+
# Maven derived files
target
*.class
diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md
index 5329b4befa168f577057878cfea1698cdf9310ae..97c8363f6e524cf4aef349a94d8488c8be2a99f3 100644
--- a/CONTRIBUTORS.md
+++ b/CONTRIBUTORS.md
@@ -10,4 +10,5 @@
* Alexander Dietrich <dietrich@adobe.com>
* Brandon Chapman <bchapman@bridge2solutions.com>
* Carlos Ortiz <carlos.ortiz@craftercms.org>
-* Pablo Diaz <padilo@gmail.com>
\ No newline at end of file
+* Pablo Diaz <padilo@gmail.com>
+* Pierre-Jean Vardanega <pierrejean.vardanega@gmail.com>
diff --git a/pom.xml b/pom.xml
index d668feeef102a276822eef31722fd2108727ded9..f17e491aabe94b010b29c523f98a467467a96c76 100644
--- a/pom.xml
+++ b/pom.xml
@@ -122,12 +122,24 @@
<artifactId>de.flapdoodle.embed.mongo</artifactId>
<version>1.46.0</version>
</dependency>
+ <dependency>
+ <groupId>org.mongodb</groupId>
+ <artifactId>mongo-java-driver</artifactId>
+ <version>2.13.0</version>
+ </dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit-dep</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
+
+ <dependency>
+ <groupId>org.mockito</groupId>
+ <artifactId>mockito-core</artifactId>
+ <version>1.10.19</version>
+ <scope>test</scope>
+ </dependency>
</dependencies>
<profiles>
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..e7a81a66b764fa746300977f92ae8a1fdb82c155
--- /dev/null
+++ b/src/main/java/com/github/joelittlejohn/embedmongo/InitDataMongoMojo.java
@@ -0,0 +1,123 @@
+/**
+ * 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 scriptsDirectory;
+
+ /**
+ * 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;
+
+ public InitDataMongoMojo() {
+ }
+
+ InitDataMongoMojo(File scriptsDirectory, int port, String databaseName) {
+ this.scriptsDirectory = scriptsDirectory;
+ this.port = port;
+ this.databaseName = databaseName;
+ }
+
+ @Override
+ public void execute() throws MojoExecutionException, MojoFailureException {
+ DB db = connectToMongoAndGetDatabase();
+
+ if (scriptsDirectory.isDirectory()) {
+ Scanner scanner = null;
+ StringBuilder instructions = new StringBuilder();
+ File[] files = scriptsDirectory.listFiles();
+ getLog().info("Folder " + scriptsDirectory.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");
+ }
+ }
+
+ DB connectToMongoAndGetDatabase() 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);
+ }
+}
diff --git a/src/test/java/com/github/joelittlejohn/embedmongo/InitDataMongoMojoTest.java b/src/test/java/com/github/joelittlejohn/embedmongo/InitDataMongoMojoTest.java
new file mode 100644
index 0000000000000000000000000000000000000000..e5f23da5acf765c0659333b234e88c300e9a5d3b
--- /dev/null
+++ b/src/test/java/com/github/joelittlejohn/embedmongo/InitDataMongoMojoTest.java
@@ -0,0 +1,137 @@
+/**
+ * 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 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.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 InitDataMongoMojoTest {
+
+ @Rule
+ public TemporaryFolder createSchemaFolder = new TemporaryFolder();
+
+ @Rule
+ public ExpectedException thrown = ExpectedException.none();
+
+ private final static int PORT = 27017;
+ private File rootFolder;
+ private File rootFolderWithError;
+
+ @Test public void
+ should_execute_instructions() throws MojoFailureException, MojoExecutionException, IOException {
+ initFolder();
+ try {
+ new InitDataMongoMojoForTest(rootFolder, PORT, "myDB").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();
+
+ thrown.expect(MojoExecutionException.class);
+ thrown.expectMessage("Database name is missing");
+
+ new InitDataMongoMojo(rootFolder, PORT, null).execute();
+ }
+
+ @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 InitDataMongoMojoForTest(rootFolderWithError, PORT, "myDB", database).execute();
+ }
+
+ private void initFolder() throws IOException {
+ File instructionsFile = createSchemaFolder.newFile();
+ BufferedWriter out = null;
+ try {
+ out = new BufferedWriter(new FileWriter(instructionsFile));
+ out.write("db.dropDatabase();\n");
+ out.write("db.users.createIndex( { email: 1 }, { unique: true } );\n");
+ } finally {
+ if (out != null) {
+ out.close();
+ }
+ }
+ rootFolder = instructionsFile.getParentFile();
+ rootFolder.mkdir();
+ }
+
+ private void initFolderWithError() throws IOException {
+ File instructionsFile = createSchemaFolder.newFile();
+ BufferedWriter reader = null;
+ try {
+ reader = new BufferedWriter(new FileWriter(instructionsFile));
+ reader.write("db.unknownInstruction();\n");
+ } finally {
+ if (reader != null) {
+ reader.close();
+ }
+ }
+ rootFolderWithError = instructionsFile.getParentFile();
+ rootFolderWithError.mkdir();
+ }
+
+ static class InitDataMongoMojoForTest extends InitDataMongoMojo {
+
+ private final DB database;
+
+ public InitDataMongoMojoForTest(File dataFolder, int port, String databaseName) throws UnknownHostException {
+ this(dataFolder, port, databaseName, new EmbedMongoDB("myDB"));
+ }
+
+ public InitDataMongoMojoForTest(File dataFolder, int port, String databaseName, DB database) {
+ super(dataFolder, port, databaseName);
+ this.database = database;
+ }
+
+ @Override
+ DB connectToMongoAndGetDatabase() throws MojoExecutionException {
+ return database;
+ }
+ }
+}
diff --git a/src/test/java/com/mongodb/EmbedMongoClient.java b/src/test/java/com/mongodb/EmbedMongoClient.java
new file mode 100644
index 0000000000000000000000000000000000000000..9011c26bc4fb95c07a27b32a0fcdfd37aab691e2
--- /dev/null
+++ b/src/test/java/com/mongodb/EmbedMongoClient.java
@@ -0,0 +1,24 @@
+/**
+ * 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
new file mode 100644
index 0000000000000000000000000000000000000000..73143464003100d29dda0d13f7ba5e998a5a170f
--- /dev/null
+++ b/src/test/java/com/mongodb/EmbedMongoDB.java
@@ -0,0 +1,85 @@
+/**
+ * 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) {
+
+ }
+}