本文整理汇总了Java中com.mongodb.CommandResult类的典型用法代码示例。如果您正苦于以下问题:Java CommandResult类的具体用法?Java CommandResult怎么用?Java CommandResult使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
CommandResult类属于com.mongodb包,在下文中一共展示了CommandResult类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: getShards
import com.mongodb.CommandResult; //导入依赖的package包/类
/**
* 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;
}
示例2: doBatchUpdate
import com.mongodb.CommandResult; //导入依赖的package包/类
private int doBatchUpdate(DBCollection dbCollection, String collName, Collection<BatchUpdateOptions> options,
boolean ordered) {
DBObject command = new BasicDBObject();
command.put("update", collName);
List<BasicDBObject> updateList = new ArrayList<BasicDBObject>();
for (BatchUpdateOptions option : options) {
BasicDBObject update = new BasicDBObject();
update.put("q", option.getQuery().getQueryObject());
update.put("u", option.getUpdate().getUpdateObject());
update.put("upsert", option.isUpsert());
update.put("multi", option.isMulti());
updateList.add(update);
}
command.put("updates", updateList);
command.put("ordered", ordered);
CommandResult commandResult = dbCollection.getDB().command(command);
return Integer.parseInt(commandResult.get("n").toString());
}
示例3: deleteUserSucceeds
import com.mongodb.CommandResult; //导入依赖的package包/类
@Test
@DirtiesContext // because we can't authenticate twice on same DB
public void deleteUserSucceeds() throws MongoServiceException {
service.createDatabase(DB_NAME);
DBObject createUserCmd = BasicDBObjectBuilder.start("createUser", "user").add("pwd", "password")
.add("roles", new BasicDBList()).get();
CommandResult result = client.getDB(DB_NAME).command(createUserCmd);
assertTrue("create should succeed", result.ok());
service.deleteUser(DB_NAME, "user");
assertFalse(client.getDB(DB_NAME).authenticate("user", "password".toCharArray()));
}
示例4: assertVersionConfiguration
import com.mongodb.CommandResult; //导入依赖的package包/类
private void assertVersionConfiguration(String configuredVersion,
String expectedVersion) {
this.context = new AnnotationConfigApplicationContext();
int mongoPort = SocketUtils.findAvailableTcpPort();
EnvironmentTestUtils.addEnvironment(this.context,
"spring.data.mongodb.port=" + mongoPort);
if (configuredVersion != null) {
EnvironmentTestUtils.addEnvironment(this.context,
"spring.mongodb.embedded.version=" + configuredVersion);
}
this.context.register(MongoAutoConfiguration.class,
MongoDataAutoConfiguration.class, EmbeddedMongoAutoConfiguration.class);
this.context.refresh();
MongoTemplate mongo = this.context.getBean(MongoTemplate.class);
CommandResult buildInfo = mongo.executeCommand("{ buildInfo: 1 }");
assertThat(buildInfo.getString("version")).isEqualTo(expectedVersion);
}
开发者ID:vikrammane23,项目名称:https-github.com-g0t4-jenkins2-course-spring-boot,代码行数:19,代码来源:EmbeddedMongoAutoConfigurationTests.java
示例5: contribute
import com.mongodb.CommandResult; //导入依赖的package包/类
@Override
public void contribute(Info.Builder builder) {
InetAddress ip = null;
Map<String, String> hostMap = new HashMap<>();
try {
ip = InetAddress.getLocalHost();
} catch (UnknownHostException e) {
e.printStackTrace();
}
hostMap.put("ipAddress", ip.getHostAddress());
hostMap.put("hostname", ip.getHostName());
builder.withDetail("appHostInfo", hostMap);
hostMap = new HashMap<>();
CommandResult commandResult = this.mongoTemplate.executeCommand("{ serverStatus: 1 }");
hostMap.put("hostname", commandResult.getString("host"));
builder.withDetail("mongoDbHostInfo", hostMap);
}
示例6: assertVersionConfiguration
import com.mongodb.CommandResult; //导入依赖的package包/类
private void assertVersionConfiguration(String configuredVersion,
String expectedVersion) {
this.context = new AnnotationConfigApplicationContext();
int mongoPort = SocketUtils.findAvailableTcpPort();
EnvironmentTestUtils.addEnvironment(this.context,
"spring.data.mongodb.port=" + mongoPort);
if (configuredVersion != null) {
EnvironmentTestUtils.addEnvironment(this.context,
"spring.mongodb.embedded.version=" + configuredVersion);
}
this.context.register(MongoAutoConfiguration.class,
MongoDataAutoConfiguration.class, EmbeddedMongoAutoConfiguration.class);
this.context.refresh();
MongoTemplate mongo = this.context.getBean(MongoTemplate.class);
CommandResult buildInfo = mongo.executeCommand("{ buildInfo: 1 }");
assertThat(buildInfo.getString("version"), equalTo(expectedVersion));
}
示例7: backupHistoryData
import com.mongodb.CommandResult; //导入依赖的package包/类
/**
* backup the last collection and put '.bak' to the end of name<br />
* be aware that the sharded mongodb does not support renameCollection()
* <p>
*
* @author chen.chen.9, 2013-8-26
* @return {@link BackupHistoryDataBean}
*/
protected BackupHistoryDataBean backupHistoryData() {
long startTime = System.currentTimeMillis();
String originalName = getResponseClassSimpleName();
String backupEndName = getSysconfig().getString("Collector.BackupEndName");
DateFormat dateFormat = new SimpleDateFormat(".yyyy-MM-dd_HH:mm");
dropPreviousCollection(originalName, backupEndName, dateFormat, getDaoSupport().getMongoTemplate());
String toName = StringUtils.join(new String[] { originalName, backupEndName, dateFormat.format(new Date()) });
String dbCommand = StringUtils.replaceEach("{ renameCollection: \"{0}.{1}\", to: \"{0}.{2}\", dropTarget: true }", new String[] { "{0}", "{1}", "{2}" },
new String[] { getSysconfig().getString("Database.MongoDB.DatabaseName"), originalName, toName });
CommandResult commandResult = getAdminMongoTemplate().executeCommand(dbCommand);
return new BackupHistoryDataBean(originalName, toName, System.currentTimeMillis() - startTime, commandResult.ok(), dbCommand);
}
示例8: getUpdateResult
import com.mongodb.CommandResult; //导入依赖的package包/类
/**
*
* mongodb,解析 更新操作是否成功
*
* 返回更新数据库的结果
*
* 小于零:更新出现异常 等于零:成功执行了更新的SQL,但是没有影响到任何数据 大于零:成功执行了更新的SQL,影响到多条数据,条数就是返回值
*
* @param result
* @return
*/
@Override
public int getUpdateResult(WriteResult result) {
if (result == null) {
return FAIL_CODE_ONE;
}
@SuppressWarnings("deprecation")
CommandResult cr = result.getLastError();
if (cr == null) {
return FAIL_CODE_TWO;
}
boolean error_flag = false;
error_flag = cr.ok();
if (!error_flag) {// 获取上次操作结果是否有错误.
return FAIL_CODE_THREE;
}
int affect_count = result.getN();// 操作影响的对象个数
if (affect_count < 0) {
return FAIL_CODE_FOUR;
} else {
return affect_count;
}
}
示例9: afterMethod
import com.mongodb.CommandResult; //导入依赖的package包/类
@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;
}
示例10: testMongoUserId
import com.mongodb.CommandResult; //导入依赖的package包/类
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);
}
示例11: run
import com.mongodb.CommandResult; //导入依赖的package包/类
public void run() {
logger.log(Level.INFO, "harvesting metrics...");
for (String mongoSrv : topology.getDiscoveredServers()) {
MongoServer ms = null;
try {
ms = new MongoServer(mongoSrv);
CommandResult mcr =
getMongoData(ms.getHost(), ms.getPort());
if (isValidData(mcr)) {
MetricFeedBundle mfb = makeMetrics(mcr);
deliverMetrics(mfb);
}
} catch (Exception e) {
logger.log(Level.SEVERE, "Exception: ", e);
}
}
}
示例12: runDBCmd
import com.mongodb.CommandResult; //导入依赖的package包/类
private CommandResult runDBCmd(
final String host,
final int port,
final String database,
final String cmd
) throws Exception {
MongoClient dbClient = null;
try {
dbClient = setupDbClient(host, port);
DB db = dbClient.getDB(database);
return db.command(cmd);
} finally {
if (dbClient != null) {
dbClient.close();
}
}
}
示例13: discoverReplicas
import com.mongodb.CommandResult; //导入依赖的package包/类
protected List<String> discoverReplicas(final String host, final int port)
throws Exception {
List<String> replicas = new ArrayList<String>();
final CommandResult cr = dbAdminCmd(host, port, "isMaster");
replicas.addAll((List<String>) cr.get("hosts"));
// hidden replicas are replicas that cannot become primaries and
// are hidden to the client app
if (cr.getBoolean("hidden")) {
// TODO: We can't assume we're the master here....
replicas.add(cr.getString("me"));
}
// passives are replicas that cannot become primaries because
// their priority is set to 0
if (cr.containsField("passives")) {
replicas.addAll((List<String>) cr.get("passives"));
}
// arbiters exist only to vote in master elections. They don't
// actually hold replica data.
if (cr.containsField("arbiters")) {
replicas.addAll((List<String>) cr.get("arbiters"));
}
return replicas;
}
示例14: status
import com.mongodb.CommandResult; //导入依赖的package包/类
@Override
public List<DependencyStatus> status() {
//note failures are tested manually for now, if you make changes test
//things still work
//TODO TEST add tests exercising failures
final String version;
try {
final CommandResult bi = gfs.getDB().command("buildInfo");
version = bi.getString("version");
} catch (MongoException e) {
LoggerFactory.getLogger(getClass())
.error("Failed to connect to MongoDB", e);
return Arrays.asList(new DependencyStatus(false,
"Couldn't connect to MongoDB: " + e.getMessage(),
"GridFS", "Unknown"));
}
return Arrays.asList(
new DependencyStatus(true, "OK", "GridFS", version));
}
示例15: status
import com.mongodb.CommandResult; //导入依赖的package包/类
public List<DependencyStatus> status() {
//note failures are tested manually for now, if you make changes test
//things still work
//TODO TEST add tests exercising failures
final List<DependencyStatus> deps = new LinkedList<>(blob.status());
final String version;
try {
final CommandResult bi = wsmongo.command("buildInfo");
version = bi.getString("version");
} catch (MongoException e) {
LoggerFactory.getLogger(getClass())
.error("Failed to connect to MongoDB", e);
deps.add(0, new DependencyStatus(false,
"Couldn't connect to MongoDB: " + e.getMessage(),
"MongoDB", "Unknown"));
return deps;
}
deps.add(0, new DependencyStatus(true, "OK", "MongoDB", version));
return deps;
}