List of usage examples for com.mongodb MongoClientURI MongoClientURI
public MongoClientURI(final String uri)
From source file:eu.vital.vitalcep.collector.Collector.java
private Collector() throws IOException { ConfigReader configReader = ConfigReader.getInstance(); mongoURL = configReader.get(ConfigReader.MONGO_URL); mongoDB = configReader.get(ConfigReader.MONGO_DB); getCollectorList();// w ww. j a v a 2 s .c om ScheduledExecutorService exec = Executors.newScheduledThreadPool(2); Runnable collectoRunnable; collectoRunnable = new Runnable() { @Override public void run() { if (sensors.length() > 0) { mongo = new MongoClient(new MongoClientURI(mongoURL)); db = mongo.getDatabase(mongoDB); } Date NOW = new Date(); String nowString = getXSDDateTime(NOW); for (int i = 0; i < sensors.length(); i++) { try { String cookie = getListenerCredentials(i); JSONArray aData = new JSONArray(); String type = sensors.getJSONObject(i).getString("cepType"); if (type.equals("CONTINUOUS")) { try { DMSListener oDMS = new DMSListener(cookie); aData = oDMS.getObservations(sensors.getJSONObject(i).getJSONArray("sources"), sensors.getJSONObject(i).getJSONArray("properties"), sensors.getJSONObject(i).getString("lastRequest")); } catch (IOException | KeyManagementException | NoSuchAlgorithmException | KeyStoreException ex) { java.util.logging.Logger.getLogger(Collector.class.getName()).log(Level.SEVERE, null, ex); } if (aData.length() > 0) { sendData2CEP(aData, i); } } else { try { JSONObject sensor = new JSONObject(); sensor = sensors.getJSONObject(i); JSONArray requests = new JSONArray(); requests = sensor.getJSONArray("requests"); PPIListener oPPI = new PPIListener(cookie); aData = oPPI.getObservations(requests, sensor.getString("lastRequest")); if (aData.length() > 0) { sendData2CEP(aData, i); } } catch (IOException | KeyManagementException | NoSuchAlgorithmException | KeyStoreException ex) { java.util.logging.Logger.getLogger(Collector.class.getName()).log(Level.SEVERE, null, ex); } } sensors.getJSONObject(i).put("lastRequest", nowString); if (mongo == null) mongo = new MongoClient(new MongoClientURI(mongoURL)); if (db == null) db = mongo.getDatabase(mongoDB); Bson filter = Filters.eq("_id", new ObjectId(sensors.getJSONObject(i).getString("id"))); Bson update = new Document("$set", new Document("lastRequest", nowString)); UpdateOptions options = new UpdateOptions().upsert(false); UpdateResult updateDoc = db.getCollection("cepinstances").updateOne(filter, update, options); } catch (GeneralSecurityException | IOException | ParseException ex) { java.util.logging.Logger.getLogger(Collector.class.getName()).log(Level.SEVERE, null, ex); } finally { if (db != null) db = null; if (mongo != null) { mongo.close(); mongo = null; } } } if (db != null) db = null; if (mongo != null) { mongo.close(); mongo = null; } } private void sendData2CEP(JSONArray aData, int i) throws JSONException, ParseException { Decoder decoder = new Decoder(); ArrayList<String> simpleEventAL = decoder.JsonldArray2DolceInput(aData); MqttAllInOne oMqtt = new MqttAllInOne(); TMessageProc MsgProcc = new TMessageProc(); //TODO: check the client name. see from cep instances and what happen when if the topic exist String clientName = "collector_" + RandomStringUtils.randomAlphanumeric(4); oMqtt.sendMsg(MsgProcc, clientName, simpleEventAL, sensors.getJSONObject(i).getString("mqin"), sensors.getJSONObject(i).getString("mqout"), true); } private String getListenerCredentials(int i) throws IOException, GeneralSecurityException, JSONException { StringBuilder ck = new StringBuilder(); Security slogin = new Security(); JSONObject credentials = new JSONObject(); // Boolean token = slogin.login(sensors.getJSONArray(i) // .getJSONObject(0) // .getString("username") // ,decrypt(sensors.getJSONArray(i) // .getJSONObject(0) // .getString("password")),false,ck); Boolean token = slogin.login("elisa", "elisotas1", false, ck); if (!token) { //throw new } String cookie = ck.toString(); return cookie; } }; exec.scheduleAtFixedRate(collectoRunnable, 0, 10, TimeUnit.SECONDS); }
From source file:eu.vital.vitalcep.collector.Collector.java
private void getCollectorList() { try {//from w ww.ja va 2 s . c o m MongoClient mongo = new MongoClient(new MongoClientURI(mongoURL)); final MongoDatabase db = mongo.getDatabase(mongoDB); BasicDBObject clause1 = new BasicDBObject("cepType", "CONTINUOUS").append("status", "OK"); BasicDBObject clause2 = new BasicDBObject("cepType", "CEPICO"); BasicDBObject clause3 = new BasicDBObject("cepType", "ALERT"); BasicDBList or = new BasicDBList(); or.add(clause1); or.add(clause2); or.add(clause3); BasicDBObject query = new BasicDBObject("$or", or); FindIterable<Document> coll; coll = db.getCollection("cepinstances").find(query); coll.forEach(new Block<Document>() { @Override public void apply(final Document document) { JSONObject oCollector = new JSONObject(); oCollector.put("id", document.getObjectId("_id").toString()); oCollector.put("mqin", document.getString("mqin")); oCollector.put("mqout", document.getString("mqout")); oCollector.put("cepType", document.getString("cepType")); if (document.getString("cepType").equals("CONTINUOUS")) { final Document doc = new Document("sources", document.get("sources")); final String jsonStringSources = doc.toJson(); JSONObject sources = new JSONObject(jsonStringSources); final Document docproperties = new Document("properties", document.get("properties")); final String jsonStringproperties = docproperties.toJson(); JSONObject sourcesproperties = new JSONObject(jsonStringproperties); oCollector.put("sources", sources.getJSONArray("sources")); oCollector.put("properties", sourcesproperties.getJSONArray("properties")); oCollector.put("username", document.getString("username")); oCollector.put("password", document.getString("password")); } else { final Document doc = new Document("requests", document.get("requests")); final String jsonStringRequests = doc.toJson(); JSONObject requestsObject = new JSONObject(jsonStringRequests); oCollector.put("requests", requestsObject.getJSONArray("requests")); oCollector.put("username", document.getString("username")); oCollector.put("password", document.getString("password")); } oCollector.put("lastRequest", document.getString("lastRequest")); sensors.put(oCollector); } }); } catch (Exception e) { String a = "a"; } finally { if (db != null) db = null; if (mongo != null) { mongo.close(); mongo = null; } } }
From source file:eu.vital.vitalcep.publisher.MessageProcessor_publisher.java
@Override public boolean processMsg(MqttMsg mqttMsg) { Encoder encoder = new Encoder(); Date date = new Date(); String xsdTime = getXSDDateTime(date); UUID uuid = UUID.randomUUID(); String id = uuid.toString();//from ww w . j a v a 2 s .co m JSONObject observation = null; try { observation = encoder.dolceOutput2Jsonld(mqttMsg.msg, id, this.sensorId, xsdTime); } catch (ParseException ex) { java.util.logging.Logger.getLogger(MessageProcessor_publisher.class.getName()) .log(java.util.logging.Level.SEVERE, null, ex); } Document doc = null; try { doc = encoder.dolceOutput2Document(mqttMsg.msg, id, this.sensorId, xsdTime); } catch (ParseException ex) { java.util.logging.Logger.getLogger(MessageProcessor_publisher.class.getName()) .log(java.util.logging.Level.SEVERE, null, ex); } logger.debug("MQTTMessage received: " + mqttMsg.msg); MongoClient mongo = null; MongoDatabase db = null; try { mongo = new MongoClient(new MongoClientURI(this.mongoURL)); db = mongo.getDatabase(this.mongoDB); db.getCollection(mongocollection).insertOne(doc); } catch (MongoException ex) { logger.error("observation not saved"); } finally { if (db != null) db = null; if (mongo != null) mongo.close(); } JSONArray body = new JSONArray(); body.put(observation); DMSManager oDMS = new DMSManager(dms_URL, cookie); try { if (!oDMS.pushObservations(body.toString())) { logger.error("couldn't push to DMS"); return false; } else { return true; } } catch (IOException | KeyManagementException | NoSuchAlgorithmException | KeyStoreException ex) { logger.error(ex); } return true; }
From source file:eu.vital.vitalcep.restApp.alert.Alerts.java
/** * Gets the filters.//w ww.ja v a 2s . c o m * * @return the filters */ @GET @Path("getalerts") @Produces(MediaType.APPLICATION_JSON) public String getAlerts() { MongoClient mongo = new MongoClient(new MongoClientURI(mongoURL)); MongoDatabase db = mongo.getDatabase(mongoDB); BasicDBObject query = new BasicDBObject(); BasicDBObject fields = new BasicDBObject().append("_id", false); fields.append("dolceSpecification", false); FindIterable<Document> coll = db.getCollection("alerts").find(query).projection(fields); final JSONArray AllJson = new JSONArray(); coll.forEach(new Block<Document>() { @Override public void apply(final Document document) { AllJson.put(document); } }); if (db != null) db = null; if (mongo != null) { mongo.close(); mongo = null; } return AllJson.toString(); }
From source file:eu.vital.vitalcep.restApp.alert.Alerts.java
/** * Creates a filter.//from ww w . j a va 2 s . c o m * * @param cepico * @param req * @return the filter id * @throws java.io.IOException */ @PUT @Path("createalert") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public Response createAlert(String cepico, @Context HttpServletRequest req) throws IOException { 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(); JSONObject jo = new JSONObject(cepico); if (!jo.has("source")) { return Response.status(Response.Status.BAD_REQUEST).build(); } MongoClient mongo = new MongoClient(new MongoClientURI(mongoURL)); MongoDatabase db = mongo.getDatabase(mongoDB); try { db.getCollection("alerts"); } catch (Exception e) { //System.out.println("Mongo is down"); mongo.close(); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); } finally { if (db != null) db = null; if (mongo != null) { mongo.close(); mongo = null; } } // create an empty query BasicDBObject query = new BasicDBObject(); BasicDBObject fields = new BasicDBObject().append("_id", false); fields.append("dolceSpecification", false); 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) { UUID uuid = UUID.randomUUID(); String randomUUIDString = uuid.toString(); String mqin = RandomStringUtils.randomAlphanumeric(8); String mqout = RandomStringUtils.randomAlphanumeric(8); Date NOW = new Date(); JSONArray requestArray; try { requestArray = createAlertRequests(jo.getJSONArray("source"), ds.getEvents(), getXSDDateTime(NOW)); } catch (Exception e) { return Response.status(Response.Status.BAD_REQUEST) .entity("not available getObservation Service for this sensor ").build(); } CEP cepProcess = new CEP(); if (!(cepProcess.CEPStart(CEP.CEPType.ALERT, ds, mqin, mqout, confFile, requestArray.toString(), credentials))) { return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); } String clientName = cepProcess.fileName; if (cepProcess.PID < 1) { return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); } DBObject dbObject = createAlertSensor(cepico, randomUUIDString, dsjo, cepProcess.id); Document doc = new Document(dbObject.toMap()); try { db.getCollection("alerts").insertOne(doc); JSONObject opState = createOperationalStateObservation(randomUUIDString); String sensorId = host + "/sensor/" + randomUUIDString; MessageProcessor_publisher Publisher_MsgProcc = new MessageProcessor_publisher(this.dmsURL, cookie, sensorId, "alertsobservations", mongoURL, mongoDB);//555 MQTT_connector_subscriper publisher = new MQTT_connector_subscriper(mqout, Publisher_MsgProcc); MqttConnectorContainer.addConnector(publisher.getClientName(), publisher); DBObject oPut = (DBObject) JSON.parse(opState.toString()); Document doc1 = new Document(oPut.toMap()); try { db.getCollection("alertsobservations").insertOne(doc1); String id = doc1.get("_id").toString(); } catch (MongoException ex) { return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); } JSONObject aOutput = new JSONObject(); aOutput.put("id", host + "/sensor/" + randomUUIDString); return Response.status(Response.Status.OK).entity(aOutput.toString()).build(); } catch (MongoException ex) { return Response.status(Response.Status.BAD_REQUEST).build(); } } else { return Response.status(Response.Status.BAD_REQUEST).build(); } } catch (JSONException | IOException e) { return Response.status(Response.Status.BAD_REQUEST).build(); } } return Response.status(Response.Status.BAD_REQUEST).build(); }
From source file:eu.vital.vitalcep.restApp.alert.Alerts.java
/** * Gets a filter./* w w w .j ava2 s . c o m*/ * * @return the filter */ @POST @Path("getAlert") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public Response getAlert(String id) { JSONObject jo = new JSONObject(id); String idjo = jo.getString("id"); MongoClient mongo = new MongoClient(new MongoClientURI(mongoURL)); MongoDatabase db = mongo.getDatabase(mongoDB); try { db.getCollection("alerts"); } catch (Exception e) { //System.out.println("Mongo is down"); mongo.close(); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); } BasicDBObject searchById = new BasicDBObject("id", idjo); String found = null; BasicDBObject fields = new BasicDBObject().append("_id", false); FindIterable<Document> coll = db.getCollection("alerts").find(searchById).projection(fields); try { found = coll.first().toJson(); } catch (Exception e) { return Response.status(Response.Status.NOT_FOUND).build(); } finally { db = null; if (mongo != null) { mongo.close(); mongo = null; } } if (found == null) { return Response.status(Response.Status.NOT_FOUND).build(); } else { return Response.status(Response.Status.OK).entity(found.toString()).build(); } }
From source file:eu.vital.vitalcep.restApp.alert.Alerts.java
/** * Gets a filter./* w w w. j a va 2 s . co m*/ * * @param filterId * @param req * @return the filter */ @DELETE @Path("deletealert") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public Response deleteAlert(String filterId, @Context HttpServletRequest req) throws IOException { MongoClient mongo = null; MongoDatabase db = null; try { 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"); mongo = new MongoClient(new MongoClientURI(mongoURL)); db = mongo.getDatabase(mongoDB); try { db.getCollection("alerts"); } catch (Exception e) { //System.out.println("Mongo is down"); mongo.close(); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); } MongoCollection<Document> coll = db.getCollection("alerts"); 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.ALERT.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(Alerts.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); } } else { return Response.status(Response.Status.NOT_FOUND).build(); } DeleteResult deleteResult = coll.deleteOne(eq("id", idjo)); if (deleteResult.getDeletedCount() < 1) { return Response.status(Response.Status.NOT_FOUND).build(); } else { return Response.status(Response.Status.OK).build(); } } catch (Exception e) { return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); } finally { db = null; if (mongo != null) { mongo.close(); mongo = null; } } }
From source file:eu.vital.vitalcep.restApp.cepRESTApi.CEPICO.java
/** * Gets the filters.//from www . ja v a 2 s . c o m * * @return the filters */ @GET @Path("getcepicos") @Produces(MediaType.APPLICATION_JSON) public Response getCEPICOs() { MongoClient mongo = new MongoClient(new MongoClientURI(mongoURL)); MongoDatabase db = mongo.getDatabase(mongoDB); BasicDBObject query = new BasicDBObject(); BasicDBObject fields = new BasicDBObject().append("_id", false).append("cepinstance", false); fields.append("dolceSpecification", false); FindIterable<Document> coll = db.getCollection("cepicos").find(query).projection(fields); final JSONArray AllJson = new JSONArray(); coll.forEach(new Block<Document>() { @Override public void apply(final Document document) { AllJson.put(document); } }); 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.cepRESTApi.CEPICO.java
/** * Creates a filter./* w w w. ja v a2 s . c om*/ * * @param cepico * @param req * @return the filter id * @throws java.io.IOException */ @PUT @Path("createcepico") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public Response createCEPICO(String cepico, @Context HttpServletRequest req) throws IOException { 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(); JSONObject jo = new JSONObject(cepico); if (!jo.has("source")) { return Response.status(Response.Status.BAD_REQUEST).build(); } MongoClient mongo = new MongoClient(new MongoClientURI(mongoURL)); MongoDatabase db = mongo.getDatabase(mongoDB); try { db.getCollection("cepicos"); } catch (Exception e) { //System.out.println("Mongo is down"); mongo.close(); 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) { UUID uuid = UUID.randomUUID(); String randomUUIDString = uuid.toString(); String mqin = RandomStringUtils.randomAlphanumeric(8); String mqout = RandomStringUtils.randomAlphanumeric(8); Date NOW = new Date(); JSONArray requestArray; try { requestArray = createCEPICORequests(jo.getJSONArray("source"), ds.getEvents(), getXSDDateTime(NOW)); } catch (Exception e) { mongo.close(); return Response.status(Response.Status.BAD_REQUEST) .entity("not available getObservation Service for this sensor ").build(); } CEP cepProcess = new CEP(); if (!(cepProcess.CEPStart(CEP.CEPType.CEPICO, ds, mqin, mqout, confFile, requestArray.toString(), credentials))) { mongo.close(); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); } if (cepProcess.PID < 1) { mongo.close(); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); } DBObject dbObject = createCEPSensor(cepico, randomUUIDString, dsjo, cepProcess.id); Document doc = new Document(dbObject.toMap()); try { db.getCollection("cepicos").insertOne(doc); JSONObject opState = createOperationalStateObservation(randomUUIDString); String sensorId = host + "/sensor/" + randomUUIDString; MessageProcessor_publisher Publisher_MsgProcc = new MessageProcessor_publisher(this.dmsURL, cookie, sensorId, "cepicosobservations", mongoURL, mongoDB);//555 MQTT_connector_subscriper publisher = new MQTT_connector_subscriper(mqout, Publisher_MsgProcc); MqttConnectorContainer.addConnector(publisher.getClientName(), publisher); DBObject oPut = (DBObject) JSON.parse(opState.toString()); Document doc1 = new Document(oPut.toMap()); try { db.getCollection("cepicosobservations").insertOne(doc1); String id = doc1.get("_id").toString(); } catch (MongoException ex) { mongo.close(); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); } JSONObject aOutput = new JSONObject(); aOutput.put("id", host + "/sensor/" + randomUUIDString); return Response.status(Response.Status.OK).entity(aOutput.toString()).build(); } catch (MongoException ex) { return Response.status(Response.Status.BAD_REQUEST).build(); } } else { mongo.close(); return Response.status(Response.Status.BAD_REQUEST).build(); } } catch (MongoException ex) { return Response.status(Response.Status.BAD_REQUEST).build(); } } else { mongo.close(); return Response.status(Response.Status.BAD_REQUEST).build(); } }
From source file:eu.vital.vitalcep.restApp.cepRESTApi.CEPICO.java
/** * Gets a filter.//from w ww . j ava 2 s . c o m * * @return the filter */ @POST @Path("getcepico") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public Response getCEPICO(String id) { JSONObject jo = new JSONObject(id); String idjo = jo.getString("id"); MongoClient mongo = new MongoClient(new MongoClientURI(mongoURL)); MongoDatabase db = mongo.getDatabase(mongoDB); try { db.getCollection("cepicos"); } 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 = null; BasicDBObject fields = new BasicDBObject().append("_id", false).append("cepinstance", false); FindIterable<Document> coll = db.getCollection("cepicos").find(searchById).projection(fields); try { found = coll.first().toJson(); } 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(); } }