List of usage examples for com.mongodb BasicDBList BasicDBList
BasicDBList
From source file:com.berkgokden.mongodb.MongoMapStore.java
License:Open Source License
public Map loadAll(Collection keys) { Map map = new HashMap(); BasicDBList dbo = new BasicDBList(); for (Object key : keys) { dbo.add(new BasicDBObject("_id", key)); }/*from w w w . j av a 2s . co m*/ BasicDBObject dbb = new BasicDBObject("$or", dbo); DBCursor cursor = coll.find(dbb); while (cursor.hasNext()) { try { DBObject obj = cursor.next(); Class clazz = Class.forName(obj.get("_class").toString()); map.put(obj.get("_id"), converter.toObject(clazz, obj)); } catch (ClassNotFoundException e) { logger.log(Level.WARNING, e.getMessage(), e); } } return map; }
From source file:com.berkgokden.mongodb.MongoMapStore.java
License:Open Source License
public Set loadAllKeys() { Set keyset = new HashSet(); BasicDBList dbo = new BasicDBList(); dbo.add("_id"); DBCursor cursor = coll.find(null, dbo); while (cursor.hasNext()) { keyset.add(cursor.next().get("_id")); }/*from www . ja va 2 s .c o m*/ return keyset; }
From source file:com.biz.mongo.MongoDBConnection.java
public String getMongoDBContext(SkillFlowContext skillFlowContext) { DBObject clause_sessionId = new BasicDBObject("sessionId", skillFlowContext.getSessionId()); // DBObject clause_contextId = new BasicDBObject("contextId", skillFlowContext.getContextId()); // DBObject clause_contextId = new BasicDBObject("queryParameter", java.util.regex.Pattern.compile(skillFlowContext.getQueryParameter())); DBObject clause_contextId = new BasicDBObject("queryParameter", skillFlowContext.getQueryParameter()); BasicDBList and_query = new BasicDBList(); and_query.add(clause_sessionId);//from www. j a va 2 s. c o m and_query.add(clause_contextId); String contextId = null; String nextStep = null; DBObject query_text = new BasicDBObject("$and", and_query); context_cursor = context.find(query_text); System.out.println("context_cursor " + context_cursor); System.out.println("context_cursor.hasNext() " + context_cursor.hasNext()); while (context_cursor.hasNext()) { System.out.println("step 1"); DBObject db_obj = context_cursor.next(); contextId = db_obj.get("sessionId").toString(); System.out.println("contextId " + contextId); nextStep = db_obj.get("nextStep").toString(); System.out.println("nextStep " + nextStep); } System.out.println("contextId+\"::\"+nextStep : " + contextId + "::" + nextStep); return contextId + "::" + nextStep; }
From source file:com.biz.mongo.MongoDBConnection.java
public String getProgressStatus(SkillFlowContext skillFlowContext) { DBObject clause_sessionId = new BasicDBObject("sessionId", skillFlowContext.getSessionId()); // DBObject clause_contextId = new BasicDBObject("contextId", skillFlowContext.getContextId()); // DBObject clause_contextId = new BasicDBObject("queryParameter", java.util.regex.Pattern.compile(skillFlowContext.getQueryParameter())); DBObject clause_contextId = new BasicDBObject("queryParameter", skillFlowContext.getQueryParameter()); BasicDBList and_query = new BasicDBList(); and_query.add(clause_sessionId);/*from w w w. j a v a 2 s .c o m*/ and_query.add(clause_contextId); String sessionId = null; String contextId = null; String nextStep = null; String contextState = null; String progress_result = null; DBObject query_text = new BasicDBObject("$and", and_query); context_cursor = context.find(query_text); // System.out.println("context_cursor "+context_cursor); // System.out.println("context_cursor.hasNext() "+context_cursor.hasNext()); if (context_cursor.hasNext()) { while (context_cursor.hasNext()) { System.out.println("step 1"); DBObject db_obj = context_cursor.next(); sessionId = db_obj.get("sessionId").toString(); // System.out.println("sessionId "+sessionId); contextId = db_obj.get("contextId").toString(); // System.out.println("contextId "+contextId); nextStep = db_obj.get("nextStep").toString(); // System.out.println("nextStep "+nextStep); contextState = db_obj.get("contextState").toString(); // System.out.println("contextState "+contextState); // System.out.println("sessionId::contextId::nextStep::contextState "+sessionId+"::"+contextId+"::"+nextStep+"::"+contextState); progress_result = sessionId + "::" + contextId + "::" + nextStep + "::" + contextState; } } else { progress_result = "NoRecord"; } return progress_result; }
From source file:com.ca.apm.mongo.test.MongoReplicaSetForTestFactory.java
License:Open Source License
private void initializeReplicaSet(Entry<String, List<IMongodConfig>> entry) throws Exception { String replicaName = entry.getKey(); List<IMongodConfig> mongoConfigList = entry.getValue(); if (mongoConfigList.size() < 3) { throw new Exception("A replica set must contain at least 3 members."); }//w w w. j av a 2 s . co m // Create 3 mongod processes for (IMongodConfig mongoConfig : mongoConfigList) { if (!mongoConfig.replication().getReplSetName().equals(replicaName)) { throw new Exception("Replica set name must match in mongo configuration"); } MongodStarter starter = MongodStarter.getDefaultInstance(); MongodExecutable mongodExe = starter.prepare(mongoConfig); MongodProcess process = mongodExe.start(); mongodProcessList.add(process); } Thread.sleep(1000); MongoClientOptions mo = MongoClientOptions.builder().autoConnectRetry(true).build(); MongoClient mongo = new MongoClient( new ServerAddress(mongoConfigList.get(0).net().getServerAddress().getHostName(), mongoConfigList.get(0).net().getPort()), mo); DB mongoAdminDB = mongo.getDB(ADMIN_DATABASE_NAME); CommandResult cr = mongoAdminDB.command(new BasicDBObject("isMaster", 1)); logger.info("isMaster: " + cr); // Build BSON object replica set settings DBObject replicaSetSetting = new BasicDBObject(); replicaSetSetting.put("_id", replicaName); BasicDBList members = new BasicDBList(); int i = 0; for (IMongodConfig mongoConfig : mongoConfigList) { DBObject host = new BasicDBObject(); host.put("_id", i++); host.put("host", mongoConfig.net().getServerAddress().getHostName() + ":" + mongoConfig.net().getPort()); members.add(host); } replicaSetSetting.put("members", members); logger.info(replicaSetSetting.toString()); // Initialize replica set cr = mongoAdminDB.command(new BasicDBObject("replSetInitiate", replicaSetSetting)); logger.info("replSetInitiate: " + cr); Thread.sleep(5000); cr = mongoAdminDB.command(new BasicDBObject("replSetGetStatus", 1)); logger.info("replSetGetStatus: " + cr); // Check replica set status before to proceed while (!isReplicaSetStarted(cr)) { logger.info("Waiting for 3 seconds..."); Thread.sleep(1000); cr = mongoAdminDB.command(new BasicDBObject("replSetGetStatus", 1)); logger.info("replSetGetStatus: " + cr); } mongo.close(); mongo = null; }
From source file:com.caci.dummyserver.MongoRepository.java
private DBObject makeQueryObject(Collection<Pair<String, String>> keys, Collection<Pair<String, Collection<String>>> filters) { DBObject result = new BasicDBObject(); if (keys != null) { for (Pair<String, String> key : keys) { result.put("key." + key.getKey(), key.getValue()); }// w ww. jav a2 s .com } if (filters != null) { for (Pair<String, Collection<String>> filter : filters) { int valueCount = filter.getValue().size(); if (valueCount == 1) { String filterValue = null; for (String v : filter.getValue()) { filterValue = v; } result.put("data." + filter.getKey(), filterValue); } else if (valueCount > 1) { BasicDBList dbList = new BasicDBList(); dbList.addAll(filter.getValue()); BasicDBObject dbObj = new BasicDBObject(); dbObj.put("$in", dbList); result.put("data." + filter.getKey(), dbObj); } } } return result; }
From source file:com.cc.manage.logic.BcompanyapplyLogic.java
/** * ???//w w w . j ava 2 s. c o m * * @param request ?? * @return * @author Ron(modify 2014.10.17) */ public JSONObject list(HttpServletRequest request) { DBObject conditionBean = new BasicDBObject(); // ? String inputname = RequestUtils.getString(request, "inputname"); String state = RequestUtils.getString(request, "state"); // ? BasicDBList values = new BasicDBList(); if (StringUtils.isNotBlank(inputname)) { Pattern pattern = Pattern.compile("^.*" + inputname + ".*$", Pattern.CASE_INSENSITIVE);// ? values.add(new BasicDBObject("name", pattern)); values.add(new BasicDBObject("contacts", pattern)); conditionBean.put("$or", values); } if (StringUtils.isNotBlank(state)) { if (StringUtils.equals(state, "exists")) { // ???? conditionBean.put("state", new BasicDBObject("$exists", false)); } else { conditionBean.put("state", state); } } // ? long count = companyapplyDao.count(TableNameConstant.T_COMPANY_APPLY, conditionBean); if (count <= 0) { return null; } // ? ?? String sortOrder = RequestUtils.getString(request, "sortOrder"); DBObject orderBy = new BasicDBObject(); if (StringUtils.isNotBlank(sortOrder)) {// StringInt orderBy.put(RequestUtils.getString(request, "sortField"), StringUtils.setOrder(sortOrder)); } else { orderBy.put("_id", StringUtils.setOrder("1")); } DBObject field = new BasicDBObject(); List<DBObject> dbList = companyapplyDao.list(TableNameConstant.T_COMPANY_APPLY, conditionBean, field, orderBy, RequestUtils.getInt(request, "pageIndex") + 1, RequestUtils.getInt(request, "pageSize")); // ?? Map<String, JSONObject> industryMap = this.ccIndustryinfoLogic.getIndustryInfoMap(); // Map<String, DBObject> areaMap = ccAreaLogic.getAreaMap(); for (int i = 0; i < dbList.size(); i++) { DBObject dbobject = dbList.get(i); // ?id?? if (CollectionUtils.isNotEmpty(industryMap)) { dbobject.put("industryName", JSONUtils.getString(industryMap.get(dbobject.get("industryuuid")), "name")); } // if (CollectionUtils.isNotEmpty(areaMap)) { dbobject.put("areaName", DBObejctUtils.getString(areaMap.get(dbobject.get("areauuid")), "name")); } } JSONObject resultBean = new JSONObject(); JSONArray json = JSONUtils.resertJSON(dbList);// _id resultBean.put("data", json.toString()); resultBean.put("total", count); return resultBean; }
From source file:com.cedac.security.acls.mongo.MongoMutableAclService.java
License:Apache License
@Override public MutableAcl updateAcl(MutableAcl acl) throws NotFoundException { Assert.notNull(acl.getId(), "Object Identity doesn't provide an identifier"); DBObject persistedAcl = getAclCollection().findOne(queryByObjectIdentity(acl.getObjectIdentity())); if (persistedAcl == null) { LOG.trace(ACL, "No ACL found for object identity {}", acl.getObjectIdentity()); throw new NotFoundException("No acl found for object identity " + acl.getObjectIdentity()); }// w w w .j av a 2 s. c o m LOG.debug(ACL, "Updating persisted ACL object"); if (acl.getParentAcl() != null) { ObjectIdentity parentOid = acl.getParentAcl().getObjectIdentity(); persistedAcl.put(parentObjectFieldName, toDBObject(parentOid)); } persistedAcl.put(ownerFieldName, toDBObject(acl.getOwner())); persistedAcl.put(entriesInheritingFieldName, acl.isEntriesInheriting()); BasicDBList list = new BasicDBList(); for (AccessControlEntry entry : acl.getEntries()) { list.add(toDBObject(entry)); } persistedAcl.put(entriesFieldName, list); getAclCollection().save(persistedAcl, writeConcern); LOG.trace(ACL, "Clearing cache including children for object identity {}", acl.getObjectIdentity()); clearCacheIncludingChildren(acl.getObjectIdentity()); LOG.trace(ACL, "Retrieve ACL via superclass."); return (MutableAcl) super.readAclById(acl.getObjectIdentity()); }
From source file:com.crosstreelabs.cognitio.service.mongo.MongoCatalogueService.java
License:Apache License
@Override public synchronized CatalogueEntry getWorkEntry() { if (!workPool.isEmpty()) { return workPool.remove(); }//from ww w . j a va2 s . c o m // Find hosts that have been recently accessed // XXX The delay time needs to be configurable int hostDelaySeconds = 45; Collection<Host> recentHosts = hostService.recentlyRequested(hostDelaySeconds); Set<ObjectId> excludedHostIds = new HashSet<>(); for (Host host : recentHosts) { excludedHostIds.add(new ObjectId(host.id)); } // Find hosts that are currently queued List<ObjectId> queuedHosts = catalogue.distinct("host", new BasicDBObject("status", "QUEUED")); for (ObjectId id : queuedHosts) { excludedHostIds.add(id); } // Exclude recently visited hosts BasicDBObject excludedHosts = new BasicDBObject("host", new BasicDBObject("$nin", excludedHostIds.toArray(new ObjectId[0]))); // Retreive pending (un-indexed) resources BasicDBObject unindexed = new BasicDBObject("status", "PENDING"); // Reindex resources older than 7 days (XXX Make configurable/calculated BasicDBObject staleResources = new BasicDBObject("$and", Arrays.asList(new BasicDBObject("last_visit", new BasicDBObject("$exists", true)), new BasicDBObject("last_visit", new BasicDBObject("$lte", new DateTime().minusDays(7).toDate())), new BasicDBObject("status", "INDEXED"))); // Now put it all together BasicDBObject and = new BasicDBObject("$and", Arrays.asList(excludedHosts, new BasicDBObject("$or", Arrays.asList(unindexed, staleResources)))); DBObject match = new BasicDBObject("$match", and); DBObject sort = new BasicDBObject("$sort", new BasicDBObject("last_updated", 1)); DBObject group = new BasicDBObject("$group", new BasicDBObject("_id", "$host").append("first", new BasicDBObject("$first", "$$ROOT"))); List<DBObject> pipeline = Arrays.asList(match, group, sort); LOGGER.debug("PIPELINE: {}", pipeline); Iterable<DBObject> refs = catalogue.aggregate(pipeline).results(); for (DBObject obj : refs) { workPool.add(fromMongoObject((DBObject) obj.get("first"))); } LOGGER.debug("WORK POOL: {}", workPool); // Update the objects in mongo to queued state BasicDBList ids = new BasicDBList(); ids.addAll(listIds(workPool)); catalogue.update(new BasicDBObject("_id", new BasicDBObject("$in", ids)), new BasicDBObject("$set", new BasicDBObject("status", "QUEUED")), false, true, WriteConcern.JOURNALED); if (workPool.isEmpty()) { return null; } return workPool.remove(); }
From source file:com.ebay.cloud.cms.dal.persistence.flatten.impl.embed.EmbedCreateCommand.java
License:Apache License
public DBObject buildCreateBody(MetaRelationship lastField, String parentPath, NewBsonEntity entity, int newVersion, MetaClass rootMetaClass, DBObject rootObject, String parentId) { BasicDBObject embedParentObject = (BasicDBObject) EmbedDBObjectFilter.filter(parentId, rootObject, rootMetaClass, null, helper); if (embedParentObject == null) { throw new CmsDalException(DalErrCodeEnum.ENTITY_NOT_FOUND, "Create, can not find embed field with Id: " + parentId); }/*w w w .j av a 2 s .c o m*/ embedParentObject.remove("_id"); // for flatten storage, the length change might differ between the embed under root and multiple level embed List<String> embedSegList = helper.getEmbedPathSegs(entity.getId(), rootMetaClass); boolean justUnderRoot = embedSegList.size() == 1; BasicDBObject setModifyObject = new BasicDBObject(); if (lastField.getCardinality() == CardinalityEnum.Many) { BasicDBList valueList = (BasicDBList) embedParentObject.get(lastField.getFlattenValueDbName()); if (valueList == null) { // creation valueList = new BasicDBList(); valueList.add(entity.getNode()); // set the value embedParentObject.put(lastField.getFlattenValueDbName(), valueList); // set the field properties setFieldProperties(lastField, setModifyObject, embedParentObject, 1, new Date(), justUnderRoot); } else { // append int size = valueList.size(); valueList.add(entity.getNode()); setFieldProperties(lastField, setModifyObject, embedParentObject, size + 1, new Date(), justUnderRoot); } } else { embedParentObject.put(lastField.getFlattenValueDbName(), entity.getNode()); setFieldProperties(lastField, setModifyObject, embedParentObject, null, new Date(), justUnderRoot); } DBObject obj = (DBObject) rootObject.get(embedFieldName); if (obj == null) { throw new CmsDalException(DalErrCodeEnum.ENTITY_NOT_FOUND, "Create, can not find embed field with Id: " + this.entity.getId()); } // update root field last modified MetaField rootEmbedfield = rootMetaClass.getFieldByFlattenValueDbName(embedFieldName); setModifyObject.put(rootEmbedfield.getFlattenPropertyValueDbName(FieldProperty.TIMESTAMP), new Date()); setModifyObject.put(embedFieldName, obj); BasicDBObject modifyBody = new BasicDBObject(); modifyBody.put("$set", setModifyObject); // increase version on root document BasicDBObject versionObject = new BasicDBObject(); versionObject.put(InternalFieldEnum.VERSION.getDbName(), 1); modifyBody.put("$inc", versionObject); buildRootUpdateObject(entity, null, modifyBody, rootMetaClass); return modifyBody; }