List of usage examples for com.mongodb CommandResult ok
public boolean ok()
From source file:com.nec.strudel.tkvs.store.tokumx.TokumxTransaction.java
License:Apache License
public TokumxTransaction(String gName, Key gKey, String dbname, DB db, TokumxReader kvs, DBCollection coll, TransactionProfiler prof) {//from ww w .j a v a2s . c o m super(gName, gKey, kvs, prof); db.requestStart(); this.db = db; //this.coll = coll; this.kvs = kvs; this.gName = gName; this.prof = prof; this.bulkwriter = coll.initializeOrderedBulkOperation(); DBObject cmd = new BasicDBObject("beginTransaction", 1).append("isolation", "serializable"); //Default is MVCC snapshot isolation level. // DBObject cmd = new BasicDBObject("beginTransaction", 1); CommandResult res = runCommand(db, cmd); if (!res.ok()) { LOGGER.warn("failed to begin transaction: " + res.getErrorMessage()); } }
From source file:com.nec.strudel.tkvs.store.tokumx.TokumxTransaction.java
License:Apache License
@Override public boolean commit() { prof.commitStart(gName);/* w w w . ja va 2s . com*/ if (kvs.isAborted()) { prof.commitFail(gName); return false; } boolean noop = true; for (CollectionBuffer b : buffers()) { Map<Key, Record> writes = b.getWrites(); String name = b.getName(); for (Map.Entry<Key, Record> e : writes.entrySet()) { Key key = e.getKey(); Record r = e.getValue(); String docName = key.toStringKey(name); //for put if (r != null) { //bulk or update? Tested: almost the same performance if (noop) { noop = false; } bulkwriter.find(new BasicDBObject(TokumxDbServer.DOCNAME, docName)).upsert().update( new BasicDBObject("$set", new BasicDBObject(TokumxDbServer.VALUENAME, r.toBytes()))); // coll.update(new // BasicDBObject(TokumxDbServer.docname, docName), // new BasicDBObject("$set", // new BasicDBObject(TokumxDbServer.valuename, // SerDeUtil.toBytes(r))), // true, // false); } else { // for delete if (noop) { noop = false; } bulkwriter.find(new BasicDBObject(TokumxDbServer.DOCNAME, docName)).remove(); //coll.remove(new BasicDBObject( //TokumxDbServer.docname, docName)); } } } if (!noop) { try { bulkwriter.execute(); } catch (com.mongodb.BulkWriteException e) { //This is tested to happen when //running multi-row transactions, //error message is: lock can not be granted LOGGER.warn("transaction failed due to BulkWriteException: " + e.getMessage()); prof.commitFail(gName); return false; } catch (@SuppressWarnings("deprecation") MongoException.Network e) { LOGGER.warn("transaction failed due to mongo network exception: " + e.getMessage()); prof.commitFail(gName); return false; } catch (MongoException e) { LOGGER.warn("transaction failed due to mongo exception: " + e.getMessage()); prof.commitFail(gName); return false; } } DBObject cmd = new BasicDBObject("commitTransaction", 1); CommandResult res = runCommand(db, cmd); if (res.ok()) { prof.commitSuccess(gName); db.requestDone(); return true; } else { prof.commitFail(gName); LOGGER.info("commit failed :" + res.getErrorMessage()); cmd = new BasicDBObject("rollbackTransaction", 1); runCommand(db, cmd); db.requestDone(); return false; } }
From source file:com.nesscomputing.mongo.MongoWriter.java
License:Apache License
protected void flushToMongo(final List<Callable<DBObject>> dbObjects) { LOG.trace("Starting write of %d elements...", dbObjects.size()); final DBCollection collection = dbCollection.get(); if (collection != null) { final WriteResult writeResult = collection.insert(Lists.transform(dbObjects, CALLABLE_FUNCTION), WriteConcern.NORMAL);//from ww w . ja va 2 s. c o m final CommandResult cmdResult = writeResult.getLastError(); if (cmdResult.ok()) { opsSent.addAndGet(dbObjects.size()); } else { LOG.warn("Command returned %s", cmdResult.getErrorMessage()); opsLost.addAndGet(dbObjects.size()); } LOG.trace("Wrote %d put ops to Mongo dbCollection %s.", dbObjects.size(), collectionName); } else { LOG.warn("dbCollection is null, probably shutting down!"); } }
From source file:com.stratio.connector.mongodb.core.engine.metadata.ShardUtils.java
License:Apache License
/** * Shard a collection./* w w w. j a v a 2 s . c om*/ * * @param mongoClient * the mongo client * @param tableMetadata * the table metadata * @throws ExecutionException * if an error exist when sharding the collection */ public static void shardCollection(MongoClient mongoClient, TableMetadata tableMetadata) throws ExecutionException { final String catalogName = tableMetadata.getName().getCatalogName().getName(); enableSharding(mongoClient, catalogName); DBObject shardKey = new BasicDBObject(); Map<String, Selector> options = SelectorOptionsUtils.processOptions(tableMetadata.getOptions()); ShardKeyType shardKeyType = getShardKeyType(options); String[] shardKeyFields = getShardKeyFields(options, shardKeyType); switch (shardKeyType) { case ASC: for (String field : shardKeyFields) { shardKey.put(field, 1); } break; case HASHED: shardKey.put(shardKeyFields[0], "hashed"); break; } // shard the collection with the key final DBObject cmd = new BasicDBObject("shardCollection", catalogName + "." + tableMetadata.getName().getName()); cmd.put("key", shardKey); CommandResult result = mongoClient.getDB("admin").command(cmd); if (!result.ok()) { LOGGER.error("Error executing" + cmd + " :" + result.getErrorMessage()); throw new ExecutionException(result.getErrorMessage()); } }
From source file:com.stratio.connector.mongodb.core.engine.metadata.ShardUtils.java
License:Apache License
/** * Enable sharding in the database.// ww w. j ava 2 s . co m * * @param mongoClient * the mongo client * @param databaseName * the database name * @throws ExecutionException * if an error exist when enabling sharding */ private static void enableSharding(MongoClient mongoClient, String databaseName) throws ExecutionException { DB db; db = mongoClient.getDB("admin"); DBObject enableShardingCommand = new BasicDBObject("enableSharding", databaseName); CommandResult result = db.command(enableShardingCommand); if (!result.ok() && !result.getErrorMessage().equals("already enabled")) { LOGGER.error("Error executing" + enableShardingCommand + " :" + result.getErrorMessage()); throw new ExecutionException(result.getErrorMessage()); } }
From source file:com.syncleus.maven.plugins.mongodb.StartMongoMojo.java
License:Open Source Community License
private void processScriptFile(final DB db, final File scriptFile) throws MojoExecutionException { Scanner scanner = null;//from w w w. ja v a 2s. c om final StringBuilder instructions = new StringBuilder(); try { scanner = new Scanner(scriptFile); while (scanner.hasNextLine()) { instructions.append(scanner.nextLine()).append("\n"); } } catch (final FileNotFoundException e) { throw new MojoExecutionException("Unable to find file with name '" + scriptFile.getName() + "'", e); } finally { if (scanner != null) { scanner.close(); } } final CommandResult result; try { final String evalString = "(function() {" + instructions.toString() + "})();"; result = db.doEval(evalString, new Object[0]); } catch (final MongoException e) { throw new MojoExecutionException("Unable to execute file with name '" + scriptFile.getName() + "'", e); } if (!result.ok()) { getLog().error("- file " + scriptFile.getName() + " parsed with error: " + result.getErrorMessage()); throw new MojoExecutionException("Error while executing instructions from file '" + scriptFile.getName() + "': " + result.getErrorMessage(), result.getException()); } getLog().info("- file " + scriptFile.getName() + " parsed successfully"); }
From source file:de.otto.mongodb.profiler.collection.DefaultCollectionProfiler.java
License:Apache License
protected void newSample(DefaultCollectionProfile profile) { final DBCollection collection = database.getCollection(profile.getCollectionName()); final CommandResult result = collection.getStats(); if (result.ok()) { profile.add(result);/*from w w w . j a v a 2s .com*/ } else { if ("ns not found".equals(result.getErrorMessage())) { profile.reset(); } } }
From source file:dk.au.cs.karibu.backend.mongo.MongoDBStorage.java
License:Apache License
/** * {@inheritDoc}/*from w w w . j ava2s.c o m*/ */ @Override public void process(String producerCode, BasicDBObject dbo) { // get a collection object to work with coll = database.getCollection(producerCode); // Insert it into Mongo WriteResult writeResult = coll.insert(dbo); CommandResult err = writeResult.getCachedLastError(); if (!err.ok()) { log.error("MongoDB insert failed with result: " + err.toString()); } }
From source file:dk.au.cs.karibu.backend.mongo.MongoDBStorage.java
License:Apache License
@Override public void store(BasicDBObject dbo) { // get the karibu statistics collection object coll = database.getCollection(KARIBU_STATISTIC_COLLECTION_NAME); // Insert it into Mongo WriteResult writeResult = coll.insert(dbo); CommandResult err = writeResult.getCachedLastError(); if (!err.ok()) { log.error("MongoDB insert failed with result: " + err.toString()); }//from ww w.ja v a 2s . c o m // System.err.println("Will store "+dbo); }
From source file:eu.eubrazilcc.lvl.storage.mongodb.MongoDBConnector.java
License:EUPL
/** * Returns the objects in the collection that are within the specified distance (in meters) * from the center point specified by the coordinates (in WGS84). The objects are sorted * from nearest to farthest.//from ww w. ja v a2 s. co m * @param collection - collection whose objects are counted * @param longitude - longitude in WGS84 coordinate reference system (CRS) * @param latitude - latitude in WGS84 coordinate reference system (CRS) * @param maxDistance - limits the results to those objects that fall within the specified * distance (in meters) from the center point * @return the objects that are within the specified distance from the center point, sorted * from nearest to farthest */ public BasicDBList geoNear(final String collection, final double longitude, final double latitude, final double maxDistance) { checkArgument(isNotBlank(collection), "Uninitialized or invalid collection"); final DB db = client().getDB(CONFIG_MANAGER.getDbName()); final BasicDBObject query = new BasicDBObject("geoNear", collection) .append("near", new BasicDBObject("type", "Point").append("coordinates", new double[] { longitude, latitude })) .append("maxDistance", maxDistance).append("spherical", true).append("uniqueDocs", true) .append("num", Integer.MAX_VALUE); LOGGER.trace("geoNear query: " + JSON.serialize(query)); final CommandResult cmdResult = db.command(query); checkState(cmdResult.ok(), "geoNear search failed"); return (BasicDBList) cmdResult.get("results"); }