com.mongodb.CommandResult Java Examples

The following examples show how to use com.mongodb.CommandResult. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: MongoDataProxy.java    From Knowage-Server with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public IDataStore load(IDataReader dataReader) {
	logger.debug("IN");

	IDataStore dataStore = null;

	CommandResult result = loadData();

	try {
		// read data
		dataReader.setFetchSize(getFetchSize());
		dataReader.setOffset(getOffset());
		dataReader.setMaxResults(getMaxResults());
		((MongoDataReader) dataReader).setAggregatedQuery(isAggregatedQuery());
		dataStore = dataReader.read(result);
	} catch (Throwable t) {
		logger.error("An error occurred while parsing resultset", t);
		throw new SpagoBIRuntimeException("An error occurred while parsing resultset", t);
	}

	logger.debug("OUT");
	return dataStore;
}
 
Example #2
Source File: DenormalizerTest.java    From secure-data-service with Apache License 2.0 6 votes vote down vote up
@Before
public void setup() {
    studentSectionAssociation.put("sectionId", SECTION1);
    studentSectionAssociation.put("studentId", STUDENT1);
    studentSectionAssociation.put("beginDate", BEGINDATE);
    studentSectionAssociation.put("endDate", ENDDATE1);

    WriteResult success = mock(WriteResult.class);
    CommandResult successCR = mock(CommandResult.class);
    CommandResult failCR = mock(CommandResult.class);
    when(success.getLastError()).thenReturn(successCR);
    when(successCR.ok()).thenReturn(true);
    when(successCR.get("value")).thenReturn("updated");
    when(failCR.get("value")).thenReturn(null);
    when(failCR.get("result")).thenReturn(null);
    when(studentCollection.update(any(DBObject.class), any(DBObject.class), eq(false), eq(true), eq(WriteConcern.SAFE))).thenReturn(
            success);
    when(studentCollection.update(any(DBObject.class), any(DBObject.class), eq(true), eq(true), eq(WriteConcern.SAFE))).thenReturn(
            success);
    when(template.getCollection("student")).thenReturn(studentCollection);

    Query query = new Query();
    query.addCriteria(Criteria.where("_id").is(SSAID));
    MongoEntity entity = new MongoEntity("studentSectionAssociation", studentSectionAssociation);
    when(template.findOne(eq(query), eq(Entity.class), eq("studentSectionAssociation"))).thenReturn(entity);
}
 
Example #3
Source File: MongoBenchmark.java    From gameserver with Apache License 2.0 6 votes vote down vote up
public static void testMongoUserId(int max, DB db) {
	String collName = "testmongobjid";
	DBCollection coll = db.getCollection(collName);
	
	//Setup a sharded collection
	BasicDBObject command = new BasicDBObject();
	command.put("shardcollection", collName);
	DBObject key = new BasicDBObject();
	key.put("_id", 1);
	command.put("key", key);
	command.put("unique", true);
	db.command(command);
	
	long startM = System.currentTimeMillis();
	for ( int i=0; i<max; i++ ) {
		BasicDBObject obj = new BasicDBObject();
		obj.put("test", "value-"+i);
		coll.save(obj);
	}
	long endM = System.currentTimeMillis();
	
	System.out.println("Insert " + max + " mongo objectid. time: " + (endM-startM) + " benchmark()");
	
	CommandResult result = db.getStats();
	System.out.println(result);
}
 
