List of usage examples for com.mongodb CommandResult ok
public boolean ok()
From source file:ezbake.deployer.publishers.database.MongoDBDatabaseSetup.java
License:Apache License
@Override public List<ArtifactDataEntry> setupDatabase(DeploymentArtifact artifact, Properties configuration, EzSecurityToken callerToken) throws DeploymentException { MongoHelper mongoHelper = new MongoHelper(configuration); MongoConfigurationHelper mongoConfiguration = mongoHelper.getMongoConfigurationHelper(); //Setup new mongo properties String databaseName = ArtifactHelpers.getNamespace(artifact); String userName = databaseName + "_user"; String password = new BigInteger(130, random).toString(32); //Connect to Mongo DB Mongo client = getMongoClient(mongoHelper); try {/*from ww w . ja va 2s . c om*/ //If user exists, re-generate the password and reset the password DBObject cmd = new BasicDBObject("updateUser", userName); cmd.put("pwd", password); cmd.put("roles", DBRole); CommandResult result = client.getDB(databaseName).command(cmd); if (!result.ok()) { logger.warn("Failed to update mongo user. {}. Attempting to add", result.getErrorMessage()); //If user doesn't exist, create new Mongo DB User/Password/Database unique for this application cmd = new BasicDBObject("createUser", userName); cmd.put("pwd", password); cmd.put("roles", DBRole); result = client.getDB(databaseName).command(cmd); result.throwOnError(); } } finally { client.close(); } //Create a mongo.properties file with mongo host, username, password(hashed), and database Map<String, String> valuesMap = Maps.newHashMap(); valuesMap.put(EzBakePropertyConstants.MONGODB_DB_NAME, databaseName); valuesMap.put(EzBakePropertyConstants.MONGODB_HOST_NAME, mongoConfiguration.getMongoDBHostName()); valuesMap.put(EzBakePropertyConstants.MONGODB_USE_SSL, Boolean.toString(mongoConfiguration.useMongoDBSSL())); Map<String, String> encryptedValuesMap = Maps.newHashMap(); encryptedValuesMap.put(EzBakePropertyConstants.MONGODB_USER_NAME, userName); encryptedValuesMap.put(EzBakePropertyConstants.MONGODB_PASSWORD, password); String connectionString = String.format("mongodb://%s:%s@%s/%s?ssl=%b", userName, password, mongoConfiguration.getMongoDBHostName(), databaseName, mongoConfiguration.useMongoDBSSL()); encryptedValuesMap.put(EzBakePropertyConstants.MONGODB_CONNECTION_STRING, connectionString); String properties = Joiner.on('\n').withKeyValueSeparator("=").join(valuesMap); String encryptedProps = Joiner.on('\n').withKeyValueSeparator("=").join(encryptedValuesMap); List<ArtifactDataEntry> entries = Lists.newArrayList(); entries.add(Utilities.createConfCertDataEntry(MONGODB_PROPERTIES_FILE_NAME, properties.getBytes())); entries.add(Utilities.createConfCertDataEntry(ENCRYPTED_MONGODB_PROPERTIES_FILE_NAME, encryptedProps.getBytes())); return entries; }
From source file:fr.cnes.sitools.datasource.mongodb.ActivationDataSourceResource.java
License:Open Source License
/** * Testing connections/* w w w . j ava 2s .c o m*/ * * @param ds * the DataSource to test * @param trace * a {@link List} of String to store the trace of the test. Can be null * @return Representation results of the connection test. */ public boolean testDataSourceConnection(MongoDBDataSource ds, List<String> trace) { Boolean result = Boolean.TRUE; Mongo mongo = null; try { do { trace(trace, "Test mongo data source connection ..."); try { mongo = new Mongo(ds.getUrl(), ds.getPortNumber()); } catch (Exception e) { result = false; getMongoDBDataSourceAdministration().getLogger().info(e.getMessage()); trace(trace, "Load driver class failed. Cause: " + e.getMessage()); break; } try { // check if the database exists // List<String> databases = mongo.getDatabaseNames(); // if (!databases.contains(ds.getDatabaseName())) { // result = false; // getMongoDBDataSourceAdministration().getLogger().info("Database does not exist"); // trace.add("Database " + ds.getDatabaseName() + " does not exist"); // break; // } DB db = mongo.getDB(ds.getDatabaseName()); // if no user and password given lets authenticate on the database if (ds.isAuthentication() && !db.isAuthenticated() && !db.authenticate(ds.getUserLogin(), ds.getUserPassword().toCharArray())) { result = false; getMongoDBDataSourceAdministration().getLogger().info("Authentication failed"); trace(trace, "Authentication failed"); break; } // try to get the stats of the database to check whether or not the database is accessible CommandResult cmd = db.getStats(); if (!cmd.ok()) { result = false; getMongoDBDataSourceAdministration().getLogger() .info("Error connecting to the database " + cmd); trace(trace, "Error connecting to the database " + cmd); break; } trace(trace, "Get connection to the database : OK"); } catch (Exception e) { result = false; getMongoDBDataSourceAdministration().getLogger().info(e.getMessage()); trace(trace, "Get connection to the database failed. Cause: " + e.getMessage()); break; } } while (false); } finally { if (mongo != null) { mongo.close(); } } return result; }
From source file:net.handle.server.MongoDBHandleStorage.java
License:Open Source License
/** * Copies the database to another://w w w. j a va2 s .co m * checkpoint_[database name] * * @throws HandleException */ public void checkpointDatabase() throws HandleException { final String checkpoint = database + "_checkpoint_" + new Date().getTime(); final BasicDBObject command = new BasicDBObject(); command.put("copydb", 1); command.put("fromdb", database); command.put("todb", checkpoint); final DB db = mongo.getDB("admin"); final CommandResult result = db.command(command); if (!result.ok()) { throw new HandleException(HandleException.SERVER_ERROR, "The checkpoint action failed:\n" + result.getErrorMessage()); } }
From source file:net.tooan.ynpay.third.mongodb.BuguAggregation.java
License:Apache License
public Iterable<DBObject> results() throws AggregationException { int size = pipeline.size(); if (size <= 0) { throw new AggregationException("Empty pipeline in aggregation!"); }/*from w w w .ja v a2 s . c o m*/ AggregationOutput output = null; if (size == 1) { output = coll.aggregate(pipeline.get(0)); } else { DBObject firstOp = pipeline.get(0); List<DBObject> subList = pipeline.subList(1, size); DBObject[] arr = subList.toArray(new DBObject[size - 1]); output = coll.aggregate(firstOp, arr); } CommandResult cr = output.getCommandResult(); if (!cr.ok()) { throw new AggregationException(cr.getErrorMessage()); } return output.results(); }
From source file:net.ymate.platform.persistence.mongodb.support.MongoDBHelper.java
License:Apache License
public Iterable<DBObject> mapReduce(String collectionName, String map, String reduce, DBObject query) throws OperatorException { MapReduceOutput _output = getCollection(collectionName).mapReduce(map, reduce, null, OutputType.INLINE, query);/* ww w.j av a 2 s . c o m*/ CommandResult _result = _output.getCommandResult(); if (!_result.ok()) { throw new OperatorException(_result.getErrorMessage()); } return _output.results(); }
From source file:net.ymate.platform.persistence.mongodb.support.MongoDBHelper.java
License:Apache License
public Iterable<DBObject> mapReduce(String collectionName, String map, String reduce, String outputTarget, OutputType type, OrderBy order, int pageNumber, int pageSize, DBObject query) throws OperatorException { MapReduceOutput _output = getCollection(collectionName).mapReduce(map, reduce, outputTarget, type, query); CommandResult _result = _output.getCommandResult(); if (!_result.ok()) { throw new OperatorException(_result.getErrorMessage()); }//from w w w .j a v a2 s.c o m DBCollection _collection = _output.getOutputCollection(); DBCursor _cursor = null; if (order != null) { _cursor = _collection.find().sort(order.toDBObject()); } else { _cursor = _collection.find(); } if (pageNumber > 0 && pageSize > 0) { _cursor.skip((pageNumber - 1) * pageSize).limit(pageSize); } List<DBObject> _results = new ArrayList<DBObject>(); for (Iterator<DBObject> _it = _cursor.iterator(); _it.hasNext();) { _results.add(_it.next()); } return _results; }
From source file:org.apache.camel.component.mongodb.MongoDbProducer.java
License:Apache License
private void processAndTransferWriteResult(WriteResult result, Exchange exchange) { // if invokeGetLastError is set, or a WriteConcern is set which implicitly calls getLastError, then we have the chance to populate // the MONGODB_LAST_ERROR header, as well as setting an exception on the Exchange if one occurred at the MongoDB server if (endpoint.isInvokeGetLastError() || (endpoint.getWriteConcern() != null ? endpoint.getWriteConcern().callGetLastError() : false)) { CommandResult cr = result.getCachedLastError() == null ? result.getLastError() : result.getCachedLastError(); exchange.getOut().setHeader(MongoDbConstants.LAST_ERROR, cr); if (!cr.ok()) { exchange.setException(MongoDbComponent.wrapInCamelMongoDbException(cr.getException())); }/* ww w.ja va2 s .co m*/ } // determine where to set the WriteResult: as the OUT body or as an IN message header if (endpoint.isWriteResultAsHeader()) { exchange.getOut().setHeader(MongoDbConstants.WRITERESULT, result); } else { exchange.getOut().setBody(result); } }
From source file:org.craftercms.commons.mongo.MongoScriptRunner.java
License:Open Source License
private void runScript(DB db, Resource scriptPath) throws MongoDataException { String script;/*from w ww. j ava 2 s. c o m*/ try { if (scriptPath.getFile().isDirectory()) { final File[] files = scriptPath.getFile().listFiles(new FilenameFilter() { @Override public boolean accept(final File dir, final String name) { return name.toLowerCase().endsWith(".js"); } }); List<File> orderFiles = Arrays.asList(files); Collections.sort(orderFiles, new Comparator<File>() { @Override public int compare(final File o1, final File o2) { return o1.getName().compareTo(o2.getName()); } }); logger.debug("Directory {} files to exec {}", scriptPath.getFile(), orderFiles); for (File file : orderFiles) { runScript(db, new FileSystemResource(file.getPath())); } } else { logger.debug("Running Script {}", scriptPath.getURI()); try { script = IOUtils.toString(scriptPath.getInputStream(), "UTF-8"); } catch (IOException e) { throw new MongoDataException("Unable to read script at " + scriptPath.getURI().toString()); } CommandResult result = db.doEval(script); if (!result.ok()) { Exception ex = result.getException(); throw new MongoDataException( "An error occurred while running script at " + scriptPath.getURI().toString(), ex); } logger.info("Mongo script at {} executed successfully", scriptPath.getDescription()); } } catch (IOException ex) { logger.error("Unable to read files from {}", ex); } }
From source file:org.eclipse.linuxtools.tmf.totalads.dbms.DBMS.java
License:Open Source License
/** * Insert an object's field with only one level of nesting. The object's class should only * have public data fields when calling this function. For example, create a class A{String b; Integer b}, * assign values after instantiating the object and pass it to the function * @param record Object from which to extract fields and values * @param database Database name//from w w w. j a v a 2 s. c o m * @param collection Collection name * @throws TotalADSDBMSException, * @throws IllegalAccessException * @throws IllegalAccessException */ public void insert(Object record, String database, String collection) throws TotalADSDBMSException, IllegalAccessException, IllegalAccessException { WriteResult writeRes = null; String exception = ""; DB db = mongoClient.getDB(database); DBCollection coll = db.getCollection(collection); BasicDBObject document = new BasicDBObject(); extractKeysAndValuesfromTheObject(record, document); try { writeRes = coll.insert(document); } catch (MongoException e) { exception = "Caught MongoException cause: " + e.getMessage(); } CommandResult cmdResult = writeRes.getLastError(); if (!cmdResult.ok()) exception += "\n error : " + cmdResult.getErrorMessage(); if (!exception.isEmpty()) throw new TotalADSDBMSException(exception); }
From source file:org.eclipse.linuxtools.tmf.totalads.dbms.DBMS.java
License:Open Source License
/** * Inserts or updates (if already exists) an object in the form of JSON representation into the database. Any kind of complex * data structure can be converted to JSON using gson library and passed to this function * @param database Database name//www. j av a2s . com * @param jsonObject JSON Object * @param collection collection name */ public void insertOrUpdateUsingJSON(String database, JsonObject keytoSearch, JsonObject jsonObjectToUpdate, String collection) throws TotalADSDBMSException { DB db = mongoClient.getDB(database); DBCollection coll = db.getCollection(collection); BasicDBObject docToUpdate = (BasicDBObject) JSON.parse(jsonObjectToUpdate.toString()); BasicDBObject keyToSearch = (BasicDBObject) JSON.parse(keytoSearch.toString()); WriteResult writeRes = coll.update(keyToSearch, docToUpdate, true, false); CommandResult cmdResult = writeRes.getLastError(); if (!cmdResult.ok()) throw new TotalADSDBMSException("Error : " + cmdResult.getErrorMessage()); }