List of usage examples for com.mongodb.util JSON parse
public static Object parse(final String jsonString)
Parses a JSON string and returns a corresponding Java object.
From source file:es.bsc.amon.controller.AppsDBMapper.java
License:Open Source License
/** * * @param start/* ww w . j a v a 2s. c o m*/ * @param end * @param showInstances if true, shows instances information instead of nodes information * @return */ public ObjectNode getAllApps(long start, long end, boolean showInstances) { DBObject query = (DBObject) JSON.parse("{ '$or' : [" + "{ '$and' : [ { timestamp : { '$gte' : " + start + " }}, { timestamp : {'$lte' : " + end + "}} ] }," + "{ '$and' : [ { endtime : { '$gte' : " + start + " }}, { endtime : {'$lte' : " + end + "}} ] }" + "]}"); //DBObject orderby = new BasicDBObject("timestamp":-1); BasicDBList ret = DBManager.instance.find(EventsDBMapper.COLL_NAME, query); Map<String, Set<String>> appsInfo = new HashMap<>(); Iterator<Object> iter = ret.iterator(); while (iter.hasNext()) { DBObject event = (DBObject) iter.next(); try { String appName = event.get(EventsDBMapper.APPID).toString(); Object node = event.get(showInstances ? EventsDBMapper.INSTANCEID : EventsDBMapper.NODEID); String nodeName = node == null ? "" : node.toString(); Set<String> appSet = appsInfo.get(appName); if (appSet == null) { appSet = new TreeSet<String>(); appsInfo.put(appName, appSet); } appSet.add(nodeName); } catch (NullPointerException ex) { Logger.warn("This element did not parsed as an application: " + event.toString() + ". Removing it from DB..."); try { EventsDBMapper.getInstance().remove(event); } catch (Exception e) { Logger.error("Cannot remove it from database"); } } } ObjectNode all = new ObjectNode(JsonNodeFactory.instance); for (Map.Entry<String, Set<String>> entry : appsInfo.entrySet()) { ArrayNode nodes = new ArrayNode(JsonNodeFactory.instance); for (String n : entry.getValue()) { nodes.add(n); } all.put(entry.getKey(), nodes); } return all; }
From source file:es.bsc.amon.controller.AppsDBMapper.java
License:Open Source License
public String getFinishedAppInstances(long start, long end, int limit) { DBObject query = (DBObject) JSON.parse("{ '$or' : [" + "{ '$and' : [ { timestamp : { '$gte' : " + start + " }}, { timestamp : {'$lte' : " + end + "}} ] }," + "{ '$and' : [ { endtime : { '$gte' : " + start + " }}, { endtime : {'$lte' : " + end + "}} ] }" + "]}"); BasicDBList ret = DBManager.instance.find(COLL_NAME, query, null, limit); return ret.toString(); }
From source file:es.bsc.amon.controller.EventsDBMapper.java
License:Open Source License
public ObjectNode storeEvent(ObjectNode event) { long timestamp = System.currentTimeMillis(); if (event.get(EventsDBMapper.TIMESTAMP) == null) { event.put(EventsDBMapper.TIMESTAMP, timestamp); } else {//from ww w .j a va2 s . c o m timestamp = event.get(EventsDBMapper.TIMESTAMP).asLong(); } DBObject dbo = (DBObject) JSON.parse(event.toString()); if (dbo.get(ENDTIME) == null) { dbo.put(ENDTIME, -1L); } colEvents.save(dbo); // return stored id and timestamp ObjectNode on = new ObjectNode(JsonNodeFactory.instance); on.put(_ID, dbo.get(_ID).toString()); on.put(TIMESTAMP, timestamp); return on; }
From source file:es.bsc.amon.controller.EventsDBMapper.java
License:Open Source License
public JsonNode getLastEvent(String appId, String nodeId) { DBObject query = (DBObject) JSON.parse("{$orderby : {timestamp : -1}, $data : { $and : [ { appId : \"" + appId + "\" }, { nodeId : \"" + nodeId + "\"} ] } }"); return Json.parse(DBManager.instance.findOne(COLL_NAME, query).toString()); }
From source file:es.bsc.amon.controller.QueriesDBMapper.java
License:Open Source License
/** * Uses the MongoDB Json query language/*w w w . j a v a 2 s . co m*/ * @param query * @return */ public ArrayNode aggregate(JsonNode query) { Object raw = JSON.parse(query.toString()); ArrayNode ret = new ArrayNode(JsonNodeFactory.instance); if (raw instanceof BasicDBObject) { ret = (ArrayNode) Json.parse(EventsDBMapper.getInstance().aggregate((BasicDBObject) raw).toString()); } else if (raw instanceof BasicDBList) { ret = (ArrayNode) Json.parse(EventsDBMapper.getInstance().aggregate((BasicDBList) raw).toString()); } return ret; }
From source file:eu.artist.cloud.auditors.AbstractedAvailabilityLogger.java
License:Open Source License
/** * @param args// ww w . ja v a 2s .c om */ public void logAvailability(ArrayList<String> TemplateIDs, String DBuser, String DBpass, String databaseIP) throws UnknownHostException, MongoException { // TODO Auto-generated method stub //needs to be periodic - but periodicity may be on the previous level-> Availability Auditor //better on the Availability Auditor level, since it will have refreshed also the state //needs to raise one thread per node, concurrent requests for all nodes? //sla is per template id? logically yes, so thread must be per template id //mongodb connection //we need to pass an object that will be the DB record and will contain all necessary information //this object will be transformed to json //more efficient to pass an arraylist of these objects (for all template IDs in one sample) and make once //the connection to the DB (for needed in the basic operation) for (String record : TemplateIDs) { Mongo mongoClient = new Mongo(databaseIP); DB db = mongoClient.getDB("3alib"); System.out.println("Host address for Backend DB:" + databaseIP); Set<String> colls = db.getCollectionNames(); for (String s : colls) { System.out.println("These are the collections... " + s); } DBCollection coll = db.getCollection("log_samples"); //log sample /*BasicDBObject doc = new BasicDBObject("name1", "MongoDB2"). append("type", "database"). append("count", 1). append("info", new BasicDBObject("x", 203).append("y", 102)); */ //DBObject obj=new DBObject(); JSON jsonObj = new JSON(); DBObject obj = (DBObject) jsonObj.parse(record); //BasicDBObject doc=new BasicDBObject(record); ObjectId obid = new ObjectId(); //System.out.println("This is the id:"+obj.get("_id")); coll.insert(obj); DBObject myDoc = coll.findOne(); //System.out.println(myDoc); //coll. mongoClient.close(); //log file must be per template ID so that it can be appended each time, if we start stop the auditing action //ideally templateID_month_year //return 0; } System.out.println("Records included"); }
From source file:eu.cassandra.server.api.csn.CSNClusters.java
License:Apache License
@PUT public Response updateClusterWithPricingIDs(String message) { JSONtoReturn jSON2Rrn = new JSONtoReturn(); DBObject obj = null;/* w w w. j a v a 2 s . c o m*/ try { obj = (DBObject) JSON.parse(message); new JSONValidator().isValid(message, JSONValidator.CLUSTER_SCHEMA); obj.put("_id", new ObjectId(obj.get("_id").toString())); DBConn.getConn().getCollection(MongoGraphs.COL_CSN_CLUSTERS).save(obj); } catch (Exception e) { return Utils .returnResponse(PrettyJSONPrinter.prettyPrint(jSON2Rrn.createJSONError("Update failed", e))); } return Utils .returnResponse(PrettyJSONPrinter.prettyPrint(jSON2Rrn.createJSON(obj, "Updated Successfully"))); }
From source file:eu.cassandra.server.api.Installations.java
License:Apache License
/** * // w w w.j a v a 2s . c om * Gets the installations under a scenario id * @param message contains the scenario_id to search the related scenarios * @return */ @GET public Response getInstallations(@QueryParam("scn_id") String scn_id, @QueryParam("filter") String filters, @QueryParam("sort") String sort, @QueryParam("limit") int limit, @QueryParam("skip") int skip, @QueryParam("count") boolean count, @QueryParam("pertype") boolean pertype, @Context HttpHeaders httpHeaders) { String page = new MongoInstallations().getInstallations(httpHeaders, scn_id, filters, sort, limit, skip, count, pertype); String countResponse = (new MongoInstallations()).getInstallations(httpHeaders, scn_id, null, null, 0, 0, true, false); DBObject jsonResponse = (DBObject) JSON.parse(countResponse); BasicDBList list = (BasicDBList) jsonResponse.get("data"); DBObject object = (DBObject) list.get(0); return Utils.returnResponseWithAppend(page, "total_size", (Integer) object.get("count")); }
From source file:eu.cassandra.server.api.Replace.java
License:Apache License
@POST public Response replace(String message) { HttpHeaders httpHeaders = null;/*from ww w . j a v a2 s . c om*/ // parse what will be replaced JSONtoReturn jSON2Rrn = new JSONtoReturn(); DBObject jsonResponse = (DBObject) JSON.parse(message); BasicDBList replacedEntities = (BasicDBList) jsonResponse.get("replaced_ids"); String newEntity = (String) jsonResponse.get("replacement_id"); String scenario = (String) jsonResponse.get("scn_id"); String entityType = (String) jsonResponse.get("entity_type"); if (Utils.getUserWithId(scenario) != null) { return Utils.returnResponse(jSON2Rrn .createJSONError("Cannot replace entities that exist in libraries", "Invalid replacement") .toString()); } String answer = ""; MongoCopyEntities copy = new MongoCopyEntities(httpHeaders); for (Object o : replacedEntities) { String entity = (String) o; switch (entityType) { case "inst": // Get the replacement object String inst = new MongoInstallations().getInstallation(httpHeaders, newEntity); DBObject instObj = ((DBObject) ((BasicDBList) ((DBObject) JSON.parse(inst)).get("data")).get(0)); // Delete the replaced new MongoInstallations().deleteInstallation(entity); // Deep copy into scenario answer = copy.copyInstallationToScenario((String) instObj.get("_id"), scenario, null, true); break; case "pers": // Get the replacement object String pers = new MongoPersons().getPerson(httpHeaders, newEntity); DBObject persObj = ((DBObject) ((BasicDBList) ((DBObject) JSON.parse(pers)).get("data")).get(0)); // Deep copy into installation // But first get the inst_id of the old person String replacedPers = new MongoPersons().getPerson(httpHeaders, entity); DBObject replacedPersObj = ((DBObject) ((BasicDBList) ((DBObject) JSON.parse(replacedPers)) .get("data")).get(0)); String inst_id = (String) replacedPersObj.get("inst_id"); // Delete the replaced new MongoPersons().deletePerson(entity); answer = copy.copyPersonToInstallation((String) persObj.get("_id"), inst_id, null, false, null); break; case "app": // Get the replacement object String app = new MongoAppliances().getAppliance(httpHeaders, newEntity); DBObject appObj = ((DBObject) ((BasicDBList) ((DBObject) JSON.parse(app)).get("data")).get(0)); // Deep copy into installation // But first get the inst_id of the old person String replacedApp = new MongoAppliances().getAppliance(httpHeaders, entity); DBObject replacedAppObj = ((DBObject) ((BasicDBList) ((DBObject) JSON.parse(replacedApp)) .get("data")).get(0)); inst_id = (String) replacedAppObj.get("inst_id"); // Deep copy into scenario answer = copy.copyApplianceToInstallation((String) appObj.get("_id"), inst_id, null); String idToPush = (String) ((DBObject) ((DBObject) JSON.parse(answer)).get("data")).get("_id"); // Find in which activities the replaced id exists DBObject qry = new BasicDBObject(); DBObject obj = new BasicDBObject("$push", new BasicDBObject(MongoActivityModels.REF_CONTAINSAPPLIANCES, idToPush)); int added = DBConn.getConn().getCollection(MongoActivityModels.COL_ACTMODELS) .update(qry, obj, false, true).getN(); // Delete the replaced it will make a cascade delete as well... new MongoAppliances().deleteAppliance(entity); break; default: return Utils.returnResponse( jSON2Rrn.createJSONError("Entity type is not a match", "Bad Request").toString()); } } // for each replacement // Get the replacement, get the reference // // // 0 add the replacement in its collection and get the id // // 1. Search installations in the scenario and replace them // // 2. Search persons in installations collection and replace them // // 3. Search appliances in installations collection and replace them // // 4. Search appliances in act_models and replace them DBObject ret = (DBObject) JSON.parse(answer); return Utils.returnResponse(PrettyJSONPrinter.prettyPrint(jSON2Rrn.createJSON(ret, "Replace succesful!"))); }
From source file:eu.cassandra.server.api.Runs.java
License:Apache License
/** * Create a run.//from ww w. j a va 2 s.c o m * In order to create and start a run, we need to have the simulation * parameter id passed as a JSON property via the POST request. After that * the procedure goes as follows: * <ol> * <i>Create a database to hold the run documents and results (dbname same as run_id)</i> * <i>Parse the smp_id from the JSON request</i> * <i>From smp_id get scn_id</i> * <i>From scn_id gather all scenario documents and create a full JSON scenario</i> * <i>If the scenario is dynamic, instantiate as documents all the virtual installations</i> * <i>Store the full scenario in a new MongoDB database</i> * <i>Create thread with JSON scenario</i> * <i>Run the thread</i> * <i>Store the run document</i> * </ol> */ @POST public Response createRun(String message) { DBObject query = new BasicDBObject(); // A query try { // Create the new database ObjectId objid = ObjectId.get(); String dbname = objid.toString(); DB db = createDB(dbname); // Create the scenario document DBObject scenario = new BasicDBObject(); // Simulation parameters DBObject jsonMessage = (DBObject) JSON.parse(message); String smp_id = (String) jsonMessage.get("smp_id"); checkForNull(smp_id, "Simulation Parameters id not posted."); query.put("_id", new ObjectId(smp_id)); DBObject simParams = DBConn.getConn().getCollection(MongoSimParam.COL_SIMPARAM).findOne(query); checkForNull(simParams, "The provided Simulation Parameters were not found in the DB."); db.getCollection(MongoSimParam.COL_SIMPARAM).insert(simParams); scenario.put("sim_params", simParams); // Scenario String scn_id = (String) simParams.get("scn_id"); checkForNull(scn_id, "Scenario id not found in posted Simulation Parameters."); query.put("_id", new ObjectId(scn_id)); DBObject scn = DBConn.getConn().getCollection(MongoScenarios.COL_SCENARIOS).findOne(query); checkForNull(scn, "The provided Scenario was not found in the DB."); db.getCollection(MongoScenarios.COL_SCENARIOS).insert(scn); scenario.put("scenario", scn); // Pricing Policy String prc_id = (String) simParams.get("prc_id"); if (prc_id != null && prc_id.matches("[a-z0-9]{24}")) { // Optionally provided query.put("_id", new ObjectId(prc_id)); DBObject pricingPolicy = DBConn.getConn().getCollection(MongoPricingPolicy.COL_PRICING) .findOne(query); checkForNull(pricingPolicy, "The provided Pricing Policy was not found in the DB."); db.getCollection(MongoPricingPolicy.COL_PRICING).insert(pricingPolicy); scenario.put("pricing", pricingPolicy); } // Pricing Policy String base_prc_id = (String) simParams.get("base_prc_id"); if (base_prc_id != null && base_prc_id.matches("[a-z0-9]{24}")) { // Optionally provided query.put("_id", new ObjectId(base_prc_id)); DBObject basePricingPolicy = DBConn.getConn().getCollection(MongoPricingPolicy.COL_PRICING) .findOne(query); checkForNull(basePricingPolicy, "The provided Baseline Pricing Policy was not found in the DB."); db.getCollection(MongoPricingPolicy.COL_PRICING).insert(basePricingPolicy); scenario.put("baseline_pricing", basePricingPolicy); } // Project String prj_id = (String) scn.get("project_id"); checkForNull(prj_id, "Project id not found in posted Scenario."); query.put("_id", new ObjectId(prj_id)); DBObject project = DBConn.getConn().getCollection(MongoProjects.COL_PROJECTS).findOne(query); checkForNull(project, "The provided Project was not found in the DB."); db.getCollection(MongoProjects.COL_PROJECTS).insert(project); scenario.put("project", project); // Demographics query = new BasicDBObject(); query.put("scn_id", scn_id); String setup = (String) scn.get("setup"); checkForNull(setup, "Setup property not set."); String name = (String) scn.get("name"); boolean isDynamic = setup.equalsIgnoreCase("dynamic"); if (isDynamic) { DBObject demog = DBConn.getConn().getCollection(MongoDemographics.COL_DEMOGRAPHICS).findOne(query); checkForNull(demog, "The provided Demographics were not found in the DB."); db.getCollection(MongoDemographics.COL_DEMOGRAPHICS).insert(demog); scenario.put("demog", demog); } // Installations query = new BasicDBObject(); query.put("scenario_id", scn_id); DBCursor cursor = DBConn.getConn().getCollection(MongoInstallations.COL_INSTALLATIONS).find(query); checkForZero(cursor.size(), "No istallations found"); int countInst = 0; while (cursor.hasNext()) { countInst++; DBObject obj = cursor.next(); if (!isDynamic) db.getCollection(MongoInstallations.COL_INSTALLATIONS).insert(obj); String inst_id = obj.get("_id").toString(); // Thermal module query = new BasicDBObject(); query.put("inst_id", inst_id); DBObject thermal = DBConn.getConn().getCollection(MongoThermal.COL_THERMAL).findOne(query); if (thermal != null) { db.getCollection(MongoThermal.COL_THERMAL).insert(thermal); obj.put("thermal", thermal); } // Persons query = new BasicDBObject(); query.put("inst_id", inst_id); DBCursor persons = DBConn.getConn().getCollection(MongoPersons.COL_PERSONS).find(query); int personCount = 0; while (persons.hasNext()) { personCount++; DBObject person = persons.next(); if (!isDynamic) db.getCollection(MongoPersons.COL_PERSONS).insert(person); // Activities String pers_id = person.get("_id").toString(); query = new BasicDBObject(); query.put("pers_id", pers_id); DBCursor activities = DBConn.getConn().getCollection(MongoActivities.COL_ACTIVITIES) .find(query); int countAct = 0; while (activities.hasNext()) { countAct++; DBObject activity = activities.next(); if (!isDynamic) db.getCollection(MongoActivities.COL_ACTIVITIES).insert(activity); // Activity Models String act_id = activity.get("_id").toString(); query = new BasicDBObject(); query.put("act_id", act_id); DBCursor activityModels = DBConn.getConn().getCollection(MongoActivityModels.COL_ACTMODELS) .find(query); int countActMod = 0; while (activityModels.hasNext()) { countActMod++; DBObject activityModel = activityModels.next(); if (!isDynamic) db.getCollection(MongoActivityModels.COL_ACTMODELS).insert(activityModel); // Duration distribution String dur_id = activityModel.get("duration").toString(); checkForNull(dur_id, "Activity Model with name '" + activityModel.get("name") + "' does not have a duration distribution."); query = new BasicDBObject(); query.put("_id", new ObjectId(dur_id)); DBObject durDist = DBConn.getConn().getCollection(MongoDistributions.COL_DISTRIBUTIONS) .findOne(query); checkForNull(durDist, "Duration distribution of '" + activityModel.get("name") + "' not found in the DB."); if (!isDynamic) db.getCollection(MongoDistributions.COL_DISTRIBUTIONS).insert(durDist); activityModel.put("duration", durDist); // Start time distribution String start_id = activityModel.get("startTime").toString(); checkForNull(start_id, "Activity Model with name '" + activityModel.get("name") + "' does not have a start time distribution."); query = new BasicDBObject(); query.put("_id", new ObjectId(start_id)); DBObject startDist = DBConn.getConn() .getCollection(MongoDistributions.COL_DISTRIBUTIONS).findOne(query); checkForNull(startDist, "Start distribution of '" + activityModel.get("name") + "' not found in the DB."); if (!isDynamic) db.getCollection(MongoDistributions.COL_DISTRIBUTIONS).insert(startDist); activityModel.put("start", startDist); // Repetitions distribution String rep_id = activityModel.get("repeatsNrOfTime").toString(); checkForNull(rep_id, "Activity Model with name '" + activityModel.get("name") + "' does not have a number of times distribution."); query = new BasicDBObject(); query.put("_id", new ObjectId(rep_id)); DBObject repDist = DBConn.getConn().getCollection(MongoDistributions.COL_DISTRIBUTIONS) .findOne(query); checkForNull(repDist, "Number of times distribution of '" + activityModel.get("name") + "' not found in the DB."); if (!isDynamic) db.getCollection(MongoDistributions.COL_DISTRIBUTIONS).insert(repDist); activityModel.put("repetitions", repDist); activity.put("actmod" + countActMod, activityModel); } activity.put("actmodcount", new Integer(countActMod)); person.put("activity" + countAct, activity); } person.put("activitycount", new Integer(countAct)); obj.put("person" + personCount, person); } obj.put("personcount", new Integer(personCount)); // Appliances query = new BasicDBObject(); query.put("inst_id", inst_id); DBCursor appliances = DBConn.getConn().getCollection(MongoAppliances.COL_APPLIANCES).find(query); int countApps = 0; while (appliances.hasNext()) { countApps++; DBObject appliance = appliances.next(); if (!isDynamic) db.getCollection(MongoAppliances.COL_APPLIANCES).insert(appliance); // Consumption model String app_id = appliance.get("_id").toString(); query = new BasicDBObject(); query.put("app_id", app_id); DBObject consModel = DBConn.getConn().getCollection(MongoConsumptionModels.COL_CONSMODELS) .findOne(query); checkForNull(consModel, "Consumption model of appliance '" + appliance.get("name") + "' not found in the DB."); if (!isDynamic) db.getCollection(MongoConsumptionModels.COL_CONSMODELS).insert(consModel); appliance.put("consmod", consModel); obj.put("app" + countApps, appliance); } obj.put("appcount", new Integer(countApps)); scenario.put("inst" + countInst, obj); } scenario.put("instcount", new Integer(countInst)); Simulation sim = new Simulation(scenario.toString(), dbname); sim.setup(false); // Scenario building finished DBObject run = buildRunObj(objid, name, prj_id, "sim"); DBConn.getConn().getCollection(MongoRuns.COL_RUNS).insert(run); String returnMsg = PrettyJSONPrinter.prettyPrint(jSON2Rrn.createJSON(run, "Sim creation successful")); logger.info(returnMsg); ThreadPoolExecutor executorPool = (ThreadPoolExecutor) context.getAttribute("MY_EXECUTOR"); Utils.printExecutorSummary(executorPool); executorPool.execute(sim); return Utils.returnResponse(returnMsg); } catch (UnknownHostException | MongoException e1) { String returnMsg = "{ \"success\": false, \"message\": \"Sim creation failed\", \"errors\": { \"hostMongoException\": \"" + e1.getMessage() + "\" } }"; e1.printStackTrace(); return Utils.returnResponse(returnMsg); } catch (Exception e) { String returnMsg = "{ \"success\": false, \"message\": \"Sim creation failed\", \"errors\": { \"generalException\": \"" + e.getMessage() + "\" } }"; e.printStackTrace(); logger.error(Utils.stackTraceToString(e.getStackTrace())); return Utils.returnResponse(returnMsg); } }