Example #4
Source File: SubDocAccessor.java    From secure-data-service with Apache License 2.0 6 votes vote down vote up
private int countSubDocs(DBObject parentQuery) {
            simplifyParentQuery(parentQuery);
            DBObject idQuery = buildIdQuery(parentQuery);

//            String queryCommand = buildAggregateQuery((idQuery == null ? parentQuery.toString() : idQuery.toString()),
//                    parentQuery.toString(), ", {$group: { _id: null, count: {$sum: 1}}}");
            String groupQuery = ", {$group: { _id: null, count: {$sum: 1}}}";
            String queryCommand;
            if (idQuery == null) {
                queryCommand = buildAggregateQuery(parentQuery.toString(), null, groupQuery);
            } else {
                queryCommand = buildAggregateQuery(idQuery.toString(), parentQuery.toString(), groupQuery);
            }
            TenantContext.setIsSystemCall(false);

            CommandResult result = template.executeCommand(queryCommand);
            @SuppressWarnings("unchecked")
            Iterator<DBObject> resultList = ((List<DBObject>) result.get("result")).iterator();
            if (resultList.hasNext()) {
                return (Integer) (resultList.next().get("count"));
            } else {
                return 0;
            }
        }
 
Example #5
Source File: MongoCommander.java    From secure-data-service with Apache License 2.0 6 votes vote down vote up
/**
 * set the state of balancer.
 *
 * @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;
}
 
Example #6
Source File: MongoCommander.java    From secure-data-service with Apache License 2.0 6 votes vote down vote up
/**
 * get list of  the shards
 * @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;
}
 
Example #7
Source File: MongoDBTestHelper.java    From brooklyn-library with Apache License 2.0 6 votes vote down vote up
public static boolean isConfigServer(AbstractMongoDBServer entity) {
    LOG.info("Checking if {} is a config server", entity);
    MongoClient mongoClient = clientForServer(entity);
    try {
        DB db = mongoClient.getDB(ADMIN_DB);
        CommandResult commandResult = db.command("getCmdLineOpts");
        Map<?, ?> parsedArgs = (Map<?, ?>)commandResult.get("parsed");
        if (parsedArgs == null) return false;
        Boolean configServer = (Boolean)parsedArgs.get("configsvr");
        if (configServer != null) {
            // v2.5 format
            return Boolean.TRUE.equals(configServer);
        } else {
            // v2.6 format
            String role = (String) ((Map)parsedArgs.get("sharding")).get("clusterRole");
            return "configsvr".equals(role);
        }
    } finally {
        mongoClient.close();
    }
}
 
Example #8
Source File: MongoDBCollectionMethodInterceptor.java    From skywalking with Apache License 2.0 6 votes vote down vote up
@Override
public Object afterMethod(EnhancedInstance objInst, Method method, Object[] allArguments, Class<?>[] argumentsTypes,
    Object ret) throws Throwable {
    AbstractSpan activeSpan = ContextManager.activeSpan();
    CommandResult cresult = null;
    if (ret instanceof WriteResult) {
        WriteResult wresult = (WriteResult) ret;
        cresult = wresult.getCachedLastError();
    } else if (ret instanceof AggregationOutput) {
        AggregationOutput aresult = (AggregationOutput) ret;
        cresult = aresult.getCommandResult();
    }
    if (null != cresult && !cresult.ok()) {
        activeSpan.log(cresult.getException());
    }
    ContextManager.stopSpan();
    return ret;
}
 
Example #9
Source File: MongoBenchmark.java    From gameserver with Apache License 2.0 5 votes vote down vote up
public static void testMapDBObject(int max, DB db) {
	String collName = "testmapobject";
	DBCollection coll = db.getCollection(collName);
	
	//Setup a sharded collection
	BasicDBObject command = new BasicDBObject();
	command.put("shardcollection", collName);
	DBObject key = new BasicDBObject();
	key.put("_id", 1);
	command.put("key", key);
	command.put("unique", true);
	db.command(command);
	
	long startM = System.currentTimeMillis();
	BasicDBObject objKey = new BasicDBObject();
	UserId userId = new UserId("username");
	objKey.put("_id", userId.getInternal());
	
	MapDBObject obj = new MapDBObject();
	for ( int i=0; i<max; i++ ) {
		obj.put("_id", userId.getInternal());
		obj.put("test-"+(i)%10, "value-"+i);
		coll.update(objKey, obj, true, false);
	}
	long endM = System.currentTimeMillis();
	
	System.out.println(collName+ " update " + max + " my objectid. time: " + (endM-startM) + " benchmark(114892)");
	
	CommandResult result = db.getStats();
	System.out.println(result);
}
 
Example #10
Source File: MongoBenchmark.java    From gameserver with Apache License 2.0 5 votes vote down vote up
public static void testStringUserId(int max, DB db) {
	String collName = "teststringid";
	DBCollection coll = db.getCollection(collName);
	
	//Setup a sharded collection
	BasicDBObject command = new BasicDBObject();
	command.put("shardcollection", collName);
	DBObject key = new BasicDBObject();
	key.put("_id", 1);
	command.put("key", key);
	command.put("unique", true);
	db.command(command);
	
	long startM = System.currentTimeMillis();
	BasicDBObject obj = new BasicDBObject();
	for ( int i=0; i<max; i++ ) {
		obj.put("_id",  "username"+i);
		obj.put("test", "value-"+i);
		coll.save(obj);
	}
	long endM = System.currentTimeMillis();
	
	System.out.println("Insert " + max + " my objectid. time: " + (endM-startM) + " benchmark()");
	
	CommandResult result = db.getStats();
	System.out.println(result);
}
 
Example #11
Source File: MongoUtilTest.java    From gameserver with Apache License 2.0 5 votes vote down vote up
@Test
public void testDoEval() {
	int x = 3;
	int y = 5;
	String code = "function(x,y) {return x+y}";
	CommandResult result = MongoDBUtil.doEval(testDB, null, "mongoutil", code, new Object[]{x, y});
	//{ "serverUsed" : "mongos.babywar.xinqihd.com:27017" , "retval" : 8.0 , "ok" : 1.0}
	System.out.println(result);
	assertEquals(8, result.getInt("retval"));
}
 
Example #12
Source File: MongoUtilTest.java    From gameserver with Apache License 2.0 5 votes vote down vote up
@Test
public void testCopyCollection() {
	String sourceNamespace = "test";
	String sourceCollection = "mongoutil"; 
	String targetNamespace = "test";
	String targetCollection = "mongoutiltest";
	
	DBObject query = MongoDBUtil.createDBObject();
	int count = 10;
	for ( int i=0; i<count; i++ ) {
		DBObject dbObject = new BasicDBObject();
		dbObject.put("_id", i);
		dbObject.put("name", "value"+i);
		MongoDBUtil.saveToMongo(dbObject, dbObject, testDB, sourceNamespace, sourceCollection, true);
	}
	List<DBObject> list = MongoDBUtil.queryAllFromMongo(query, testDB, sourceNamespace, sourceCollection, null);
	assertEquals(count, list.size());
	
	MongoDBUtil.removeDocument(testDB, targetNamespace, targetCollection, null);
	
	String code = 
			"function(sourceDatabase, sourceNamespace, sourceCollection, targetDatabase, targetNamespace, targetCollection) { \n"+
			" var currentdb = db.getSisterDB(sourceDatabase); \n"+
			" var gamedb = db.getSisterDB(targetDatabase); \n"+
			" currentdb.getCollection(sourceNamespace+\".\"+sourceCollection).find().forEach(function(x){gamedb.getCollection(targetNamespace+\".\"+targetCollection).insert(x)}); \n"+
			" return sourceNamespace;\n"+
			"}";
	
	CommandResult result = MongoDBUtil.doEval(
			testDB, sourceNamespace, sourceCollection, code, 
			new Object[]{testDB, sourceNamespace, sourceCollection, 
					testDB, targetNamespace, targetCollection});
	System.out.println(result);
	
	list = MongoDBUtil.queryAllFromMongo(query, testDB, targetNamespace, targetCollection, null);
	assertEquals(count, list.size());
}
 
Example #13
Source File: MongoNativeExtractor.java    From deep-spark with Apache License 2.0 5 votes vote down vote up
/**
 * Gets split data.
 *
 * @param collection the collection
 * @return the split data
 */
