List of usage examples for com.mongodb CommandResult ok
public boolean ok()
From source file:org.pentaho.mongo.MongoUtils.java
License:Open Source License
/** * Get the set of collections for a MongoDB database. * //from w ww . j av a2s .co m * @param meta * Input meta with connection information * @param varSpace * Variable space to substitute variables with * @param dB * Name of database * @param username * Username to request collections on behalf of * @param realPass * Password of user * @return Set of collections in the database requested. * @throws KettleException * If an error occurs. */ public static Set<String> getCollectionsNames(final MongoDbInputMeta meta, final TransMeta varSpace, final String dB, final String username, final String realPass) throws KettleException { try { AuthContext context = MongoUtils.createAuthContext(meta, varSpace); return context.doAs(new PrivilegedExceptionAction<Set<String>>() { @Override public Set<String> run() throws Exception { MongoClient conn = null; try { conn = MongoDbInputData.initConnection(meta, varSpace, null); DB theDB = conn.getDB(dB); if (!Const.isEmpty(username) || !Const.isEmpty(realPass)) { CommandResult comResult = theDB.authenticateCommand(username, realPass.toCharArray()); if (!comResult.ok()) { throw new Exception( BaseMessages.getString(PKG, "MongoDbInput.ErrorAuthenticating.Exception", //$NON-NLS-1$ comResult.getErrorMessage())); } } return theDB.getCollectionNames(); } finally { if (conn != null) { conn.close(); } } } }); } catch (PrivilegedActionException ex) { if (ex.getCause() instanceof KettleException) { throw (KettleException) ex.getCause(); } else { throw new KettleException( "Unable to retrieve collection names for database " + dB + " from MongoDB", ex.getCause()); } } }
From source file:org.sipfoundry.commons.mongo.MongoUtil.java
License:Open Source License
/** * Running java script commands. With throw MongoCommandException if * command wasn't successful.// w w w . j a va2 s . co m * * Example: * BasicBSONObject ret = MongoUtil.runCommand(m_db, "rs.config()"); */ public static BasicBSONObject runCommand(DB db, String command) { CommandResult status = db.doEval(command); if (!status.ok()) { String msg = format("Cannot run command '%s'. Result '%s'.", command, status); throw new MongoCommandException(msg); } return getObject(status, "retval"); }
From source file:org.slc.sli.ingestion.util.MongoCommander.java
License:Apache License
/** * get list of the shards/*from w w w .java 2 s .co m*/ * @param dbConn * @return */ private static List<String> getShards(DB dbConn) { List<String> shards = new ArrayList<String>(); DBObject listShardsCmd = new BasicDBObject("listShards", 1); CommandResult res = dbConn.command(listShardsCmd); if (!res.ok()) { LOG.error("Error getting shards for {}: {}", dbConn, res.getErrorMessage()); } BasicDBList listShards = (BasicDBList) res.get("shards"); //Only get shards for sharding mongo if (listShards != null) { ListIterator<Object> iter = listShards.listIterator(); while (iter.hasNext()) { BasicDBObject shard = (BasicDBObject) iter.next(); shards.add(shard.getString(ID)); } } return shards; }
From source file:org.slc.sli.ingestion.util.MongoCommander.java
License:Apache License
/** * Move chunks of a collection to different shards * @param collection : the collection to be split * @param shards : list of all shards/*from ww w . j av a 2 s.c o m*/ * @param dbConn * @return Error description, or null if no errors */ private static String moveChunks(String collection, List<String> shards, DB dbConn) { int numShards = shards.size(); if (numShards == 0) { return null; } // // Fraction of 256 that each block will occupy // int charOffset = 256 / numShards; // // Keep list of the start point for each chunk, so we can move the chunk after creating them // List<String> moveStrings = new ArrayList<String>(); moveStrings.add("$minkey"); // // We want one chunk per shard, so we need to do numShards-1 splits // Calculate where to split and do it // for (int shard = 1; shard <= numShards - 1; shard++) { // // Split points based on the fraction of 256 that each chunk should occupy // String splitString = Integer.toHexString(charOffset * shard); moveStrings.add(splitString); CommandResult result = dbConn.command(buildSplitCommand(collection, splitString)); if (!result.ok()) { LOG.error("Error splitting chunk in {}: {}", collection, result.getErrorMessage()); return result.getErrorMessage(); } } // // Move each chunk to the correct shard // One of these moves will get a "that chunk is already on that shard" error // which is ok // for (int index = 0; index < numShards; index++) { DBObject moveCommand = new BasicDBObject(); moveCommand.put("moveChunk", collection); moveCommand.put("find", new BasicDBObject(ID, moveStrings.get(index))); moveCommand.put("to", shards.get(index)); CommandResult result = dbConn.command(moveCommand); if (!result.ok()) { if (!result.getErrorMessage().equals("that chunk is already on that shard")) { LOG.error("Error moving chunk in {}: {}", collection, result.getErrorMessage()); return result.getErrorMessage(); } } } return null; }
From source file:org.slc.sli.ingestion.util.MongoCommander.java
License:Apache License
/** * set the state of balancer./*from w ww . j av a 2 s . c o m*/ * * @param dbConn * @param state * @return Error description, or null if no errors */ private static String setBalancerState(DB dbConn, boolean state) { DBObject balancer = new BasicDBObject(ID, "balancer"); DBObject updateObj = new BasicDBObject(); String stopped = state ? "false" : "true"; updateObj.put("$set", new BasicDBObject("stopped", stopped)); WriteResult wresult = dbConn.getSisterDB("config").getCollection("settings").update(balancer, updateObj, true, false); if (wresult != null) { CommandResult result = wresult.getLastError(); if (!result.ok()) { LOG.error("Error setting balancer state to {}: {}", state, result.getErrorMessage()); return result.getErrorMessage(); } } return null; }
From source file:org.slc.sli.ingestion.util.MongoCommander.java
License:Apache License
/** * Pre-split database/*from ww w.ja v a2 s . c o m*/ * @param shardCollections: the set of collections to be split * @param dbName * @param mongoTemplate * @return Error description, or null if no errors */ public static String preSplit(Set<String> shardCollections, String dbName, MongoTemplate mongoTemplate) { DB dbConn = mongoTemplate.getDb().getSisterDB("admin"); //Don't do anything if it is non-sharded List<String> shards = getShards(dbConn); if (shards.size() == 0) { return null; } //set balancer off String sresult = setBalancerState(dbConn, false); if (sresult != null) { return sresult; } // Enable sharding for this database DBObject enableShard = new BasicDBObject("enableSharding", dbName); CommandResult result = dbConn.command(enableShard); if (!result.ok()) { LOG.error("Error enabling sharding on {}: {}", dbConn, result.getErrorMessage()); return result.getErrorMessage(); } for (String coll : shardCollections) { String collection = dbName + "." + coll; // Enable sharding for this collection, sharding on _id DBObject shardColl = new BasicDBObject(); shardColl.put("shardCollection", collection); shardColl.put("key", new BasicDBObject(ID, 1)); result = dbConn.command(shardColl); if (!result.ok()) { LOG.error("Error enabling shard'ing on {}: {}", collection, result.getErrorMessage()); return result.getErrorMessage(); } sresult = moveChunks(collection, shards, dbConn); if (sresult != null) { return sresult; } } return preSplitBinCollections(dbName, mongoTemplate); }
From source file:org.slc.sli.ingestion.util.MongoCommander.java
License:Apache License
private static String preSplitBinCollections(String dbName, MongoTemplate mongoTemplate) { DB dbConn = mongoTemplate.getDb().getSisterDB("admin"); List<String> shards = getShards(dbConn); if (shards != null && shards.size() > 0) { int numShards = shards.size(); List<String> collections = Arrays.asList("recordHash", "deltas"); for (String collectionName : collections) { LOG.info("Shard count = {}. Setting up sharding config for {}!", numShards, collectionName); String collection = dbName + "." + collectionName; DBObject shardColl = new BasicDBObject(); shardColl.put("shardCollection", collection); shardColl.put("key", new BasicDBObject(ID, 1)); CommandResult result = dbConn.command(shardColl); if (!result.ok()) { LOG.error("Error enabling shard'ing on recordHash: {}", result.getErrorMessage()); return result.getErrorMessage(); }/* ww w. ja va 2s . com*/ int charOffset = 256 / numShards; List<byte[]> shardPoints = new ArrayList<byte[]>(); shardPoints.add(null); for (int shard = 1; shard < numShards; shard++) { String splitString = Integer.toHexString(charOffset * shard); if (splitString.length() < 2) { splitString = "0" + splitString; } splitString = splitString + STR_0X38; byte[] splitPoint = RecordHash.hex2Binary(splitString); shardPoints.add(splitPoint); LOG.info("Adding recordHash splitPoint [" + RecordHash.binary2Hex(splitPoint) + "]"); DBObject splitCmd = new BasicDBObject(); splitCmd.put("split", collection); splitCmd.put("middle", new BasicDBObject(ID, splitPoint)); result = dbConn.command(splitCmd); if (!result.ok()) { LOG.error("Error splitting chunk in recordHash: {}", result.getErrorMessage()); return result.getErrorMessage(); } } for (int index = 0; index < numShards; index++) { DBObject moveCommand = new BasicDBObject(); moveCommand.put("moveChunk", collection); moveCommand.put("find", new BasicDBObject(ID, index == 0 ? "$minkey" : shardPoints.get(index))); moveCommand.put("to", shards.get(index)); result = dbConn.command(moveCommand); if (!result.ok()) { if (!result.getErrorMessage().equals("that chunk is already on that shard")) { LOG.error("Error moving chunk in recordHash: {}", result.getErrorMessage()); return result.getErrorMessage(); } } } } } else { LOG.info("No shards or shard count < 0. Not setting sharding config for recordHash!"); } return null; }
From source file:org.springframework.data.document.mongodb.monitor.AbstractMonitor.java
License:Apache License
public CommandResult getServerStatus() { CommandResult result = getDb("admin").command("serverStatus"); if (!result.ok()) { logger.error("Could not query for server status. Command Result = " + result); throw new MongoException("could not query for server status. Command Result = " + result); }//from ww w .j a v a2 s . c om return result; }
From source file:org.springframework.datastore.mapping.mongo.engine.MongoEntityPersister.java
License:Apache License
@Override protected Object generateIdentifier(final PersistentEntity persistentEntity, final DBObject nativeEntry) { return mongoTemplate.execute(new DbCallback<Object>() { @Override// w w w .j a v a2 s . c o m public Object doInDB(DB con) throws MongoException, DataAccessException { String collectionName = getCollectionName(persistentEntity, nativeEntry); DBCollection dbCollection = con.getCollection(collectionName + NEXT_ID_SUFFIX); // If there is a numeric identifier then we need to rely on optimistic concurrency controls to obtain a unique identifer // sequence. If the identifier is not numeric then we assume BSON ObjectIds. if (hasNumericalIdentifier) { while (true) { DBCursor result = dbCollection.find().sort(new BasicDBObject(MONGO_ID_FIELD, -1)).limit(1); long nextId; if (result.hasNext()) { final Long current = getMappingContext().getConversionService() .convert(result.next().get(MONGO_ID_FIELD), Long.class); nextId = current + 1; } else { nextId = 1; } nativeEntry.put(MONGO_ID_FIELD, nextId); final WriteResult writeResult = dbCollection.insert(nativeEntry); final CommandResult lastError = writeResult.getLastError(); if (lastError.ok()) { break; } else { final Object code = lastError.get("code"); // duplicate key error try again if (code != null && code.equals(11000)) { continue; } break; } } return nativeEntry.get(MONGO_ID_FIELD); } else { ObjectId objectId = ObjectId.get(); if (ObjectId.class.isAssignableFrom(persistentEntity.getIdentity().getType())) { nativeEntry.put(MONGO_ID_FIELD, objectId); return objectId; } else { String stringId = objectId.toString(); nativeEntry.put(MONGO_ID_FIELD, stringId); return stringId; } } } }); }
From source file:org.swissbib.docproc.flink.plugins.DSV11ContentEnrichment.java
License:Open Source License
private void initializeMongoConnection(HashMap<String, String> configuration) throws Exception { try {/* www . j ava2 s .c o m*/ String[] mongoClient = configuration.get("MONGO.CLIENT").split("###"); String[] mongoAuthentication = null; if (configuration.containsKey("MONGO.AUTHENTICATION")) { mongoAuthentication = configuration.get("MONGO.AUTHENTICATION").split("###"); } ServerAddress server = new ServerAddress(mongoClient[0], Integer.valueOf(mongoClient[1])); String[] mongoDB = configuration.get("MONGO.DB.DSV11").split("###"); DB db = null; if (mongoAuthentication != null) { MongoCredential credential = MongoCredential.createMongoCRCredential(mongoAuthentication[1], mongoAuthentication[0], mongoAuthentication[2].toCharArray()); mClient = new MongoClient(server, Arrays.asList(credential)); db = mClient.getDB(mongoDB[0]); } else { mClient = new MongoClient(server); db = mClient.getDB(mongoDB[0]); } //simple test if authentication was successfull CommandResult cR = db.getStats(); if (cR != null && !cR.ok()) { throw new Exception( "authentication against database wasn't possible - no DSV11 Processing will take place when type DSV11ContentEnrichment is called from XSLT templates"); } nativeSource = mClient.getDB(mongoDB[0]); searchCollection = nativeSource.getCollection(mongoDB[1]); } catch (UnknownHostException uHE) { dsv11ProcessingError.error("MongoError", "Mongo Connection couldn't be established"); dsv11ProcessingError.error("MongoError", uHE); uHE.printStackTrace(); throw uHE; } catch (Exception ex) { dsv11ProcessingError.error("MongoError", "General Exception while trying to connect to Mongo"); dsv11ProcessingError.error("MongoError", ex); ex.printStackTrace(); throw ex; } }