下面列出了怎么用com.mongodb.CommandResult的API类实例代码及写法,或者点击链接到github查看源代码。
@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;
}
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();
}
}
@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;
}
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);
}
/**
* 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;
}
/**
* 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;
}
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;
}
}
@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);
}
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;
}
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;
}
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();
}
}
public BasicBSONObject getServerStatus() {
Optional<CommandResult> result = runDBCommand("admin", "serverStatus");
if (result.isPresent() && result.get().ok()) {
return result.get();
} else {
return EMPTY_RESPONSE;
}
}
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;
}
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();
}
/**
* 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();
}
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);
}
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);
}
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);
}
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);
}
@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"));
}
@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());
}
/**
* 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);
}
@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" ) ) ) ) );
}
@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 ) );
}
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;
}
@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;
}
@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();
}
@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);
}
@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());
}
private CommandResult loadData() {
logger.debug("IN");
CommandResult result = null;
String clientUrl = dataSource.getUrlConnection();
logger.debug("Getting the connection URL and db name");
if (dataSource.getUser() != null && dataSource.getPwd() != null && dataSource.getUser().length() > 0 && dataSource.getPwd().length() > 0) {
String authPart = "mongodb://"+dataSource.getUser()+":"+dataSource.getPwd()+"@";
clientUrl = clientUrl.replace("mongodb://", authPart);
}
logger.debug("MongoDB connection URI:"+clientUrl);
MongoClientURI mongoClientURI= new MongoClientURI(clientUrl);
MongoClient mongoClient = new MongoClient(new MongoClientURI(clientUrl));
logger.debug("Connecting to mongodb");
String databaseName = mongoClientURI.getDatabase();
logger.debug("Database name: " + databaseName);
try {
logger.debug("Connecting to the db " + databaseName);
DB database = mongoClient.getDB(databaseName);
logger.debug("Executing the statement" + statement);
result = database.doEval(getDecoredStatement());
} catch (Exception e) {
logger.error("Exception executing the MongoDataset", e);
throw new SpagoBIRuntimeException("Exception executing the MongoDataset", e);
} finally {
logger.debug("Closing connection");
mongoClient.close();
}
logger.debug("OUT");
return result;
}