private BasicDBList getSplitData(DBCollection collection) {

    final DBObject cmd = BasicDBObjectBuilder.start("splitVector", collection.getFullName())
            .add("keyPattern", new BasicDBObject(MONGO_DEFAULT_ID, 1))
            .add("force", false)
            .add("maxChunkSize", splitSize)
            .get();

    CommandResult splitVectorResult = collection.getDB().getSisterDB("admin").command(cmd);
    return (BasicDBList) splitVectorResult.get(SPLIT_KEYS);

}
 
Example #14
Source File: MongoDbOutputTest.java    From pentaho-mongodb-plugin with Apache License 2.0 5 votes vote down vote up
@Test public void testUpdate() throws Exception {
  setupReturns();
  WriteResult result = mock( WriteResult.class );
  CommandResult commandResult = mock( CommandResult.class );
  when( commandResult.ok() ).thenReturn( true );
  when( mongoCollectionWrapper.update( any( DBObject.class ), any( DBObject.class ), anyBoolean(), anyBoolean() ) )
    .thenReturn( result );
  when( stepMetaInterface.getUpdate() ).thenReturn( true );

  // flag a field for update = "foo"
  MongoDbOutputMeta.MongoField mongoField = mongoFields.get( 0 );
  mongoField.m_updateMatchField = true;

  setupRowMeta();
  dbOutput.init( stepMetaInterface, stepDataInterace );
  assertTrue( dbOutput.processRow( stepMetaInterface, stepDataInterace ) );
  ArgumentCaptor<BasicDBObject> updateQueryCaptor = ArgumentCaptor.forClass( BasicDBObject.class );
  ArgumentCaptor<BasicDBObject> insertCaptor = ArgumentCaptor.forClass( BasicDBObject.class );

  // update is executed
  verify( mongoCollectionWrapper )
    .update( updateQueryCaptor.capture(), insertCaptor.capture(), anyBoolean(), anyBoolean() );
  // updated field is expected
  assertThat( updateQueryCaptor.getValue(), equalTo( new BasicDBObject( "foo", "foo" ) ) );
  // insert document is expected
  assertThat( insertCaptor.getValue(),
    equalTo( new BasicDBObject( ( ImmutableMap.of( "foo", "foo", "bar", "bar", "baz", "baz" ) ) ) ) );
}
 
