fongo : a really simple mongorestore in only 30 SLOC !

If you use a fake mongodb like ‘fongo’ and you want to import a zip dump into fongo, here is a way to do that :

public void restoreDump(String filePath) throws RestoreFailedException {
ZipFile zipFile;
try {
zipFile = new ZipFile(filePath);
} catch (IOException e1) {
throw new RestoreFailedException (e1);
}
Enumeration< ? extends ZipArchiveEntry> entries = zipFile.getEntries();
DB currentDB = null;
while (entries.hasMoreElements()) {
ZipArchiveEntry entry = entries.nextElement();
if ("dump/".equals(entry.getName())) {
continue;
}
if (entry.isDirectory()) {
String[] pathParts = entry.getName().split ("/");
String dbName = pathParts [pathParts.length - 1];
currentDB = FongoDBTest.fongo.getMongo ().getDB(dbName);
} else if (entry.getName().endsWith(".bson")) {
String currentCollectionName = entry.getName().substring(
entry.getName().lastIndexOf('/') + 1,
entry.getName().lastIndexOf(".bson"));
DBCollection currentCollection = currentDB.createCollection(
currentCollectionName, new BasicDBObject());
BasicBSONDecoder bsonDecoder = new BasicBSONDecoder();
BSONObject bson;
try {
InputStream in = zipFile.getInputStream(entry);
while ((bson = bsonDecoder.readObject(in)) != null){
BasicDBObject dbObject = new BasicDBObject();
dbObject.putAll(bson);
currentCollection.insert(dbObject);
}
} catch (IOException e) {
//I think there will be some padding that will throw this exception anyway.
}
}
}
try {
zipFile.close ();
} catch (IOException e) {
throw new RestoreFailedException (e1);
}
}

The fongo object can be instantiated using this lines of code :

LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
//set debug logs off
lc.getLogger (FongoDBCollection.class).setLevel (Level.ERROR);
lc.getLogger (ExpressionParser.class).setLevel (Level.ERROR);
lc.getLogger (FongoDB.class).setLevel (Level.ERROR);
FongoDBTest.fongo = new Fongo ("unit test server");

Then you will not print out a big amount of useless debug logs.