List of usage examples for com.mongodb BasicDBObject append
@Override public BasicDBObject append(final String key, final Object val)
From source file:com.ibm.bluemix.smartveggie.dao.UserDaoImpl.java
@Override public BasicDBObject updateUser(UserDTO userDTO) { BasicDBObject updates = null;//from ww w. j a v a 2 s.c o m try { System.out.println("Updating Users..."); DB db = MongodbConnection.getMongoDB(); DBCollection col = db.getCollection(ICollectionName.COLLECTION_USERS); BasicDBObject query = new BasicDBObject(); query.append("userName", userDTO.getUserName()); System.out.println("Updating Record: " + query); updates = new BasicDBObject(); if ((userDTO.getFirstName() != null) && (userDTO.getFirstName() != "")) updates.append("firstName", userDTO.getFirstName()); if ((userDTO.getLastName() != null) && (userDTO.getLastName() != "")) updates.append("lastName", userDTO.getLastName()); if ((userDTO.getAddressLine1() != null) && (userDTO.getAddressLine1() != "")) updates.append("addressLine1", userDTO.getAddressLine1()); if ((userDTO.getAddressLine2() != null) && (userDTO.getAddressLine2() != "")) updates.append("addressLine2", userDTO.getAddressLine2()); if ((userDTO.getAge() > 0) && (userDTO.getAge() < 100)) updates.append("age", userDTO.getAge()); if ((userDTO.getSex() != null) && (userDTO.getSex() != "")) updates.append("sex", userDTO.getSex()); if ((userDTO.getUserName() != null) && (userDTO.getUserName() != "")) updates.append("userName", userDTO.getUserName()); if ((userDTO.getPassword() != null) && (userDTO.getPassword() != "")) updates.append("password", userDTO.getPassword()); if ((userDTO.getCity() != null) && (userDTO.getCity() != "")) updates.append("city", userDTO.getCity()); if ((userDTO.getPinCode() != null) && (userDTO.getPinCode() != "")) updates.append("pin", userDTO.getPinCode()); if ((userDTO.getUserTypeCode() != null) && (userDTO.getUserTypeCode() != "")) { updates.append("userType", userDTO.getUserTypeCode()); if (userDTO.getUserTypeCode().equalsIgnoreCase("vendor")) { if ((userDTO.getLicenseNo() != null) && (userDTO.getLicenseNo() != "")) { updates.append("licenseNo", userDTO.getLicenseNo()); //Process the date field SimpleDateFormat formatter = new SimpleDateFormat("dd/mm/yyyy"); String validFrom = userDTO.getValidFrom(); String validTo = userDTO.getValidTo(); try { Date validFromDate = formatter.parse(validFrom); Date validToDate = formatter.parse(validTo); System.out.println(validFromDate); updates.append("validFrom", validFromDate); updates.append("validTo", validToDate); //System.out.println(formatter.format(validFromDate)); } catch (Exception e) { e.printStackTrace(); } } } else if (userDTO.getUserTypeCode().equalsIgnoreCase("regulator")) { if (userDTO.getRegulatingCityCode() != null && userDTO.getRegulatingCityCode() != null) { updates.append("regulatingCityCode", userDTO.getRegulatingCityCode()); } if (userDTO.getRegulatingCityCode() != null && userDTO.getRegulatingCityCode() != null) { updates.append("regulatingCityName", userDTO.getRegulatingCityName()); } } } System.out.println("Querying for update: " + query); col.update(query, updates); System.out.println("col after update" + col.toString() + col.getCount()); } catch (Exception e) { throw e; } return updates; }
From source file:com.ibm.bluemix.smartveggie.dao.UserDaoImpl.java
@Override public List<BasicDBObject> retrieveAllUsersForType(String userTypeCode) { List<BasicDBObject> listDBObjects = null; try {//from ww w .j a va2 s . c o m System.out.println("Retrieving All User of Type..." + userTypeCode); listDBObjects = new ArrayList<BasicDBObject>(); DB db = MongodbConnection.getMongoDB(); DBCollection col = db.getCollection(ICollectionName.COLLECTION_USERS); BasicDBObject query = new BasicDBObject(); if ((userTypeCode != null) && (userTypeCode != "")) query.append("userType", userTypeCode); System.out.println("Querying for: " + query); DBCursor cursor = col.find(query); BasicDBObject obj = null; while (cursor.hasNext()) { obj = (BasicDBObject) cursor.next(); System.out.println("Retrieved: " + obj); listDBObjects.add(obj); } cursor.close(); } catch (Exception e) { throw e; } return listDBObjects; }
From source file:com.ibm.db2j.MongoDB.java
License:Open Source License
/** * This method adds an operator to the mongo query to enforce the derby qualifier specified. * @param mongoConditions - Object representing the conditions of a mongoDB query. * This will be modified to enforce the qualifier condition * @param qual - A derby format qualifier, holding a condition that should be added to the query. *//* www . j a v a2 s. c o m*/ public void addMongoOperator(BasicDBObject mongoConditions, Qualifier qual) { try { // work out the two component parts - the field and the value being compared String mongoFieldName = getMetaData().getColumnName(qual.getColumnId() + 1); Object mongoValue = qual.getOrderable().getObject(); if (qual.getOperator() == Orderable.ORDER_OP_EQUALS) { //equals operator is a special case if (qual.negateCompareResult()) { mongoConditions.append(mongoFieldName, new BasicDBObject("$ne", mongoValue)); //$ne is the mongo "not equals" operator, so this is "field != value" } else { mongoConditions.append(mongoFieldName, mongoValue); //add a condition that field = value } } else { String mongoOperatorText = mongoOperatorLookup(qual.getOperator()); if (qual.negateCompareResult()) { // add a condition comparing the field and value with the negated operator mongoConditions.append(mongoFieldName, new BasicDBObject("$not", new BasicDBObject(mongoOperatorText, mongoValue))); } else { // add a condition comparing the field and value with the operator mongoConditions.append(mongoFieldName, new BasicDBObject(mongoOperatorText, mongoValue)); } } } catch (SQLException e) { // This happens if we cannot resolve the qualifier metadata. // log the exception and carry on without this qualifier. logger.logException(MongoMessages.DSWRAPPER_MONGODB_QUALIFIER_META_DATA_ERROR, "Meta Data resolution failed for " + getPrefix(), e); } catch (StandardException e) { // This happens when the qualifier.getOrderable throws an error. // log the exception and carry on without this qualifier. logger.logException(MongoMessages.DSWRAPPER_MONGODB_QUALIFIER_ACCESS_ERROR, "Qualifier error for: " + qual.toString(), e); } }
From source file:com.ibm.db2j.MongoDB.java
License:Open Source License
/** * This method adds an operator to the mongo query to enforce the derby qualifiers specified. * @param query - Object representing the conditions of a mongoDB query. * This will be modified to enforce the qualRow conditions * @param qualRow - an array of derby database qualifiers, holding a set of conditions * that should be added to the query. * @param operator - indicates how the qualRow conditions should be combined with the query - "OR" or "AND". *//*w w w . j a v a 2 s.com*/ public void addMongoOperatorRow(BasicDBObject query, Qualifier qualRow[], CombinationOperator operator) { if (qualRow == null || qualRow.length == 0) { // Don't include any entry for this row. } else if (qualRow.length == 1) { // just include the single entry addMongoOperator(query, qualRow[0]); } else { // we have > 1 qualifier so they need including in a list, prefixed by the // necessary operator. String combinationText; switch (operator) { case OR: combinationText = "$or"; break; case AND: combinationText = "$and"; break; default: // throw exception combinationText = "$invalid"; } // construct a separate sub-list of conditions to hold the qualifiers. BasicDBList insideOperatorList = new BasicDBList(); addMongoOperators(insideOperatorList, qualRow); query.append(combinationText, insideOperatorList); } }
From source file:com.ifactory.service.weather.photo.PhotoService.java
License:Apache License
private BasicDBObject setGeoCoord(double lat, double lng, double radius) { BasicDBObject query = new BasicDBObject(); BasicDBList geo = new BasicDBList(); geo.add(lat);// w ww. jav a 2 s. co m geo.add(lng); BasicDBList center = new BasicDBList(); center.add(geo); center.add(radius); query.append("geo.coordinates", new BasicDBObject("$within", new BasicDBObject("$center", center))); return query; }
From source file:com.ifactory.service.weather.photo.PhotoService.java
License:Apache License
public ArrayList<Photo> get() { DB db = mongoClient.getDB(this.dbName); DBCollection coll = db.getCollection(PHOTO_COLLECTION); BasicDBObject query = null; DBCursor cursor = null;/*from w ww. j a va 2s . co m*/ ArrayList<Photo> photoList = new ArrayList(); int weatherClassMin = -1; int weatherClassMax = -1; double rad = this.radius; while (true) { // If latitude and longitude were given, append geo search query if (this.lat != UNAVAILABLE_LATITUDE && this.lng != UNAVAILABLE_LONGITUDE) { query = setGeoCoord(this.lat, this.lng, rad); } else { query = new BasicDBObject(); } // It the weather Id has given, append weather search query if (this.weatherId > 0) { if (weatherClassMin == -1 && weatherClassMax == -1) { query.append("weather", this.weatherId); } else { System.out.println("query with weatherClassMin(" + weatherClassMin + ") and weatherClassMax(" + weatherClassMax + ")"); query.append("weather", new BasicDBObject("$gte", weatherClassMin).append("$lte", weatherClassMax)); System.out.println(query.toString()); } } try { cursor = coll.find(query).limit(this.limit); if (cursor.count() > 0) { System.out.println( "photo found(lat: " + this.lat + ", lng: " + this.lng + ", radius: " + rad + ")"); break; } else if (this.growable == false || rad >= UNAVAILABLE_LATITUDE) { if (rad >= UNAVAILABLE_LATITUDE) { rad = this.radius / 2; if (weatherClassMin == -1 && weatherClassMax == -1) { // In this case, there is no proper photos by the given weather. // Let's find any photos bound for same weather class. weatherClassMin = ((int) this.weatherId / 100) * 100; weatherClassMax = (((int) this.weatherId / 100) + 1) * 100; System.out.println("weatherClassMin and weatherClassMax exist"); } else if (this.weatherId > 0) { this.weatherId = 0; System.out.println("weatherid goes to zero"); continue; } else { break; } } else { break; } } } catch (CommandFailureException e) { cursor = null; break; } rad = rad * 2; } try { while (cursor != null && cursor.hasNext()) { DBObject obj = cursor.next(); Photo.Builder b = new Photo.Builder((String) obj.get("name"), ((Number) obj.get("weather")).intValue()); ArrayList<Double> coord = ((ArrayList<Double>) ((DBObject) obj.get("geo")).get("coordinates")); b.geoCoord(coord.get(0), coord.get(1)).day(((Boolean) obj.get("day")).booleanValue()) .timestamp(((Number) obj.get("timestamp")).longValue()).origin(this.origin); photoList.add(b.build()); } } finally { if (cursor != null) { cursor.close(); } } return photoList; }
From source file:com.ikanow.infinit.e.api.custom.mapreduce.CustomHandler.java
License:Open Source License
private String getCustomInputCollection(String inputColl, List<ObjectId> communityIds) { String output = null;//from w w w . j a va 2 s.c o m //if not one of the standard collections, see if its in custommr.customlookup List<Object> searchTerms = new ArrayList<Object>(); try { ObjectId jid = new ObjectId(inputColl); searchTerms.add(new BasicDBObject(CustomMapReduceJobPojo._id_, jid)); } catch (Exception e) { //oid failed, will only add title } searchTerms.add(new BasicDBObject("jobtitle", inputColl)); try { //find admin entry BasicDBObject query = new BasicDBObject(CustomMapReduceJobPojo.communityIds_, new BasicDBObject(DbManager.in_, communityIds.toArray())); query.append(DbManager.or_, searchTerms.toArray()); DBObject dbo = DbManager.getCustom().getLookup().findOne(query); if (dbo != null) { CustomMapReduceJobPojo cmr = CustomMapReduceJobPojo.fromDb(dbo, CustomMapReduceJobPojo.class); output = cmr._id.toString(); } } catch (Exception exc) { //no tables were found leave output null } return output; }
From source file:com.ikanow.infinit.e.api.knowledge.processing.ScoringUtils.java
License:Open Source License
private void stage4_prepareEntsForOutput(LinkedList<BasicDBObject> entityReturn) { if (_s0_nNumEntsReturn > 0) { // (else entities not enabled) for (EntSigHolder qsf = _s3_pqEnt.poll(); null != qsf; qsf = _s3_pqEnt.poll()) // (start with lowest ranking) {/* ww w. j a v a2 s . c o m*/ BasicDBObject ent = qsf.unusedDbo; if (null == ent) { int nTries = 0; if (null != qsf.entityInstances) { // (should never be null but just to be on the safe side... for (TempEntityInDocBucket tefb : qsf.entityInstances) { // (Try to find an entity that wasn't promoted ie can now be re-used // if we can't find one quite quickly then bail out and we'll pay the cost of cloning it) if (!tefb.doc.bPromoted) { ent = tefb.dbo; break; } else if (++nTries > 10) { break; } } if (null == ent) { ent = qsf.entityInstances.get(0).dbo; } } else { // (no entityInstances, something alias-related has gone wrong, just skip) continue; } } //TESTED qsf.entityInstances = null; // (don't need this any more, can be gc'd) try { if (null != qsf.aliasInfo) { if (!qsf.index.equals(qsf.aliasInfo.getIndex())) { ent.put(EntityPojo.index_, qsf.aliasInfo.getIndex()); ent.put(EntityPojo.disambiguated_name_, qsf.aliasInfo.getDisambiguatedName()); ent.put(EntityPojo.type_, qsf.aliasInfo.getType()); ent.put(EntityPojo.dimension_, qsf.aliasInfo.getDimension()); if (null != qsf.aliasInfo.getGeotag()) { BasicDBObject aliasedGeoTag = new BasicDBObject(); aliasedGeoTag.put(GeoPojo.lat_, qsf.aliasInfo.getGeotag().lat); aliasedGeoTag.put(GeoPojo.lon_, qsf.aliasInfo.getGeotag().lon); ent.put(EntityPojo.geotag_, aliasedGeoTag); if (null != qsf.aliasInfo.getOntology_type()) { ent.put(EntityPojo.ontology_type_, qsf.aliasInfo.getOntology_type()); } } //TESTED } } //TESTED if (null == ent.get(EntityPojo.datasetSignificance_)) { // Not getting promoted so need to add fields... if (Double.isNaN(qsf.datasetSignificance)) { ent.put("datasetSignificance", 0.0); } else { ent.put(EntityPojo.datasetSignificance_, qsf.datasetSignificance); } ent.put(EntityPojo.queryCoverage_, qsf.queryCoverage); ent.put(EntityPojo.averageFreq_, qsf.avgFreqOverQuerySubset); if (qsf.nTotalSentimentValues > 0) { ent.put(EntityPojo.positiveSentiment_, qsf.positiveSentiment); ent.put(EntityPojo.negativeSentiment_, qsf.negativeSentiment); ent.put(EntityPojo.sentimentCount_, qsf.nTotalSentimentValues); } } else { // (... but can just use it without cloning) BasicDBObject ent2 = new BasicDBObject(); for (Map.Entry<String, Object> kv : ent.entrySet()) { ent2.append(kv.getKey(), kv.getValue()); } ent = ent2; } ent.removeField(EntityPojo.relevance_); if (Double.isNaN(qsf.maxDocSig)) { ent.put(EntityPojo.significance_, 0.0); } else { ent.put(EntityPojo.significance_, qsf.maxDocSig); } ent.put(EntityPojo.frequency_, (long) qsf.maxFreq); entityReturn.addFirst(ent); } catch (Exception e) { // Probably a JSON error, just carry on String title = ent.getString(EntityPojo.index_); logger.error(title + ": " + e.getMessage()); } //TESTED } } //TESTED }
From source file:com.ikanow.infinit.e.api.social.sharing.ShareHandler.java
License:Open Source License
/** * searchShares/*w w w .j a v a 2 s . c o m*/ * @param personIdStr * @param searchby * @param idStrList * @param sharetypes * @param skip * @param limit * @return */ //TODO (): be able to specify not returning content? public ResponsePojo searchShares(String personIdStr, String searchby, String idStrList, String sharetypes, String skip, String limit, boolean ignoreAdmin, boolean returnContent, boolean searchParent) { ResponsePojo rp = new ResponsePojo(); /////////////////////////////////////////////////////////////////////////////////////////////// // Sample search queries // share/search/ // share/search/?type=binary // share/search/?searchby=person&id=admin_infinite@ikanow.com // share/search/?searchby=community&id=4d88d0f1f9a624a4b0c8bd71,4d88d0f1f9a624a4b0c8bd72&type=dataset&skip=0&limit=10 /////////////////////////////////////////////////////////////////////////////////////////////// // Create Query Object BasicDBObject query = new BasicDBObject(); HashSet<ObjectId> memberOf = SocialUtils.getUserCommunities(personIdStr); // (need this to sanitize share communities even if searching explicitly by community) boolean bAdmin = false; if (!ignoreAdmin) { bAdmin = RESTTools.adminLookup(personIdStr); } // Community search, supports one or more communities._id values if ((searchby != null) && (searchby.equalsIgnoreCase("community") || searchby.equalsIgnoreCase("communities"))) { query = getCommunityQueryObject(query, idStrList, personIdStr, ignoreAdmin, bAdmin, memberOf, searchParent); //TESTED regex and list versions (single and multiple), no allowed commmunity versions } else if ((searchby != null) && searchby.equalsIgnoreCase("person")) { if ((ignoreAdmin || !bAdmin) || (null == idStrList)) { // not admin or no ids spec'd query.put("owner._id", new ObjectId(personIdStr)); } //TESTED else { // admin and spec'd - can either be an array of ids or an array of email addresses memberOf = null; // (also returns all the communities in the mapper below) // List of communities to search on String[] idStrArray = idStrList.split(","); List<ObjectId> peopleIds = new ArrayList<ObjectId>(); for (String idStr : idStrArray) { try { ObjectId id = new ObjectId(idStr); peopleIds.add(id); } catch (Exception e) { // Try as people's email addresses query.put("owner.email", new BasicDBObject("$in", idStrArray)); peopleIds.clear(); break; } //TESTED } if (peopleIds.size() > 0) { BasicDBObject communities = new BasicDBObject(); communities.append("$in", peopleIds); query.put("owner._id", communities); } //TESTED } //TESTED: nobody, ids, emails } else { // Defaults to all communities to which a user belongs (or everything for admins) if (ignoreAdmin || !bAdmin) { if (null != memberOf) { query.put("communities._id", new BasicDBObject("$in", memberOf)); } else { // (some error but we'll let this go if the share has no security) query.put("communities", new BasicDBObject("$exists", false)); } } else { memberOf = null; // (also returns all the communities in the mapper below) } } // Search on share type or types if (sharetypes != null && sharetypes.length() > 0) { if (sharetypes.split(",").length > 1) { BasicDBObject types = new BasicDBObject(); String[] typeArray = sharetypes.split(","); types.append("$in", typeArray); query.put("type", types); } else { query.put("type", sharetypes); } } //REMOVING BINARY, if you want to return it you can't do deserialize on it BasicDBObject removeFields = new BasicDBObject("binaryData", false); if (!returnContent) { removeFields.put("share", false); } try { DBCursor dbc = null; // Attempt to parse skip and limit into ints if they aren't null int numToSkip = 0; int limitToNum = 0; if (skip != null) try { numToSkip = Integer.parseInt(skip); } catch (Exception e) { } if (limit != null) try { limitToNum = Integer.parseInt(limit); } catch (Exception e) { } // Run find query based on whether or not to skip and limit the number of results to return if (skip != null && limit != null) { dbc = (DBCursor) DbManager.getSocial().getShare().find(query, removeFields).skip(numToSkip) .limit(limitToNum); } else if (skip != null && limit == null) { dbc = (DBCursor) DbManager.getSocial().getShare().find(query, removeFields).skip(numToSkip); } else if (skip == null && limit != null) { dbc = (DBCursor) DbManager.getSocial().getShare().find(query, removeFields).limit(limitToNum); } else { dbc = (DBCursor) DbManager.getSocial().getShare().find(query, removeFields); } List<SharePojo> shares = SharePojo.listFromDb(dbc, SharePojo.listType()); if (!shares.isEmpty()) { Iterator<SharePojo> shareIt = shares.iterator(); while (shareIt.hasNext()) { SharePojo share = shareIt.next(); if (null != share.getDocumentLocation()) { try { if ((null == share.getType()) || !share.getType().equalsIgnoreCase("binary")) { // (ignore binary references) share.setShare(this.getReferenceString(share)); } //TESTED } catch (Exception e) { // couldn't access data, just remove data from list share.setShare("{}"); } } } //TESTED rp.setData(shares, new SharePojoApiMap(memberOf)); rp.setResponse(new ResponseObject("Share", true, "Shares returned successfully")); } else { rp.setResponse(new ResponseObject("Share", true, "No shares matching search critera found.")); } } catch (Exception e) { logger.error("Exception Message: " + e.getMessage(), e); rp.setResponse(new ResponseObject("Share", false, "Unable to search for shares: " + e.getMessage())); } return rp; }
From source file:com.ikanow.infinit.e.api.social.sharing.ShareHandler.java
License:Open Source License
private BasicDBObject getCommunityQueryObject(BasicDBObject query, String idStrList, String personIdStr, boolean ignoreAdmin, boolean bAdmin, HashSet<ObjectId> memberOf, boolean searchParent) { if (idStrList != null && idStrList.length() > 0) { idStrList = allowCommunityRegex(personIdStr, idStrList, true); // (allows regex, plus multiple communities) // List of communities to search on String[] idStrArray = idStrList.split(","); List<ObjectId> communityIds = new ArrayList<ObjectId>(); for (String idStr : idStrArray) { try { ObjectId id = new ObjectId(idStr); if (isMemberOwnerAdminOfCommunity(id, ignoreAdmin, bAdmin, memberOf)) { communityIds.add(id); }/* ww w. j a v a 2 s . com*/ } catch (Exception ex) { } } if (communityIds.size() > 0) { if (searchParent) { //get the comm objects for these communities, so we can grab all their parents and add them to the query BasicDBObject communities = new BasicDBObject(); communities.append("$in", getParentIds(communityIds, personIdStr, ignoreAdmin, bAdmin, memberOf)); query.put("communities._id", communities); } else { //otherwise just use the given commids BasicDBObject communities = new BasicDBObject(); communities.append("$in", communityIds); query.put("communities._id", communities); } } else { // (some error but we'll let this go if the share has no security) query.put("communities", new BasicDBObject("$exists", false)); } } else { // (some error but we'll let this go if the share has no security) query.put("communities", new BasicDBObject("$exists", false)); } return query; }