Example #15
Source File: MongoDbOutputTest.java    From pentaho-mongodb-plugin with Apache License 2.0 5 votes vote down vote up
@Test public void doBatchWithRetry() throws Exception {
  setupReturns();
  setupRowMeta();
  dbOutput.m_batch = new ArrayList<DBObject>();
  dbOutput.m_batch.add( new BasicDBObject( ImmutableMap.of( "foo", "fooval", "bar", "barval", "baz", "bazval" ) ) );
  List<Object[]> batchRows = new ArrayList<Object[]>();
  batchRows.add( rowData );

  List<DBObject> batchCopy = new ArrayList( dbOutput.m_batch );

  dbOutput.m_batchRows = batchRows;
  when( stepMetaInterface.getWriteRetries() ).thenReturn( "1" );
  when( stepMetaInterface.getWriteRetryDelay() ).thenReturn( "0" );
  WriteResult result = mock( WriteResult.class );
  CommandResult commandResult = mock( CommandResult.class );
  when( commandResult.ok() ).thenReturn( true );
  when( mongoCollectionWrapper.save( dbOutput.m_batch.get( 0 ) ) ).thenReturn( result );

  doThrow( mock( MongoException.class ) ).when( mongoCollectionWrapper ).insert( anyList() );
  dbOutput.init( stepMetaInterface, stepDataInterace );
  dbOutput.doBatch();

  // should attempt insert once, falling back to save on retry
  verify( mongoCollectionWrapper, times( 1 ) ).insert( anyList() );
  verify( mongoCollectionWrapper, times( 1 ) ).save( batchCopy.get( 0 ) );

  // batch should be cleared.
  assertThat( dbOutput.m_batch.size(), equalTo( 0 ) );
  assertThat( dbOutput.m_batchRows.size(), equalTo( 0 ) );
}
 
