// @see http://nesbot.com/2011/11/28/play-2-morphia-logging-error
MorphiaLoggerFactory.reset();
MorphiaLoggerFactory.registerLogger(SLF4JLogrImplFactory.class);
try {
Configuration morphiaConf = Configuration.root().getConfig(ConfigKey.PREFIX);
if (morphiaConf == null) {
throw Configuration.root().reportError(ConfigKey.PREFIX, "Missing Morphia configuration", null);
}
MorphiaLogger.debug(morphiaConf);
String mongoURIstr = morphiaConf.getString(ConfigKey.DB_MONGOURI.getKey());
String seeds = morphiaConf.getString(ConfigKey.DB_SEEDS.getKey());
String dbName = null;
String username = null;
String password = null;
if(StringUtils.isNotBlank(mongoURIstr)) {
MongoURI mongoURI = new MongoURI(mongoURIstr);
mongo = connect(mongoURI);
dbName = mongoURI.getDatabase();
username = mongoURI.getUsername();
if(mongoURI.getPassword() != null) {
password = new String(mongoURI.getPassword());
}
} else if (StringUtils.isNotBlank(seeds)) {
mongo = connect(seeds);
} else {
mongo = connect(
morphiaConf.getString(ConfigKey.DB_HOST.getKey()),
morphiaConf.getString(ConfigKey.DB_PORT.getKey()));
}
if (StringUtils.isBlank(dbName)) {
dbName = morphiaConf.getString(ConfigKey.DB_NAME.getKey());
if (StringUtils.isBlank(dbName)) {
throw morphiaConf.reportError(ConfigKey.DB_NAME.getKey(), "Missing Morphia configuration", null);
}
}
morphia = new Morphia();
// To prevent problem during hot-reload
if (application.isDev()) {
morphia.getMapper().getOptions().objectFactory = new PlayCreator();
}
// Configure validator
new ValidationExtension(morphia);
//Check if credentials parameters are present
if (StringUtils.isBlank(username)) {
username = morphiaConf.getString(ConfigKey.DB_USERNAME.getKey());
}
if (StringUtils.isBlank(password)) {
password = morphiaConf.getString(ConfigKey.DB_PASSWORD.getKey());
}
if (StringUtils.isNotBlank(username) ^ StringUtils.isNotBlank(password)) {
throw morphiaConf.reportError(ConfigKey.DB_NAME.getKey(), "Missing username or password", null);
}
// Create datastore
if (StringUtils.isNotBlank(username) && StringUtils.isNotBlank(password)) {
ds = morphia.createDatastore(mongo, dbName, username, password.toCharArray());
} else {
ds = morphia.createDatastore(mongo, dbName);
}
MorphiaLogger.debug("Datastore [%s] created", dbName);
// Create GridFS
String uploadCollection = morphiaConf.getString(ConfigKey.COLLECTION_UPLOADS.getKey());
if (StringUtils.isBlank(dbName)) {
uploadCollection = "uploads";
MorphiaLogger.warn("Missing Morphia configuration key [%s]. Use default value instead [%s]", ConfigKey.COLLECTION_UPLOADS, "uploads");
}
gridfs = new GridFS(ds.getDB(), uploadCollection);