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:eu.vital.vitalcep.restApp.filteringApi.ContinuosFiltering.java
private DBObject createCEPFilterSensor(String filter, String randomUUIDString, JSONObject dsjo, String cepInstance) throws JSONException { DBObject dbObject = (DBObject) JSON.parse(filter); dbObject.put("@context", "http://vital-iot.eu/contexts/sensor.jsonld"); dbObject.put("id", host + "/sensor/" + randomUUIDString); dbObject.put("type", "vital:CEPFilterSensor"); dbObject.put("status", "vital:Running"); JSONArray observes = new JSONArray(); JSONArray compl = dsjo.getJSONArray("complex"); for (int i = 0; i < compl.length(); i++) { JSONObject oComplex = new JSONObject(compl.get(i).toString()); JSONObject oObserves = new JSONObject(); oObserves.put("type", "vital:ComplexEvent"); //oObserves.put("uri", host+"/sensor/"+randomUUIDString // +"/"+oComplex.getString("id").toString()); oObserves.put("id", host + "/sensor/" + randomUUIDString + "/" + oComplex.getString("id")); observes.put(oObserves);// ww w . ja v a2 s . c o m } DBObject dbObject2 = (DBObject) JSON.parse(observes.toString()); dbObject.put("ssn:observes", dbObject2); dbObject.put("cepinstance", cepInstance); return dbObject; }
From source file:eu.vital.vitalcep.restApp.filteringApi.StaticFiltering.java
/** * Creates a filter.//ww w . j a va 2 s. co m * * @param info * @return the filter id * @throws java.io.IOException */ @POST @Path("filterstaticdata") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public Response filterstaticdata(String info, @Context HttpServletRequest req) throws IOException, UnsupportedEncodingException, NoSuchAlgorithmException { JSONObject jo = new JSONObject(info); if (jo.has("dolceSpecification") && jo.has("data")) { // && jo.has("data") for demo MongoClient mongo = new MongoClient(new MongoClientURI(mongoURL)); MongoDatabase db = mongo.getDatabase(mongoDB); try { db.getCollection("staticdatafilters"); } catch (Exception e) { //System.out.println("Mongo is down"); db = null; if (mongo != null) { mongo.close(); mongo = null; } return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); } if (jo.has("dolceSpecification")) { //Filter oFilter = new Filter(filter); JSONObject dsjo = jo.getJSONObject("dolceSpecification"); String str = dsjo.toString();//"{\"dolceSpecification\": "+ dsjo.toString()+"}"; try { DolceSpecification ds = new DolceSpecification(str); if (!(ds instanceof DolceSpecification)) { return Response.status(Response.Status.BAD_REQUEST).build(); } String mqin = RandomStringUtils.randomAlphanumeric(8); String mqout = RandomStringUtils.randomAlphanumeric(8); JSONArray aData = jo.getJSONArray("data"); CEP cepProcess = new CEP(); if (!(cepProcess.CEPStart(CEP.CEPType.DATA, ds, mqin, mqout, confFile, aData.toString(), null))) { return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); } String clientName = "collector_" + RandomStringUtils.randomAlphanumeric(4); if (cepProcess.PID < 1) { return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); } UUID uuid = UUID.randomUUID(); String randomUUIDString = uuid.toString(); DBObject dbObject = createCEPFilterStaticSensorJsonld(info, randomUUIDString, jo, dsjo, "vital:CEPFilterStaticDataSensor"); Document doc = new Document(dbObject.toMap()); try { db.getCollection("staticdatafilters").insertOne(doc); String id = doc.get("_id").toString(); } catch (MongoException ex) { db = null; if (mongo != null) { mongo.close(); mongo = null; } return Response.status(Response.Status.BAD_REQUEST).build(); } JSONObject opState = createOperationalStateObservation(randomUUIDString); DBObject oPut = (DBObject) JSON.parse(opState.toString()); Document doc1 = new Document(oPut.toMap()); try { db.getCollection("staticdatafiltersobservations").insertOne(doc1); String id = doc1.get("_id").toString(); } catch (MongoException ex) { db = null; if (mongo != null) { mongo.close(); mongo = null; } return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); } ///////////////////////////////////////////////////// // creates client and messages process // MqttAllInOne oMqtt = new MqttAllInOne(); TMessageProc MsgProcc = new TMessageProc(); ///////////////////////////////////////////////////////////////////////// // PREPARING DOLCE INPUT Decoder decoder = new Decoder(); ArrayList<String> simpleEventAL = decoder.JsonldArray2DolceInput(aData); String sal = simpleEventAL.toString(); ///////////////////////////////////////////////////////////////////////////// // SENDING TO MOSQUITTO oMqtt.sendMsg(MsgProcc, clientName, simpleEventAL, mqin, mqout, false); ///////////////////////////////////////////////////////////////////////////// //RECEIVING FROM MOSQUITO ArrayList<MqttMsg> mesagges = MsgProcc.getMsgs(); ArrayList<Document> outputL; outputL = new ArrayList<>(); Encoder encoder = new Encoder(); outputL = encoder.dolceOutputList2ListDBObject(mesagges, host, randomUUIDString); String sOutput = "["; for (int i = 0; i < outputL.size(); i++) { Document element = outputL.get(i); if (i == 0) { sOutput = sOutput + element.toJson(); } sOutput = sOutput + "," + element.toJson(); } sOutput = sOutput + "]"; StringBuilder ck = new StringBuilder(); try { Security slogin = new Security(); Boolean token = slogin.login(req.getHeader("name"), req.getHeader("password"), false, ck); if (!token) { return Response.status(Response.Status.UNAUTHORIZED).build(); } cookie = ck.toString(); DMSManager oDMS = new DMSManager(dmsURL, cookie); MongoCollection<Document> collection = db.getCollection("staticdatafiltersobservations"); if (outputL.size() > 0) { collection.insertMany(outputL); if (!oDMS.pushObservations(sOutput)) { java.util.logging.Logger.getLogger(StaticFiltering.class.getName()) .log(Level.SEVERE, "couldn't save to the DMS"); } } } catch (KeyManagementException | KeyStoreException ex) { db = null; if (mongo != null) { mongo.close(); mongo = null; } java.util.logging.Logger.getLogger(MessageProcessor_publisher.class.getName()) .log(Level.SEVERE, null, ex); } //cepProcess. try { CepContainer.deleteCepProcess(cepProcess.PID); if (!cepProcess.cepDispose()) { java.util.logging.Logger.getLogger(StaticFiltering.class.getName()).log(Level.SEVERE, "couldn't terminate ucep"); } } catch (Exception e) { java.util.logging.Logger.getLogger(StaticFiltering.class.getName()).log(Level.SEVERE, null, e); } db = null; if (mongo != null) { mongo.close(); mongo = null; } return Response.status(Response.Status.OK).entity(sOutput).build(); } catch (IOException | JSONException | java.text.ParseException e) { db = null; if (mongo != null) { mongo.close(); mongo = null; } return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); } } return Response.status(Response.Status.BAD_REQUEST).build(); } return Response.status(Response.Status.BAD_REQUEST).build(); }
From source file:eu.vital.vitalcep.restApp.filteringApi.StaticFiltering.java
private DBObject createCEPFilterStaticSensorJsonld(String info, String randomUUIDString, JSONObject jo, JSONObject dsjo, String type) throws JSONException { DBObject dbObject = (DBObject) JSON.parse(info); dbObject.removeField("id"); dbObject.put("@context", "http://vital-iot.eu/contexts/sensor.jsonld"); dbObject.put("id", host + "/sensor/" + randomUUIDString); dbObject.put("name", jo.getString("name")); dbObject.put("type", "vital:" + type); //dbObject.put("type", "vital:CEPSensor"); dbObject.put("description", jo.getString("description")); //demo// ww w .j a v a 2 s . c o m // JSONArray data = jo.getJSONArray("data"); // dbObject.put("data",data.toString()); JSONArray compl = dsjo.getJSONArray("complex"); JSONArray observes = new JSONArray(); for (int i = 0; i < compl.length(); i++) { JSONObject oComplex = new JSONObject(compl.get(i).toString()); JSONObject oObserves = new JSONObject(); oObserves.put("type", "vital:ComplexEvent"); //oObserves.put("uri", host.toString() // +"/sensor/"+randomUUIDString // +"/"+oComplex.getString("id").toString()); oObserves.put("id", host + "/sensor/" + randomUUIDString + "/" + oComplex.getString("id").toString()); observes.put(oObserves); } DBObject dbObject2 = (DBObject) JSON.parse(observes.toString()); dbObject.put("ssn:observes", dbObject2); dbObject.put("status", "vital:running"); return dbObject; }
From source file:eu.vital.vitalcep.restApp.filteringApi.StaticFiltering.java
/** * Gets a filter./*from w w w .j a v a 2 s . c om*/ * * @param info * @param req * @return the filter * @throws java.io.IOException */ @POST @Path("filterstaticquery") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public Response filterstaticquery(String info, @Context HttpServletRequest req) throws IOException { JSONObject jo = new JSONObject(info); if (jo.has("dolceSpecification") && jo.has("query")) { // && jo.has("data") for demo StringBuilder ck = new StringBuilder(); Security slogin = new Security(); JSONObject credentials = new JSONObject(); Boolean token = slogin.login(req.getHeader("name"), req.getHeader("password"), false, ck); credentials.put("username", req.getHeader("name")); credentials.put("password", req.getHeader("password")); if (!token) { return Response.status(Response.Status.UNAUTHORIZED).build(); } this.cookie = ck.toString(); MongoClient mongo = new MongoClient(new MongoClientURI(mongoURL)); MongoDatabase db = mongo.getDatabase(mongoDB); try { db.getCollection("staticqueryfilters"); } catch (Exception e) { //System.out.println("Mongo is down"); db = null; if (mongo != null) { mongo.close(); mongo = null; } return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); } if (jo.has("dolceSpecification")) { //Filter oFilter = new Filter(filter); JSONObject dsjo = jo.getJSONObject("dolceSpecification"); String str = dsjo.toString();//"{\"dolceSpecification\": "+ dsjo.toString()+"}"; try { DolceSpecification ds = new DolceSpecification(str); if (!(ds instanceof DolceSpecification)) { return Response.status(Response.Status.BAD_REQUEST).build(); } String mqin = RandomStringUtils.randomAlphanumeric(8); String mqout = RandomStringUtils.randomAlphanumeric(8); CEP cepProcess = new CEP(); if (!(cepProcess.CEPStart(CEP.CEPType.QUERY, ds, mqin, mqout, confFile, jo.getString("query"), null))) { return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); } String clientName = "collector_" + RandomStringUtils.randomAlphanumeric(4); if (cepProcess.PID < 1) { return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); } UUID uuid = UUID.randomUUID(); String randomUUIDString = uuid.toString(); DBObject dbObject = createCEPFilterStaticSensorJsonld(info, randomUUIDString, jo, dsjo, "vital:CEPFilterStaticQuerySensor"); Document doc = new Document(dbObject.toMap()); try { db.getCollection("staticqueryfilters").insertOne(doc); String id = doc.get("_id").toString(); } catch (MongoException ex) { db = null; if (mongo != null) { mongo.close(); mongo = null; } return Response.status(Response.Status.BAD_REQUEST).build(); } JSONObject opState = createOperationalStateObservation(randomUUIDString); DBObject oPut = (DBObject) JSON.parse(opState.toString()); Document doc1 = new Document(oPut.toMap()); try { db.getCollection("staticqueryfiltersobservations").insertOne(doc1); String id = doc1.get("_id").toString(); } catch (MongoException ex) { db = null; if (mongo != null) { mongo.close(); mongo = null; } return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); } ///////////////////////////////////////////////////// // creates client and messages process // MqttAllInOne oMqtt = new MqttAllInOne(); TMessageProc MsgProcc = new TMessageProc(); JSONArray aData = new JSONArray(); try { DMSManager oDMS = new DMSManager(dmsURL, cookie); aData = oDMS.getObservations(jo.getString("query")); if (aData.length() < 1) { CepContainer.deleteCepProcess(cepProcess.PID); if (!cepProcess.cepDispose()) { java.util.logging.Logger.getLogger(StaticFiltering.class.getName()) .log(Level.SEVERE, "bcep Instance not terminated"); } ; db = null; if (mongo != null) { mongo.close(); mongo = null; } return Response.status(Response.Status.BAD_REQUEST).entity("no data to be filtered") .build(); } } catch (KeyManagementException | KeyStoreException ex) { java.util.logging.Logger.getLogger(StaticFiltering.class.getName()).log(Level.SEVERE, null, ex); } //DMSManager oDMS = new DMSManager(dmsURL,req.getHeader("vitalAccessToken")); ///////////////////////////////////////////////////////////////////////// // PREPARING DOLCE INPUT Decoder decoder = new Decoder(); ArrayList<String> simpleEventAL = decoder.JsonldArray2DolceInput(aData); ///////////////////////////////////////////////////////////////////////////// // SENDING TO MOSQUITTO oMqtt.sendMsg(MsgProcc, clientName, simpleEventAL, mqin, mqout, false); ///////////////////////////////////////////////////////////////////////////// //RECEIVING FROM MOSQUITO ArrayList<MqttMsg> mesagges = MsgProcc.getMsgs(); //FORMATTING OBSERVATIONS OUTPUT Encoder encoder = new Encoder(); ArrayList<Document> outputL; outputL = new ArrayList<>(); outputL = encoder.dolceOutputList2ListDBObject(mesagges, host, randomUUIDString); String sOutput = "["; for (int i = 0; i < outputL.size(); i++) { Document element = outputL.get(i); if (i == 0) { sOutput = sOutput + element.toJson(); } sOutput = sOutput + "," + element.toJson(); } sOutput = sOutput + "]"; try { DMSManager pDMS = new DMSManager(dmsURL, cookie); MongoCollection<Document> collection = db.getCollection("staticqueryfiltersobservations"); if (outputL.size() > 0) { collection.insertMany(outputL); if (!pDMS.pushObservations(sOutput)) { java.util.logging.Logger.getLogger(StaticFiltering.class.getName()) .log(Level.SEVERE, "coudn't save to the DMS"); } } } catch (IOException | KeyManagementException | NoSuchAlgorithmException | KeyStoreException ex) { db = null; if (mongo != null) { mongo.close(); mongo = null; } java.util.logging.Logger.getLogger(StaticFiltering.class.getName()).log(Level.SEVERE, null, ex); } CepContainer.deleteCepProcess(cepProcess.PID); if (!cepProcess.cepDispose()) { java.util.logging.Logger.getLogger(StaticFiltering.class.getName()).log(Level.SEVERE, "bcep Instance not terminated"); } ; db = null; if (mongo != null) { mongo.close(); mongo = null; } return Response.status(Response.Status.OK).entity(sOutput).build(); } catch (IOException | JSONException | NoSuchAlgorithmException | java.text.ParseException e) { db = null; if (mongo != null) { mongo.close(); mongo = null; } return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); } } return Response.status(Response.Status.BAD_REQUEST).build(); } return Response.status(Response.Status.BAD_REQUEST).build(); }
From source file:eu.vital.vitalcep.restApp.vuaippi.Observation.java
/** * Gets sensors metadata ./*from www .ja v a 2 s .c o m*/ * * @return the metadata of the sensors * @throws java.io.FileNotFoundException */ @POST @Path("stream/subscribe") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public Response subscribeToObservations(String info, @Context HttpServletRequest req) throws FileNotFoundException, IOException { StringBuilder ck = new StringBuilder(); Security slogin = new Security(); Boolean token = slogin.login(req.getHeader("name"), req.getHeader("password"), false, ck); if (!token) { return Response.status(Response.Status.UNAUTHORIZED).build(); } MongoClient mongo = new MongoClient(new MongoClientURI(mongoURL)); MongoDatabase db = mongo.getDatabase(mongoDB); DBObject dbObject = (DBObject) JSON.parse(info); if (!dbObject.containsField("sensor")) { return Response.status(Response.Status.BAD_REQUEST).build(); } if (!dbObject.containsField("property")) { return Response.status(Response.Status.BAD_REQUEST).build(); } if (!dbObject.containsField("url")) { return Response.status(Response.Status.BAD_REQUEST).build(); } Document doc = new Document(dbObject.toMap()); try { db.getCollection("subscriptions").insertOne(doc); String id = doc.get("_id").toString(); return Response.status(Response.Status.OK).entity("{\"subscription\":\"" + id + "\"}").build(); } catch (MongoException ex) { return Response.status(Response.Status.BAD_REQUEST).build(); } finally { db = null; if (mongo != null) { mongo.close(); mongo = null; } } }
From source file:eu.vital.vitalcep.restApp.vuaippi.Sensor.java
/** * Gets sensors metadata .//from ww w. j av a2 s. c o m * * @param req * @return the metadata of the sensors * @throws java.io.FileNotFoundException */ @POST @Path("observation") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public Response getSensorsObservations(String info, @Context HttpServletRequest req) throws FileNotFoundException, IOException { // // StringBuilder ck = new StringBuilder(); // Security slogin = new Security(); // // Boolean token = slogin.login(req.getHeader("name") // ,req.getHeader("password"),false,ck); // if (!token){ // return Response.status(Response.Status.UNAUTHORIZED).build(); // } DBObject request = (DBObject) JSON.parse(info); BasicDBList sensors; String property; if (!request.containsField("sensor") || !request.containsField("property")) { return Response.status(Response.Status.BAD_REQUEST).build(); } else { try { sensors = (BasicDBList) request.get("sensor"); property = (String) request.get("property"); } catch (Exception e) { return Response.status(Response.Status.BAD_REQUEST).build(); } } String sfrom = null; String sto = null; if (request.containsField("from") && request.containsField("to")) { if (!isDateValid((String) request.get("from")) || !isDateValid((String) request.get("to"))) { return Response.status(Response.Status.BAD_REQUEST).entity("wrong xsd:dateTime format").build(); } try { sfrom = getXSDDateTimeSecure((String) request.get("from")); sto = getXSDDateTimeSecure((String) request.get("to")); } catch (ParseException e) { return Response.status(Response.Status.BAD_REQUEST).entity("wrong xsd:dateTime format").build(); } } else if (request.containsField("from")) { if (!isDateValid((String) request.get("from"))) { return Response.status(Response.Status.BAD_REQUEST).build(); } try { sfrom = getXSDDateTimeSecure((String) request.get("from")); } catch (ParseException e) { return Response.status(Response.Status.BAD_REQUEST).entity("wrong xsd:dateTime format").build(); } } JSONArray observations = new JSONArray(); if (request.containsField("from") && request.containsField("to")) { observations = getObservations(sensors, property, sfrom, sto); } else if (request.containsField("from")) { //now Date NOW = new Date(); observations = getObservations(sensors, property, sfrom, getXSDDateTime(NOW)); } else { observations = getObservations(sensors, property, null, null); } return Response.status(Response.Status.OK).entity(observations.toString()).build(); }
From source file:ezbake.data.mongo.conversion.MongoConverter.java
License:Apache License
/** * Convert a string JS/JSON object to a Mongo DBObject. * // w ww. ja v a2s .co m * @param object A JSON/JavaScript object. * @param isJson Boolean flag to indicate whether the <code>object</code> passed is known to be valid JSON. If a * client is unsure, or is passing a JavaScript object, we will deserialize the <code>object</code> into a * JavaScript object first and then serializse the constructed JavaScript object to JSON before attempting * the conversion to a Mongo DBObject. * @return A Mongo DBObject instance ("A key-value map that can be saved to the database") * @throws JSONException If decoding/encoding the JSON fails. */ public final static DBObject toDBObject(final String object, boolean isJson) throws JSONException { String jsonString; if (isJson) { logger.debug("Assuming the String object provided is properly " + "encoded and can be parsed via Mongo's JSON.parse(...) method"); jsonString = object; } else { logger.debug("Assuming the String object provided is a JS object " + "and will not parse via Mongo's JSON.parse(...) method"); // Convert a javascript object literal to a Java object // NOTE: This Type and Constructor are non obvious, but the // constructor is parsing a JavaScript object literal, NOT // a JSON string. final JSONObject objectFromString = new JSONObject(object); // Here we convert the java object to a valid JSON String jsonString = objectFromString.toString(); logger.debug("Updated JSON String for parsing."); } // Parse the JSON string into a Mongo DBObject final DBObject dbObject = (DBObject) JSON.parse(jsonString); return dbObject; }
From source file:ezbake.data.mongo.EzMongoHandler.java
License:Apache License
@Override public void ensureIndex(String collectionName, String jsonKeys, String jsonOptions, EzSecurityToken security) throws TException, EzMongoBaseException { try {// ww w .j a va 2 s. c om HashMap<String, String> auditParamsMap = new HashMap<>(); auditParamsMap.put("action", "ensureIndex"); auditParamsMap.put("collectionName", collectionName); auditParamsMap.put("jsonKeys", jsonKeys); auditParamsMap.put("jsonOptions", jsonOptions); auditLog(security, AuditEventType.FileObjectCreate, auditParamsMap); TokenUtils.validateSecurityToken(security, this.getConfigurationProperties()); if (StringUtils.isEmpty(collectionName)) { throw new EzMongoBaseException("collectionName is required."); } final String finalCollectionName = getCollectionName(collectionName); final DBObject indexKeys = (DBObject) JSON.parse(jsonKeys); if (!StringUtils.isEmpty(jsonOptions)) { final DBObject indexOptions = (DBObject) JSON.parse(jsonOptions); db.getCollection(finalCollectionName).ensureIndex(indexKeys, indexOptions); } else { db.getCollection(finalCollectionName).ensureIndex(indexKeys); } appLog.info("ensured index with keys: {}, options: {}", jsonKeys, jsonOptions); } catch (final Exception e) { throw enrichException("ensureIndex", e); } }
From source file:ezbake.data.mongo.EzMongoHandler.java
License:Apache License
/** * Create MongoDB indexes for the given fields in some collection. * * @param collectionName The Name of the collection the document belongs to * @param jsonKeys The Mongo index keys/*w w w .j a va 2 s . c om*/ * @param jsonOptions Optional options for the particular fields being indexed. * @param security A valid EzSecurity token * @throws TException If authentication fails * @throws EzMongoBaseException If some other error occurs */ @Override public void createIndex(String collectionName, String jsonKeys, String jsonOptions, EzSecurityToken security) throws TException, EzMongoBaseException { try { HashMap<String, String> auditParamsMap = new HashMap<>(); auditParamsMap.put("action", "createIndex"); auditParamsMap.put("collectionName", collectionName); auditParamsMap.put("jsonKeys", jsonKeys); auditParamsMap.put("jsonOptions", jsonOptions); auditLog(security, AuditEventType.FileObjectCreate, auditParamsMap); TokenUtils.validateSecurityToken(security, this.getConfigurationProperties()); if (StringUtils.isEmpty(collectionName)) { throw new EzMongoBaseException("collectionName is required."); } final String finalCollectionName = getCollectionName(collectionName); final DBObject indexKeys = (DBObject) JSON.parse(jsonKeys); // The 'options' object is optional if (StringUtils.isEmpty(jsonOptions)) { db.getCollection(finalCollectionName).createIndex(indexKeys); } else { final DBObject indexOptions = (DBObject) JSON.parse(jsonOptions); // check if "ns" and "name" fields are not in the jsonOptions - then need to put them in. // otherwise, mongodb throws this error: // "Cannot authorize inserting into system.indexes documents without a string-typed \"ns\" field." String ns = (String) indexOptions.get("ns"); if (ns == null) { ns = dbName + "." + finalCollectionName; indexOptions.put("ns", ns); appLog.info("putting index's ns as : {}", ns); } String name = (String) indexOptions.get("name"); if (name == null) { name = ""; final Set<String> keySet = indexKeys.keySet(); for (final String key : keySet) { final Object keyValue = indexKeys.get(key); if (name.length() > 0) { name += "_"; } name += key + "_" + keyValue.toString(); } indexOptions.put("name", name); appLog.info("putting index's name as : {}", name); } db.getCollection(finalCollectionName).createIndex(indexKeys, indexOptions); } appLog.info("created index with keys: {}, options: {}", jsonKeys, jsonOptions); } catch (final Exception e) { throw enrichException("createIndex", e); } }
From source file:ezbake.data.mongo.EzMongoHandler.java
License:Apache License
@Override public long getCountFromQuery(String collectionName, String jsonQuery, EzSecurityToken security) throws TException, EzMongoBaseException { try {/* w w w .j av a2 s . co m*/ HashMap<String, String> auditParamsMap = new HashMap<>(); auditParamsMap.put("action", "getCountFromQuery"); auditParamsMap.put("collectionName", collectionName); auditParamsMap.put("jsonQuery", jsonQuery); auditLog(security, AuditEventType.FileObjectAccess, auditParamsMap); TokenUtils.validateSecurityToken(security, this.getConfigurationProperties()); if (StringUtils.isEmpty(collectionName)) { throw new EzMongoBaseException("collectionName is required."); } final DBObject queryCommand = (DBObject) JSON.parse(jsonQuery); final DBObject query = new BasicDBObject("$match", queryCommand); final String finalCollectionName = getCollectionName(collectionName); appLog.info("getCountFromQuery, finalCollectionName: {}, {}", finalCollectionName, jsonQuery); final DBObject[] aggregationCommandsArray = mongoFindHelper .getFindAggregationCommandsArray_withcounter(0, 0, null, null, security, true, READ_OPERATION); final AggregationOutput aggregationOutput = db.getCollection(finalCollectionName).aggregate(query, aggregationCommandsArray); final BasicDBList resultsList = (BasicDBList) aggregationOutput.getCommandResult().get("result"); long count = 0; if (resultsList.size() > 0) { final BasicDBObject resultsObj = (BasicDBObject) resultsList.get(0); count = resultsObj.getLong("count"); } return count; } catch (final Exception e) { throw enrichException("getCountFromQuery", e); } }