Example #16
Source File: SubDocAccessor.java    From secure-data-service with Apache License 2.0 5 votes vote down vote up
public boolean doUpdate(Query query, Update update) {
    DBObject queryDBObject = toSubDocQuery(query, true);

    DBObject elementMatch = new BasicDBObject("$elemMatch", query.getQueryObject());
    queryDBObject.put(subField, elementMatch);

    DBObject patchUpdate = toSubDocUpdate(update);
    String updateCommand = "{findAndModify:\"" + collection + "\",query:" + queryDBObject.toString()
            + ",update:" + patchUpdate.toString() + "}";
    LOG.debug("the update date mongo command is: {}", updateCommand);
    TenantContext.setIsSystemCall(false);
    CommandResult result = template.executeCommand(updateCommand);
    return result.get("value") != null;

}
 
Example #17
Source File: SubDocAccessor.java    From secure-data-service with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
        private List<Entity> findSubDocs(DBObject parentQuery, DBObject limitQuery) {
            StringBuilder limitQuerySB = new StringBuilder();
            if (limitQuery != null && limitQuery.keySet().size() > 0) {
                if (limitQuery.get("$sort") != null) {
                    limitQuerySB.append(",{$sort:" + limitQuery.get("$sort").toString() + "}");
                }
                if (limitQuery.get("$skip") != null) {
                    limitQuerySB.append(",{$skip:" + limitQuery.get("$skip") + "}");
                }
                if (limitQuery.get("$limit") != null) {
                    limitQuerySB.append(",{$limit:" + limitQuery.get("$limit") + "}");
                }
            }
            simplifyParentQuery(parentQuery);

            DBObject idQuery = buildIdQuery(parentQuery);
//            String queryCommand = buildAggregateQuery(idQuery != null ? idQuery.toString() : parentQuery.toString(),
//                    parentQuery.toString(), limitQuerySB.toString());
            String queryCommand;
            if (idQuery == null) {
                queryCommand = buildAggregateQuery(parentQuery.toString(), null, limitQuerySB.toString());
            } else {
                queryCommand = buildAggregateQuery(idQuery.toString(), parentQuery.toString(), limitQuerySB.toString());
            }
            TenantContext.setIsSystemCall(false);
            CommandResult result = template.executeCommand(queryCommand);
            List<DBObject> subDocs = (List<DBObject>) result.get("result");
            List<Entity> entities = new ArrayList<Entity>();

            if (subDocs != null && subDocs.size() > 0) {
                for (DBObject dbObject : subDocs) {
                    entities.add(convertDBObjectToSubDoc(((DBObject) dbObject.get(subField))));
                }
            }
            return entities;
        }
 
Example #18
Source File: AggregationLoaderTest.java    From secure-data-service with Apache License 2.0 5 votes vote down vote up
@Before
public void setup() {
    // assume mongo template can do its job
    CommandResult cr = mock(CommandResult.class);
    when(mongoTemplate.executeCommand(anyString())).thenReturn(cr);
    when(cr.ok()).thenReturn(true);

    when(aggregationLoader.getFiles()).thenReturn(new ArrayList<String>());
    aggregationLoader.init();
}
 
Example #19
Source File: ContainerDocumentAccessorTest.java    From secure-data-service with Apache License 2.0 5 votes vote down vote up
@Before
public void setup() {
    mockCollection = Mockito.mock(DBCollection.class);
    writeResult = Mockito.mock(WriteResult.class);
    commandResult = Mockito.mock(CommandResult.class);
    testAccessor = new ContainerDocumentAccessor(generatorStrategy, naturalKeyExtractor, mongoTemplate, schemaRepo);
    MockitoAnnotations.initMocks(this);
    when(mockHolder.getContainerDocument(ATTENDANCE)).thenReturn(createContainerDocAttendance());
    entity = createAttendanceEntity();
    when(writeResult.getLastError()).thenReturn(commandResult);
    when(commandResult.ok()).thenReturn(true);
}
 
