List of usage examples for com.mongodb BasicDBObject get
public Object get(final String key)
From source file:controllers.FilterController.java
License:Apache License
public static Graph getGraph(Filter filter, String property) { final List<String> keys = new ArrayList<String>(); final List<String> values = new ArrayList<String>(); final Graph result = new Graph(property, keys, values); final BasicDBObject query = Application.getFilterQuery(filter); final MapReduceJob job = new HistogramJob(filter.getCollection(), property, query); final Cache cache = Configurator.getDefaultConfigurator().getPersistence().getCache(); final Property p = cache.getProperty(property); long width = -1; if (p.getType().equals(PropertyType.INTEGER.toString())) { DBObject range = (DBObject) query.get("metadata." + property + ".value"); Long low = (Long) range.get("$gte"); Long high = (Long) range.get("$lte"); width = high - low + 1; //because of lte/gte HashMap<String, String> config = new HashMap<String, String>(); config.put("bin_width", width + ""); job.setConfig(config);// w ww. j a v a2 s .c om } final MapReduceOutput output = job.execute(); if (p.getType().equals(PropertyType.INTEGER.toString())) { calculateNumericHistogramResults(output, keys, values, width); } else { calculateHistogramResults(output, keys, values); } result.sort(); if (result.getKeys().size() > 100) { result.cutLongTail(); } return result; }
From source file:datapreparation.MongoStatistics.java
public void usersToUrls() { // To directly connect to a single MongoDB server (note that this will not auto-discover the primary even MongoClient mongoClient;/*www.java 2 s .c om*/ try { mongoClient = new MongoClient("localhost"); //use database DB db = mongoClient.getDB("users"); //get collection DBCollection coll = db.getCollection("urls"); //iterate with a cursor BasicDBObject query = new BasicDBObject("source", new BasicDBObject("$exists", true)); DBCursor cursor = coll.find(query); BufferedWriter writer = null; try { writer = new BufferedWriter(new FileWriter("Users_To_Urls.txt")); writer.write("url,user,time\n"); while (cursor.hasNext()) { BasicDBObject tweet = (BasicDBObject) cursor.next(); String time = tweet.get("created_at").toString(); String user = tweet.get("from_user").toString(); String urls[] = tweet.get("source").toString().replaceAll(""", "").split(";"); for (String url : urls) { if (url.matches("http.*")) { //The user posted one link, write it in the file! writer.write(url + "," + user + "," + time + "\n"); } } } } finally { cursor.close(); mongoClient.close(); writer.close(); } } catch (IOException ex) { System.out.println("Something's Wrong! " + ex); } }
From source file:dev.j.regere.respository.MongoIntermediatePersistedTable.java
License:Apache License
@Override public RegereRuleFlowWrapper load(String regereId, String commonIdentifier, Map<String, Object> currentEvent) { final BasicDBObject dbList = new BasicDBObject(ID, regereId + STRING_COLAN + commonIdentifier); if (logger.isDebugEnabled()) { logger.debug("loading intermediate event for key [" + dbList.get(ID) + "]"); }//from ww w. java 2 s . c om final DBObject dbObject = dbCollection.findOne(dbList); if (dbObject != null) { logger.info("New intermediate object found loading the object from db"); currentEvent = loadPersistedValues(currentEvent, dbObject.toMap()); } //todo store final rule passed variable and the pass re rules in mongo return new RegereRuleFlowWrapper(currentEvent, new HashSet<Integer>(10)); }
From source file:edu.slu.action.ObjectAction.java
/** * Update a given annotation. Cannot set or unset keys. * @respond with state of new object in the body */// w ww . j av a2 s. com public void patchUpdateObject() throws ServletException, Exception { Boolean historyNextUpdatePassed = false; System.out.println("trying to patch"); if (null != processRequestBody(request, true) && methodApproval(request, "patch")) { BasicDBObject query = new BasicDBObject(); JSONObject received = JSONObject.fromObject(content); if (received.containsKey("@id")) { String updateHistoryNextID = received.getString("@id"); query.append("@id", updateHistoryNextID); BasicDBObject originalObject = (BasicDBObject) mongoDBService .findOneByExample(Constant.COLLECTION_ANNOTATION, query); //The originalObject DB object boolean alreadyDeleted = checkIfDeleted(JSONObject.fromObject(originalObject)); boolean isReleased = checkIfReleased(JSONObject.fromObject(originalObject)); if (alreadyDeleted) { writeErrorResponse("The object you are trying to update is deleted.", HttpServletResponse.SC_FORBIDDEN); } else if (isReleased) { writeErrorResponse("The object you are trying to update is released. Fork to make changes.", HttpServletResponse.SC_FORBIDDEN); } else { if (null != originalObject) { BasicDBObject updatedObject = (BasicDBObject) originalObject.copy(); //A copy of the original, this will be saved as a new object. Make all edits to this variable. Set<String> update_anno_keys = received.keySet(); boolean triedToSet = false; int updateCount = 0; //If the object already in the database contains the key found from the object recieved from the user, update it barring a few special keys //Users cannot update the __rerum property, so we ignore any update action to that particular field. for (String key : update_anno_keys) { if (originalObject.containsKey(key)) { //Skip keys we want to ignore and keys that match but have matching values if (!(key.equals("@id") || key.equals("__rerum") || key.equals("objectID") || key.equals("_id")) && received.get(key) != originalObject.get(key)) { updatedObject.remove(key); updatedObject.append(key, received.get(key)); updateCount += 1; } } else { triedToSet = true; // break; } } if (triedToSet) { System.out.println("Patch meh 1"); //@cubap @theHabes We continued with what we could patch. Do we tell the user at all? //writeErrorResponse("A key you are trying to update does not exist on the object. You can set with the patch_set or put_update action.", HttpServletResponse.SC_BAD_REQUEST); } else if (updateCount == 0) { System.out.println("Patch meh 2"); addLocationHeader(received); writeErrorResponse("Nothing could be PATCHed", HttpServletResponse.SC_NO_CONTENT); } else { JSONObject newObject = JSONObject.fromObject(updatedObject);//The edited original object meant to be saved as a new object (versioning) newObject = configureRerumOptions(newObject, true); //__rerum for the new object being created because of the update action newObject.remove("@id"); //This is being saved as a new object, so remove this @id for the new one to be set. //Since we ignore changes to __rerum for existing objects, we do no configureRerumOptions(updatedObject); DBObject dbo = (DBObject) JSON.parse(newObject.toString()); String newNextID = mongoDBService.save(Constant.COLLECTION_ANNOTATION, dbo); String newNextAtID = Constant.RERUM_ID_PREFIX + newNextID; BasicDBObject dboWithObjectID = new BasicDBObject((BasicDBObject) dbo); dboWithObjectID.append("@id", newNextAtID); newObject.element("@id", newNextAtID); newObject.remove("_id"); mongoDBService.update(Constant.COLLECTION_ANNOTATION, dbo, dboWithObjectID); historyNextUpdatePassed = alterHistoryNext(updateHistoryNextID, newNextAtID); //update history.next or original object to include the newObject @id if (historyNextUpdatePassed) { System.out.println("Patch updated object: " + newNextAtID); JSONObject jo = new JSONObject(); JSONObject iiif_validation_response = checkIIIFCompliance(newNextAtID, "2.1"); jo.element("code", HttpServletResponse.SC_OK); jo.element("original_object_id", updateHistoryNextID); jo.element("new_obj_state", newObject); //FIXME: @webanno standards say this should be the response. jo.element("iiif_validation", iiif_validation_response); try { addWebAnnotationHeaders(newNextID, isContainerType(newObject), isLD(newObject)); addLocationHeader(newObject); response.addHeader("Access-Control-Allow-Origin", "*"); response.setStatus(HttpServletResponse.SC_OK); response.addHeader("Content-Type", "application/json; charset=utf-8"); response.setContentType("UTF-8"); out = response.getWriter(); out.write(mapper.writer().withDefaultPrettyPrinter().writeValueAsString(jo)); } catch (IOException ex) { Logger.getLogger(ObjectAction.class.getName()).log(Level.SEVERE, null, ex); } } else { //The error is already written to response.out, do nothing. } } } else { writeErrorResponse( "Object " + received.getString("@id") + " not found in RERUM, could not patch update.", HttpServletResponse.SC_BAD_REQUEST); } } } else { writeErrorResponse("Object did not contain an @id, could not patch update.", HttpServletResponse.SC_BAD_REQUEST); } } }
From source file:edu.slu.mongoEntity.Agent.java
public Agent(BasicDBObject dbo) { this.objectID = dbo.getObjectId("_id").toString(); this.aID = dbo.getString("@id"); this.mbox = dbo.getString("mbox"); this.mbox_sha1sum = dbo.getString("mbox_sha1sum"); this.type = dbo.getString("type"); this.created = dbo.getLong("created"); this.modified = dbo.getLong("modified"); this.group = JSONArray.fromObject(dbo.get("group")); this.personID = dbo.getString("personID"); this.organization = JSONArray.fromObject(dbo.get("organization")); }
From source file:edu.slu.mongoEntity.ProjectUserProfile.java
public ProjectUserProfile(BasicDBObject dbo) { this.objectID = dbo.getObjectId("_id").toString(); if (null != dbo.getString("userObjectID")) { this.objectID = dbo.getString("userObjectID"); }/*from ww w.j ava 2s.com*/ if (null != dbo.getString("alias")) { this.alias = dbo.getString("alias"); } if (null != dbo.getString("server_ip")) { JSONArray ja = (JSONArray) dbo.get("ls_serverIP"); this.ls_serverIP = ja.subList(0, ja.size() - 1); } this.dateCreated = dbo.getLong("date_created"); this.dateUpdated = dbo.getLong("date_updated"); if (null != dbo.getString("config")) { this.config = dbo.getString("config"); } }
From source file:edu.umass.cs.gnsserver.database.MongoRecords.java
License:Apache License
private Object getWithDotNotation(String key, BasicDBObject bson) throws JSONException { if (key.contains(".")) { int indexOfDot = key.indexOf("."); String subKey = key.substring(0, indexOfDot); BasicDBObject subBson = (BasicDBObject) bson.get(subKey); if (subBson == null) { throw new JSONException(subKey + " is null"); }/*from w w w . ja va 2 s . c o m*/ try { return getWithDotNotation(key.substring(indexOfDot + 1), subBson); } catch (JSONException e) { throw new JSONException(subKey + "." + e.getMessage()); } } else { Object result = bson.get(key); return result; } }
From source file:es.bsc.amon.controller.AppsDBMapper.java
License:Open Source License
public void addAppInstance(String appInstanceJson) { BasicDBObject dbo = (BasicDBObject) JSON.parse(appInstanceJson); BasicDBObject data = ((BasicDBObject) dbo.get(FIELD_DATA)); if (data == null || dbo.get(FIELD_APP_ID) == null || dbo.get(FIELD_INSTANCE_ID) == null || data.get(FIELD_DATA_START) == null || data.get(FIELD_DATA_END) == null || data.get(FIELD_DATA_POWER) == null) { throw new AppException("The App document must have the following structure:\n" + "{'appId' : ...\n" + "'instanceId' : ...\n" + "'data' : {\n" + "\t'start' : ....\n" + "\t'end' : ....\n" + "\t'power' : ....\n" + "}}"); }/*from www. ja v a 2s . c om*/ long timestamp = System.currentTimeMillis(); dbo.put(FIELD_TIMESTAMP, timestamp); colAppInstances.insert(dbo); }
From source file:eu.cassandra.server.mongo.util.MongoDBQueries.java
License:Apache License
/** * /* ww w . j av a 2s. c o m*/ * @param coll * @param entityName * @param cid * @param successMsg * @return */ public DBObject getInternalEntity(HttpHeaders httpHeaders, String coll, String entityName, String cid, String successMsg) { BasicDBObject internalEntity = null; try { BasicDBObject query = new BasicDBObject(entityName + ".cid", new ObjectId(cid)); BasicDBObject fields = new BasicDBObject(entityName, 1); DBObject result = new MongoDBQueries().executeFindQuery(httpHeaders, coll, query, fields, "Get " + entityName + " with cid=" + " from " + coll); @SuppressWarnings("unchecked") Vector<DBObject> data = (Vector<DBObject>) result.get("data"); BasicDBList internalEntities = (BasicDBList) data.get(0).get(entityName); for (int i = 0; i < internalEntities.size(); i++) { BasicDBObject entity = (BasicDBObject) internalEntities.get(i); if (cid.equals(entity.get("cid").toString())) { internalEntity = entity; if (successMsg == null) successMsg = "Internal entity " + entityName + " with cid=" + cid + " from collection=" + coll + " successfully retrieved"; return jSON2Rrn.createJSON(internalEntity, successMsg); } } throw new MongoRefNotFoundException("RefNotFound: Cannot get internal entity " + entityName + " with cid=" + cid + " from collection: " + coll); } catch (Exception e) { return jSON2Rrn.createJSONError("GetInternalEntityError: Cannot get internal entity " + entityName + " with cid=" + cid + " from collection: " + coll, e); } }
From source file:eu.cassandra.server.mongo.util.MongoDBQueries.java
License:Apache License
/** * curl -i --header "dbname:run_id" 'http://localhost:8080/cassandra/api/results?inst_id=instID_&aggr_unit=3&metric=1&from=3&to=100' * //from www . j a v a 2s .co m * @param installationId * @param metric * @param aggregationUnit * @param fromTick * @param toTick * @return */ public DBObject mongoResultQuery(HttpHeaders httpHeaders, String installationId, String metricS, String aggregationUnitS, String fromTickS, String toTickS) { try { String runId = getDbNameFromHTTPHeader(httpHeaders); if (runId == null && installationId == null) throw new RestQueryParamMissingException( "QueryParamMissing: Both run_id and installation_id are null"); String aggrUnit = " (Minute)"; String defaultAggrUnit = " (Minute)"; Integer aggregationUnit = null; Integer defaultAggregationUnit = null; if (aggregationUnitS != null) { aggregationUnit = Integer.parseInt(aggregationUnitS); aggrUnit = " " + aggregationUnit + " Minute" + (aggregationUnit == 1 ? "" : "s") + ")"; } int numberOfDays = Integer.parseInt( DBConn.getConn(runId).getCollection("sim_param").findOne().get("numberOfDays").toString()); if (numberOfDays == 1) { defaultAggregationUnit = 5; defaultAggrUnit = " (5 Minutes)"; } else if (numberOfDays <= 5) { defaultAggregationUnit = 15; defaultAggrUnit = " (15 Minutes)"; } else if (numberOfDays <= 20) { defaultAggregationUnit = 60; defaultAggrUnit = " (1 Hour)"; } else if (numberOfDays <= 60) { defaultAggregationUnit = 180; defaultAggrUnit = " (3 Hours)"; } else if (numberOfDays <= 360) { defaultAggregationUnit = 720; defaultAggrUnit = " (12 Hours)"; } if (aggregationUnit == null) { aggregationUnit = defaultAggregationUnit; aggrUnit = defaultAggrUnit; } Integer fromTick = null; if (fromTickS != null) fromTick = Integer.parseInt(fromTickS); Integer toTick = null; if (toTickS != null) toTick = Integer.parseInt(toTickS); String coll = MongoResults.COL_AGGRRESULTS; if (aggregationUnit == null || aggregationUnit <= 0) aggregationUnit = 1; if (installationId != null) coll = MongoResults.COL_INSTRESULTS; String yMetric = ACTIVE_POWER_P; if (metricS != null && metricS.equalsIgnoreCase(REACTIVE_POWER_Q)) yMetric = REACTIVE_POWER_Q; //db.inst_results.find({inst_id:"dszfs123",tick:{$gt:1}}).sort({tick:1}).pretty() //db.inst_results.group( // { // keyf:function(doc) // {var key=new NumberInt(doc.tick/4); return {x:key} // } , // cond:{inst_id:"instID_"}, // reduce:function(obj,prev) // {prev.csum+=obj.p}, // initial:{csum:0} // } //) BasicDBObject condition = null; if (installationId != null || fromTick != null || toTick != null) condition = new BasicDBObject(); if (installationId != null) condition.append("inst_id", installationId); if (fromTick != null && toTick != null) condition.append("tick", BasicDBObjectBuilder.start("$gte", fromTick).add("$lte", toTick).get()); else if (fromTick != null) condition.append("tick", new BasicDBObject("$gte", fromTick)); else if (toTick != null) condition.append("tick", new BasicDBObject("$lte", toTick)); BasicDBObject groupCmd = new BasicDBObject("ns", coll); groupCmd.append("$keyf", "function(doc){var key=new NumberInt(doc.tick/" + aggregationUnit + "); return {x:key}}"); if (condition != null) groupCmd.append("cond", condition); groupCmd.append("$reduce", "function(obj,prev){prev.y+=obj." + yMetric + "}"); groupCmd.append("initial", new BasicDBObject("y", 0)); @SuppressWarnings("deprecation") BasicDBList dbList = (BasicDBList) DBConn.getConn(getDbNameFromHTTPHeader(httpHeaders)) .getCollection(coll).group(groupCmd); if (aggregationUnit > 1) { for (int i = 0; i < dbList.size(); i++) { BasicDBObject obj = (BasicDBObject) dbList.get(i); obj.put("y", Double.parseDouble(obj.get("y").toString()) / aggregationUnit); } } return jSON2Rrn.createJSONPlot(dbList, "Data for plot retrieved successfully", "Consumption " + (yMetric.equalsIgnoreCase(REACTIVE_POWER_Q) ? "Reactive Power" : "Active Power"), "Time" + aggrUnit, yMetric.equalsIgnoreCase(REACTIVE_POWER_Q) ? "VAr" : "W", defaultAggregationUnit, numberOfDays); } catch (Exception e) { e.printStackTrace(); return jSON2Rrn.createJSONError("Error in retrieving results", e.getMessage()); } }