List of usage examples for com.mongodb MongoClient getDatabase
public MongoDatabase getDatabase(final String databaseName)
From source file:eu.vital.vitalcep.restApp.filteringApi.ContinuosFiltering.java
/** * Gets a filter.//from w ww . j a v a 2 s . c om * * @param filterId * @param req * @return the filter */ @POST @Path("getcontinuousfilter") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public Response getcontinuousfilter(String filterId, @Context HttpServletRequest req) { 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(); } this.cookie = ck.toString(); JSONObject jo = new JSONObject(filterId); String idjo = jo.getString("id"); MongoClient mongo = new MongoClient(new MongoClientURI(mongoURL)); MongoDatabase db = mongo.getDatabase(mongoDB); try { db.getCollection("continuousfilters"); } 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(); } BasicDBObject searchById = new BasicDBObject("id", idjo); String found; BasicDBObject fields = new BasicDBObject().append("_id", false).append("cepinstance", false); FindIterable<Document> coll = db.getCollection("continuousfilters").find(searchById).projection(fields); try { found = coll.first().toJson(); db = null; if (mongo != null) { mongo.close(); mongo = null; } } catch (Exception e) { db = null; if (mongo != null) { mongo.close(); mongo = null; } return Response.status(Response.Status.NOT_FOUND).build(); } if (found == null) { return Response.status(Response.Status.NOT_FOUND).build(); } else { return Response.status(Response.Status.OK).entity(found).build(); } }
From source file:eu.vital.vitalcep.restApp.filteringApi.ContinuosFiltering.java
/** * Gets a filter.//from www . jav a2 s. c o m * * @param filterId * @param req * @return the filter */ @DELETE @Path("deletecontinuousfilter") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public Response deletecontinuousfilter(String filterId, @Context HttpServletRequest req) throws 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(); } this.cookie = ck.toString(); JSONObject jo = new JSONObject(filterId); String idjo = jo.getString("id"); MongoClient mongo = new MongoClient(new MongoClientURI(mongoURL)); MongoDatabase db = mongo.getDatabase(mongoDB); try { db.getCollection("continuousfilters"); } 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(); } MongoCollection<Document> coll = db.getCollection("continuousfilters"); Bson filter = Filters.eq("id", idjo); FindIterable<Document> iterable = coll.find(filter); String cepInstance; CEP cepProcess = new CEP(); if (iterable != null && iterable.first() != null) { Document doc = iterable.first(); cepInstance = doc.getString("cepinstance"); MongoCollection<Document> collInstances = db.getCollection("cepinstances"); ObjectId ci = new ObjectId(cepInstance); Bson filterInstances = Filters.eq("_id", ci); FindIterable<Document> iterable2 = collInstances.find(filterInstances); if (iterable2 != null) { Document doc2 = iterable2.first(); cepProcess.PID = doc2.getInteger("PID"); cepProcess.fileName = doc2.getString("fileName"); cepProcess.cepFolder = doc2.getString("cepFolder"); cepProcess.type = CEP.CEPType.CONTINUOUS.toString(); CepProcess cp = new CepProcess(null, null, null, null); cp.PID = doc2.getInteger("PID"); cepProcess.cp = cp; if (!cepProcess.cepDispose()) { java.util.logging.Logger.getLogger(ContinuosFiltering.class.getName()).log(Level.SEVERE, "bcep Instance not terminated"); } else { Bson filter1 = Filters.eq("_id", ci); Bson update = new Document("$set", new Document("status", "terminated")); UpdateOptions options = new UpdateOptions().upsert(false); UpdateResult updateDoc = db.getCollection("cepinstances").updateOne(filter1, update, options); } ; CepContainer.deleteCepProcess(cp.PID); } } DeleteResult deleteResult = coll.deleteOne(eq("id", idjo)); db = null; if (mongo != null) { mongo.close(); mongo = null; } if (deleteResult.getDeletedCount() < 1) { return Response.status(Response.Status.NOT_FOUND).build(); } else { return Response.status(Response.Status.OK).build(); } }
From source file:eu.vital.vitalcep.restApp.filteringApi.StaticFiltering.java
/** * Creates a filter.//from ww w.j av a 2 s.c om * * @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
/** * Gets the filters.//from w ww . j a va 2 s.c o m * * @return the filters */ @GET @Path("getstaticdatafilters") @Produces(MediaType.APPLICATION_JSON) public Response getStaticDataFilters(@Context HttpServletRequest req) { 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(); } this.cookie = ck.toString(); 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(); } // create an empty query BasicDBObject query = new BasicDBObject(); BasicDBObject fields = new BasicDBObject().append("_id", false); fields.append("dolceSpecification", false); FindIterable<Document> coll = db.getCollection("staticdatafilters").find(query).projection(fields); final JSONArray AllJson = new JSONArray(); coll.forEach(new Block<Document>() { @Override public void apply(final Document document) { String aux = document.toJson(); JSONObject sensoraux = new JSONObject(aux); AllJson.put(sensoraux); } }); db = null; if (mongo != null) { mongo.close(); mongo = null; } return Response.status(Response.Status.OK).entity(AllJson.toString()).build(); }
From source file:eu.vital.vitalcep.restApp.filteringApi.StaticFiltering.java
/** * Gets the filters.//from www.j a va 2s . c o m * * @return the filters */ @GET @Path("getstaticqueryfilters") @Produces(MediaType.APPLICATION_JSON) public Response getStaticQueryFilters(@Context HttpServletRequest req) { 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(); } 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(); } // create an empty query BasicDBObject query = new BasicDBObject(); BasicDBObject fields = new BasicDBObject().append("_id", false); fields.append("dolceSpecification", false); FindIterable<Document> coll = db.getCollection("staticqueryfilters").find(query).projection(fields); final JSONArray AllJson = new JSONArray(); coll.forEach(new Block<Document>() { @Override public void apply(final Document document) { String aux = document.toJson(); JSONObject sensoraux = new JSONObject(aux); AllJson.put(sensoraux); } }); db = null; if (mongo != null) { mongo.close(); mongo = null; } return Response.status(Response.Status.OK).entity(AllJson.toString()).build(); }
From source file:eu.vital.vitalcep.restApp.filteringApi.StaticFiltering.java
/** * Gets a filter.// w ww .j a v a 2 s . c om * * @param filterId * @param req * @return the filter */ @POST @Path("getstaticdatafilter") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public Response getstaticdatafilter(String filterId, @Context HttpServletRequest req) { 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(); } this.cookie = ck.toString(); JSONObject jo = new JSONObject(filterId); String idjo = jo.getString("id"); 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(); } BasicDBObject searchById = new BasicDBObject("id", idjo); String found; BasicDBObject fields = new BasicDBObject().append("_id", false).append("cepinstance", false); FindIterable<Document> coll = db.getCollection("staticdatafilters").find(searchById).projection(fields); try { found = coll.first().toJson(); db = null; if (mongo != null) { mongo.close(); mongo = null; } } catch (Exception e) { db = null; if (mongo != null) { mongo.close(); mongo = null; } return Response.status(Response.Status.NOT_FOUND).build(); } if (found == null) { return Response.status(Response.Status.NOT_FOUND).build(); } else { return Response.status(Response.Status.OK).entity(found).build(); } }
From source file:eu.vital.vitalcep.restApp.filteringApi.StaticFiltering.java
/** * Gets a filter.// w w w .j ava 2s . c om * * @param filterId * @param req * @return the filter */ @POST @Path("getstaticqueryfilter") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public Response getstaticqueryfilter(String filterId, @Context HttpServletRequest req) { 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(); } this.cookie = ck.toString(); JSONObject jo = new JSONObject(filterId); String idjo = jo.getString("id"); 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(); } BasicDBObject searchById = new BasicDBObject("id", idjo); String found; BasicDBObject fields = new BasicDBObject().append("_id", false).append("cepinstance", false); FindIterable<Document> coll = db.getCollection("staticqueryfilters").find(searchById).projection(fields); try { found = coll.first().toJson(); db = null; if (mongo != null) { mongo.close(); mongo = null; } } catch (Exception e) { return Response.status(Response.Status.NOT_FOUND).build(); } if (found == null) { return Response.status(Response.Status.NOT_FOUND).build(); } else { return Response.status(Response.Status.OK).entity(found).build(); } }
From source file:eu.vital.vitalcep.restApp.filteringApi.StaticFiltering.java
/** * Gets a filter.//from w w w .j ava2 s .c o m * * @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 ./* w w w .ja v a2 s . c om*/ * * @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.Observation.java
@POST @Path("stream/unsubscribe") @Consumes(MediaType.APPLICATION_JSON)//from ww w.ja va2 s.com @Produces(MediaType.APPLICATION_JSON) public Response unSubscribeToObservations(String info, @Context HttpServletRequest req) throws FileNotFoundException, IOException { JSONObject jObject = new JSONObject(); try { jObject = new JSONObject(info); if (!jObject.has("subscription")) { return Response.status(Response.Status.BAD_REQUEST).build(); } } catch (Exception e) { return Response.status(Response.Status.BAD_REQUEST).build(); } 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); Document doc = new Document("_id", new ObjectId(jObject.getString("subscription"))); DeleteResult deleted = db.getCollection("subscriptions").deleteOne(doc); db = null; if (mongo != null) { mongo.close(); mongo = null; } if (deleted.wasAcknowledged() != true || deleted.getDeletedCount() != 1) { return Response.status(Response.Status.NOT_FOUND).build(); } return Response.status(Response.Status.OK).build(); }