Example #20
Source File: MongoGenericDao.java    From howsun-javaee-framework with Apache License 2.0 5 votes vote down vote up
@Override
public <T> int update(Class<T> entityClass, String[] fields, Object[] fieldValues, Serializable id) {
	WriteResult result = operations.updateFirst(new Query(where("_id").is(id)), setFieldValue(fields, fieldValues), entityClass);
	CommandResult commandResult = result.getLastError();
	if(commandResult.ok()){
		return 1;
	}
	throw new DaoException(commandResult.getErrorMessage());
}
 
Example #21
Source File: DBusMongoClient.java    From DBus with Apache License 2.0 5 votes vote down vote up
private boolean isReplSet() {
    boolean ret = false;
    DB db = new DB(mongoClient, "admin");
    CommandResult cr = db.command("replSetGetStatus");
    logger.info("isReplSet: {}", cr.toJson());
    if (cr.containsField("set") && cr.containsField("members")) {
        ret = true;
    }
    return ret;
}
 
Example #22
Source File: DBusMongoClient.java    From DBus with Apache License 2.0 5 votes vote down vote up
private boolean isShard() {
    boolean ret = false;
    DB db = new DB(mongoClient, "admin");
    CommandResult cr = db.command("isdbgrid");
    logger.info("isShard: {}", cr.toJson());
    if (cr.containsField("isdbgrid") && cr.getInt("isdbgrid") == 1) {
        ret = true;
    }
    return ret;
}
 
Example #23
Source File: MongoDBClientSupport.java    From brooklyn-library with Apache License 2.0 5 votes vote down vote up
private Optional<CommandResult> runDBCommand(String database, final DBObject command) {
    MongoClient client = client();
    try {
        final DB db = client.getDB(database);
        final CommandResult[] status = new CommandResult[1];

        // The mongoDB client can occasionally fail to connect. Try up to 5 times to run the command
        boolean commandResult = Repeater.create().backoff(Duration.ONE_SECOND, 1.5, null).limitIterationsTo(5)
                .until(new Callable<Boolean>() {
                    @Override
                    public Boolean call() throws Exception {
                        try {
                            status[0] = db.command(command);
                            return true;
                        } catch (Exception e) {
                            LOG.warn("Command " + command + " on " + address.getHost() + " failed", e);
                            return false;
                        }
                    }
        }).run();

        if (!commandResult) {
            return Optional.absent();
        }

        if (!status[0].ok()) {
            LOG.debug("Unexpected result of {} on {}: {}",
                    new Object[] { command, getServerAddress(), status[0].getErrorMessage() });
        }
        return Optional.of(status[0]);
    } finally {
        client.close();
    }
}
 
Example #24
Source File: MongoDBClientSupport.java    From brooklyn-library with Apache License 2.0 5 votes vote down vote up
public BasicBSONObject getServerStatus() {
    Optional<CommandResult> result = runDBCommand("admin", "serverStatus");
    if (result.isPresent() && result.get().ok()) {
        return result.get();
    } else {
        return EMPTY_RESPONSE;
    }
}
 
Example #25
Source File: MongoDBClientSupport.java    From brooklyn-library with Apache License 2.0 5 votes vote down vote up
public boolean ping() {
    MongoClient client = fastClient();
    DBObject command = new BasicDBObject("ping", "1");
    final DB db = client.getDB("admin");

    try {
        CommandResult status = db.command(command);
        return status.ok();
    } catch (MongoException e) {
        LOG.warn("Pinging server {} failed with {}", address.getHost(), e);
    } finally {
        client.close();
    }
    return false;
}
 
Example #26
Source File: MongoDBClientSupport.java    From brooklyn-library with Apache License 2.0 5 votes vote down vote up
public boolean initializeReplicaSet(String replicaSetName, Integer id) {
    HostAndPort primary = getServerHostAndPort();
    BasicBSONObject config = ReplicaSetConfig.builder(replicaSetName)
            .member(primary, id)
            .build();

    BasicDBObject dbObject = new BasicDBObject("replSetInitiate", config);
    LOG.debug("Initiating replica set with: " + dbObject);

    Optional<CommandResult> result = runDBCommand("admin", dbObject);
    if (result.isPresent() && result.get().ok() && LOG.isDebugEnabled()) {
        LOG.debug("Completed initiating MongoDB replica set {} on entity {}", replicaSetName, this);
    }
    return result.isPresent() && result.get().ok();
}
 
Example #27
Source File: MongoDBClientSupport.java    From brooklyn-library with Apache License 2.0 5 votes vote down vote up
/**
 * Runs replSetReconfig with the given BasicBSONObject. Returns true if the result's
 * status is ok.
 */
private boolean reconfigureReplicaSet(BasicBSONObject newConfig) {
    BasicDBObject command = new BasicDBObject("replSetReconfig", newConfig);
    LOG.debug("Reconfiguring replica set to: " + command);
    Optional<CommandResult> result = runDBCommand("admin", command);
    return result.isPresent() && result.get().ok();
}
 
Example #28
Source File: MongoBenchmark.java    From gameserver with Apache License 2.0 5 votes vote down vote up
public static void testMyUserId(int max, DB db) {
	String collName = "testmyuserid";
	DBCollection coll = db.getCollection(collName);
	
	//Setup a sharded collection
	BasicDBObject command = new BasicDBObject();
	command.put("shardcollection", collName);
	DBObject key = new BasicDBObject();
	key.put("_id", 1);
	command.put("key", key);
	command.put("unique", true);
	db.command(command);
	
	long startM = System.currentTimeMillis();
	BasicDBObject obj = new BasicDBObject();
	for ( int i=0; i<max; i++ ) {
		UserId userId = new UserId("username"+i);
		obj.put("_id",  userId.getInternal());
		obj.put("test", "value-"+i);
		coll.save(obj);
	}
	long endM = System.currentTimeMillis();
	
	System.out.println("Insert " + max + " my objectid. time: " + (endM-startM) + " benchmark()");
	
	CommandResult result = db.getStats();
	System.out.println(result);
}
 
Example #29
Source File: MongoBenchmark.java    From gameserver with Apache License 2.0 5 votes vote down vote up
public static void testBasicBson(int max, DB db) {
	String collName = "testbasicbson";
	DBCollection coll = db.getCollection(collName);
	
	//Setup a sharded collection
	BasicDBObject command = new BasicDBObject();
	command.put("shardcollection", collName);
	DBObject key = new BasicDBObject();
	key.put("_id", 1);
	command.put("key", key);
	command.put("unique", true);
	db.command(command);
	
	long startM = System.currentTimeMillis();
	BasicDBObject objKey = new BasicDBObject();
	UserId userId = new UserId("username");
	objKey.put("_id", userId.getInternal());
	
	BasicDBObject obj = new BasicDBObject();
	for ( int i=0; i<max; i++ ) {
		obj.put("_id", userId.getInternal());
		obj.put("test-"+(i)%10, "value-"+i);
		coll.update(objKey, obj, true, false);
	}
	long endM = System.currentTimeMillis();
	
	System.out.println(collName+ " update " + max + " my objectid. time: " + (endM-startM) + " benchmark(56273)");
	
	CommandResult result = db.getStats();
	System.out.println(result);
}
 
Example #30
Source File: MongoDBClientSupport.java    From brooklyn-library with Apache License 2.0 4 votes vote down vote up
public boolean addShardToRouter(String hostAndPort) {
    LOG.debug("Adding shard " + hostAndPort);
    BasicDBObject command = new BasicDBObject("addShard", hostAndPort);
    Optional<CommandResult> result = runDBCommand("admin", command);
    return result.isPresent() && result.get().ok();
}