List of usage examples for com.mongodb MongoClient getDatabase
public MongoDatabase getDatabase(final String databaseName)
From source file:eu.vital.vitalcep.restApp.vuaippi.Sensor.java
/** * Gets sensors metadata ./* w ww. j a v a 2 s . c o m*/ * * @param info * @param req * @return the metadata of the sensors * @throws java.io.FileNotFoundException */ @POST @Path("metadata") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public Response getSensorMetadata(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); try { JSONObject filter = new JSONObject(info); if (!filter.has("type") && !filter.has("id")) { final JSONArray sensorspool1 = new JSONArray(); // create an empty query BasicDBObject query = new BasicDBObject(); BasicDBObject fields = new BasicDBObject().append("_id", false).append("query", false) .append("data", false).append("complexEvent", false).append("source", false) .append("event", false).append("dolceSpecification", false); FindIterable<Document> coll = db.getCollection("continuousfilters").find(query).projection(fields); coll.forEach(new Block<Document>() { @Override public void apply(final Document document) { String aux = document.toJson(); JSONObject sensoraux = new JSONObject(aux); sensoraux.put("status", "vital:Running"); sensorspool1.put(sensoraux); } }); BasicDBObject query3 = new BasicDBObject(); BasicDBObject fields3 = new BasicDBObject().append("_id", false).append("query", false) .append("data", false).append("complexEvent", false).append("source", false) .append("event", false).append("dolceSpecification", false); FindIterable<Document> coll3 = db.getCollection("staticdatafilters").find(query3) .projection(fields3); coll3.forEach(new Block<Document>() { @Override public void apply(final Document document) { String aux = document.toJson(); JSONObject sensoraux = new JSONObject(aux); sensoraux.put("status", "vital:Running"); sensorspool1.put(sensoraux); } }); BasicDBObject query4 = new BasicDBObject(); BasicDBObject fields4 = new BasicDBObject().append("_id", false).append("query", false) .append("data", false).append("complexEvent", false).append("source", false) .append("event", false).append("dolceSpecification", false); FindIterable<Document> coll4 = db.getCollection("staticqueryfilters").find(query4) .projection(fields4); coll4.forEach(new Block<Document>() { @Override public void apply(final Document document) { String aux = document.toJson(); JSONObject sensoraux = new JSONObject(aux); sensoraux.put("status", "vital:Running"); sensorspool1.put(sensoraux); } }); // create an empty query BasicDBObject fieldscep = new BasicDBObject().append("_id", false).append("source", false) .append("query", false).append("complexEvent", false).append("data", false) .append("event", false).append("dolceSpecification", false); FindIterable<Document> coll2 = db.getCollection("cepicos").find(query).projection(fieldscep); coll2.forEach(new Block<Document>() { @Override public void apply(final Document document) { String aux = document.toJson(); JSONObject sensoraux = new JSONObject(aux); sensoraux.put("status", "vital:Running"); sensorspool1.put(sensoraux); } }); JSONObject monSensor = new JSONObject(); monSensor.put("@context", "http://vital-iot.eu/contexts/sensor.jsonld"); monSensor.put("id", host + "/sensor/1"); monSensor.put("type", "vital:MonitoringSensor"); monSensor.put("name", "CEP System Monitoring Sensor"); monSensor.put("description", "A virtual sensor that monitors the operationalstate of the CEP system"); JSONObject observesItem1 = new JSONObject(); observesItem1.put("type", "vital:OperationalState"); observesItem1.put("id", host + "/sensor/1/operationalState"); JSONObject observesItem2 = new JSONObject(); observesItem2.put("type", "vital:SysUptime"); observesItem2.put("id", host + "/sensor/1/sysUptime"); JSONObject observesItem3 = new JSONObject(); observesItem3.put("type", "vital:SysLoad"); observesItem3.put("id", host + "/sensor/1/sysLoad"); JSONObject observesItem4 = new JSONObject(); observesItem4.put("type", "vital:errors"); observesItem4.put("id", host + "/sensor/1/errors"); JSONArray observes = new JSONArray(); observes.put(observesItem1); observes.put(observesItem2); observes.put(observesItem3); //observes.put(observesItem4); monSensor.put("ssn:observes", observes); monSensor.put("status", "vital:Running"); sensorspool1.put(monSensor); return Response.status(Response.Status.OK).entity(sensorspool1.toString()).build(); } else if (filter.has("type")) { JSONArray filteredSensors = new JSONArray(); final JSONArray sensorspool = new JSONArray(); JSONArray types = filter.getJSONArray("type"); for (int i = 0; i < types.length(); i++) { String type = types.getString(i); switch (type) { case CEPICOSENSOR_TYPE: case "vital:CEPSensor": case "CEPSensor": // create an empty query BasicDBObject fieldscep = new BasicDBObject().append("_id", false).append("source", false) .append("query", false).append("complexEvent", false).append("data", false) .append("event", false).append("dolceSpecification", false); BasicDBObject query = new BasicDBObject(); FindIterable<Document> coll2 = db.getCollection("cepicoss").find(query) .projection(fieldscep); coll2.forEach(new Block<Document>() { @Override public void apply(final Document document) { String aux = document.toJson(); JSONObject sensoraux = new JSONObject(aux); sensoraux.put("status", "vital:Running"); sensorspool.put(sensoraux); } }); break; case MONITORINGSENSOR_TYPE: JSONObject monSensor = new JSONObject(); monSensor.put("@context", "http://vital-iot.eu/contexts/sensor.jsonld"); monSensor.put("id", host + "/sensor/1"); monSensor.put("type", "vital:MonitoringSensor"); monSensor.put("name", "CEP System Monitoring Sensor"); monSensor.put("description", "A virtual sensor that monitors the operationalstate of the CEP system"); JSONObject observesItem1 = new JSONObject(); observesItem1.put("type", "vital:OperationalState"); observesItem1.put("id", host + "/sensor/1/operationalState"); JSONObject observesItem2 = new JSONObject(); observesItem2.put("type", "vital:SysUptime"); observesItem2.put("id", host + "/sensor/1/sysUptime"); JSONObject observesItem3 = new JSONObject(); observesItem3.put("type", "vital:SysLoad"); observesItem3.put("id", host + "/sensor/1/sysLoad"); JSONObject observesItem4 = new JSONObject(); observesItem4.put("type", "vital:errors"); observesItem4.put("id", host + "/sensor/1/errors"); JSONArray observes = new JSONArray(); observes.put(observesItem1); observes.put(observesItem2); observes.put(observesItem3); //observes.put(observesItem4); monSensor.put("ssn:observes", observes); monSensor.put("status", "vital:Running"); sensorspool.put(monSensor); filteredSensors.put(monSensor); break; case CEPFILTERSTATICDATASENSOR_TYPE: case "vital:CEPFilterStaticDataSensor": case "CEPFilterStaticDataSensor": BasicDBObject query3 = new BasicDBObject(); BasicDBObject fields3 = new BasicDBObject().append("_id", false).append("query", false) .append("data", false).append("complexEvent", false).append("source", false) .append("event", false).append("dolceSpecification", false); FindIterable<Document> coll3 = db.getCollection("staticdatafilters").find(query3) .projection(fields3); coll3.forEach(new Block<Document>() { @Override public void apply(final Document document) { String aux = document.toJson(); JSONObject sensoraux = new JSONObject(aux); sensoraux.put("status", "vital:Running"); sensorspool.put(sensoraux); } }); break; case CEPFILTERSTATICQUERYSENSOR_TYPE: case "vital:CEPFilterStaticQuerySensor": case "CEPFilterStaticQuerySensor": BasicDBObject query4 = new BasicDBObject(); BasicDBObject fields4 = new BasicDBObject().append("_id", false).append("query", false) .append("data", false).append("complexEvent", false).append("source", false) .append("event", false).append("dolceSpecification", false); FindIterable<Document> coll4 = db.getCollection("staticqueryfilters").find(query4) .projection(fields4); coll4.forEach(new Block<Document>() { @Override public void apply(final Document document) { String aux = document.toJson(); JSONObject sensoraux = new JSONObject(aux); sensoraux.put("status", "vital:Running"); sensorspool.put(sensoraux); } }); break; case CEPFILTERSENSOR_TYPE: case "vital:CEPFilterSensor": case "CEPFilterSensor": // create an empty query BasicDBObject query2 = new BasicDBObject(); BasicDBObject fields = new BasicDBObject().append("_id", false).append("query", false) .append("data", false).append("complexEvent", false).append("source", false) .append("event", false).append("dolceSpecification", false); FindIterable<Document> coll = db.getCollection("continuousfilters").find(query2) .projection(fields); coll.forEach(new Block<Document>() { @Override public void apply(final Document document) { String aux = document.toJson(); JSONObject sensoraux = new JSONObject(aux); sensoraux.put("status", "vital:Running"); sensorspool.put(sensoraux); } }); break; default: return Response.status(Response.Status.BAD_REQUEST).build(); } } return Response.status(Response.Status.OK).entity(sensorspool.toString()).build(); } else if (filter.has("id")) { final JSONArray sensorspool2 = new JSONArray(); JSONArray ids = filter.getJSONArray("id"); for (int i = 0; i < ids.length(); i++) { String id = ids.getString(i); // create an empty query BasicDBObject query = new BasicDBObject("id", id); BasicDBObject fields = new BasicDBObject().append("_id", false).append("query", false) .append("data", false).append("complexEvent", false).append("source", false) .append("event", false).append("dolceSpecification", false); FindIterable<Document> coll = db.getCollection("filters").find(query).projection(fields); coll.forEach(new Block<Document>() { @Override public void apply(final Document document) { String aux = document.toJson(); JSONObject sensoraux = new JSONObject(aux); sensoraux.put("status", "vital:Running"); sensorspool2.put(sensoraux); } }); BasicDBObject fields3 = new BasicDBObject().append("_id", false).append("query", false) .append("data", false).append("complexEvent", false).append("source", false) .append("event", false).append("dolceSpecification", false); FindIterable<Document> coll3 = db.getCollection("staticdatafilters").find(query) .projection(fields3); coll3.forEach(new Block<Document>() { @Override public void apply(final Document document) { String aux = document.toJson(); JSONObject sensoraux = new JSONObject(aux); sensoraux.put("status", "vital:Running"); sensorspool2.put(sensoraux); } }); BasicDBObject fields4 = new BasicDBObject().append("_id", false).append("query", false) .append("data", false).append("complexEvent", false).append("source", false) .append("event", false).append("dolceSpecification", false); FindIterable<Document> coll4 = db.getCollection("staticqueryfilters").find(query) .projection(fields4); coll4.forEach(new Block<Document>() { @Override public void apply(final Document document) { String aux = document.toJson(); JSONObject sensoraux = new JSONObject(aux); sensoraux.put("status", "vital:Running"); sensorspool2.put(sensoraux); } }); // create an empty query BasicDBObject fieldscep = new BasicDBObject().append("_id", false).append("source", false) .append("query", false).append("complexEvent", false).append("data", false) .append("event", false).append("dolceSpecification", false); FindIterable<Document> coll2 = db.getCollection("ceps").find(query).projection(fieldscep); coll2.forEach(new Block<Document>() { @Override public void apply(final Document document) { String aux = document.toJson(); JSONObject sensoraux = new JSONObject(aux); sensoraux.put("status", "vital:Running"); sensorspool2.put(sensoraux); } }); if (id.equals(host + "/sensor/1")) { JSONObject monSensor = new JSONObject(); monSensor.put("@context", "http://vital-iot.eu/contexts/sensor.jsonld"); monSensor.put("id", host + "/sensor/1"); monSensor.put("type", "vital:MonitoringSensor"); monSensor.put("name", "CEP System Monitoring Sensor"); monSensor.put("description", "A virtual sensor that monitors the operationalstate of the CEP system"); JSONObject observesItem1 = new JSONObject(); observesItem1.put("type", "vital:OperationalState"); observesItem1.put("id", host + "/sensor/1/operationalState"); JSONObject observesItem2 = new JSONObject(); observesItem2.put("type", "vital:SysUptime"); observesItem2.put("id", host + "/sensor/1/sysUptime"); JSONObject observesItem3 = new JSONObject(); observesItem3.put("type", "vital:SysLoad"); observesItem3.put("id", host + "/sensor/1/sysLoad"); JSONObject observesItem4 = new JSONObject(); observesItem4.put("type", "vital:errors"); observesItem4.put("id", host + "/sensor/1/errors"); JSONArray observes = new JSONArray(); observes.put(observesItem1); observes.put(observesItem2); observes.put(observesItem3); //observes.put(observesItem4); monSensor.put("ssn:observes", observes); monSensor.put("status", "vital:Running"); sensorspool2.put(monSensor); } } return Response.status(Response.Status.OK).entity(sensorspool2.toString()).build(); } } catch (JSONException ex) { return Response.status(Response.Status.BAD_REQUEST).build(); } finally { db = null; if (mongo != null) { mongo.close(); mongo = null; } } return Response.status(Response.Status.BAD_REQUEST).build(); }
From source file:eu.vital.vitalcep.restApp.vuaippi.Sensor.java
/** * Gets sensors status ./*from w ww . java 2 s . c o m*/ * * @param info * @param req * @return the metadata of the sensors * @throws java.io.FileNotFoundException */ @POST @Path("status") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public Response getSensorStatus(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); final JSONArray sensorspool = new JSONArray(); try { JSONObject filter = new JSONObject(info); if (filter.has("id")) { JSONArray ids = filter.getJSONArray("id"); for (int i = 0; i < ids.length(); i++) { String id = ids.getString(i); BasicDBObject query = new BasicDBObject("ssn:featureOfInterest", id); BasicDBObject fields = new BasicDBObject().append("_id", false); FindIterable<Document> coll = db.getCollection("filtersobservations").find(query) .projection(fields); coll.forEach(new Block<Document>() { @Override public void apply(final Document document) { String aux = document.toJson(); JSONObject sensoraux = new JSONObject(aux); sensorspool.put(sensoraux); } }); BasicDBObject fields3 = new BasicDBObject().append("_id", false).append("query", false) .append("data", false).append("complexEvent", false).append("source", false) .append("event", false).append("dolceSpecification", false); FindIterable<Document> coll3 = db.getCollection("staticdatafiltersobservations").find(query) .projection(fields3); //DBCollection coll3 = db.getCollection("staticdatafiltersobservations"); coll3.forEach(new Block<Document>() { @Override public void apply(final Document document) { String aux = document.toJson(); JSONObject sensoraux = new JSONObject(aux); sensorspool.put(sensoraux); } }); BasicDBObject fields4 = new BasicDBObject().append("_id", false).append("query", false) .append("data", false).append("complexEvent", false).append("source", false) .append("event", false).append("dolceSpecification", false); FindIterable<Document> coll4 = db.getCollection("staticqueryfiltersobservations").find(query) .projection(fields4); //DBCollection coll4 = db.getCollection("staticqueryfiltersobservations"); coll4.forEach(new Block<Document>() { @Override public void apply(final Document document) { String aux = document.toJson(); JSONObject sensoraux = new JSONObject(aux); sensorspool.put(sensoraux); } }); BasicDBObject fieldscep = new BasicDBObject().append("_id", false).append("source", false) .append("query", false).append("complexEvent", false).append("data", false) .append("event", false).append("dolceSpecification", false); //DBCollection coll2 = db.getCollection("cepsobservations"); // create an empty query FindIterable<Document> coll2 = db.getCollection("cepsobservations").find(query) .projection(fieldscep); coll2.forEach(new Block<Document>() { @Override public void apply(final Document document) { String aux = document.toJson(); JSONObject sensoraux = new JSONObject(aux); sensorspool.put(sensoraux); } }); DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX"); if (id.equals(host + "/sensor/1")) { JSONObject opState = new JSONObject(); opState.put("@context", "http://vital-iot.eu/contexts/measurement.jsonld"); opState.put("id", host + "/sensor/1/observation/1"); opState.put("type", "ssn:Observation"); opState.put("ssn:featureOfInterest", host + "/sensor/1"); JSONObject property = new JSONObject(); property.put("type", "vital:OperationalState"); opState.put("ssn:observationProperty", property); JSONObject resultTime = new JSONObject(); Date date = new Date(); resultTime.put("time:inXSDDateTime", dateFormat.format(date));//check format opState.put("ssn:observationResultTime", resultTime); //"time:inXSDDateTime": "2015-10-14T11:59:11+02:00" JSONObject hasValue = new JSONObject(); hasValue.put("type", "ssn:ObservationValue"); hasValue.put("value", "vital:Running"); JSONObject observationResult = new JSONObject(); observationResult.put("ssn:hasValue", hasValue); observationResult.put("type", "ssn:SensorOutput"); opState.put("ssn:observationResult", observationResult); sensorspool.put(opState); JSONObject sysUpTime = new JSONObject(); sysUpTime.put("@context", "http://vital-iot.eu/contexts/measurement.jsonld"); sysUpTime.put("id", host + "/sensor/1/observation/2"); sysUpTime.put("type", "ssn:Observation"); JSONObject property2 = new JSONObject(); property2.put("type", "vital:SysUptime"); sysUpTime.put("ssn:observationProperty", property2); JSONObject resultTime2 = new JSONObject(); Date date2 = new Date(); resultTime2.put("time:inXSDDateTime", dateFormat.format(date2));//check format sysUpTime.put("ssn:observationResultTime", resultTime2); sysUpTime.put("ssn:featureOfInterest", host + "/sensor/1"); JSONObject hasValue2 = new JSONObject(); hasValue2.put("type", "ssn:ObservationValue"); RuntimeMXBean rb = ManagementFactory.getRuntimeMXBean(); long uptime = rb.getUptime(); hasValue2.put("value", "" + uptime); hasValue2.put("qudt:unit", "qudt:Milliseconds"); JSONObject observationResult2 = new JSONObject(); observationResult2.put("ssn:hasValue", hasValue2); observationResult2.put("type", "ssn:SensorOutput"); sysUpTime.put("ssn:observationResult", observationResult2); sensorspool.put(sysUpTime); JSONObject sysLoad = new JSONObject(); sysLoad.put("@context", "http://vital-iot.eu/contexts/measurement.jsonld"); sysLoad.put("id", host + "/sensor/1/observation/3"); sysLoad.put("type", "ssn:Observation"); JSONObject property3 = new JSONObject(); property3.put("type", "vital:SysLoad"); sysLoad.put("ssn:observationProperty", property3); JSONObject resultTime3 = new JSONObject(); Date date3 = new Date(); resultTime3.put("time:inXSDDateTime", dateFormat.format(date3));//check format sysLoad.put("ssn:observationResultTime", resultTime3); sysLoad.put("ssn:featureOfInterest", host + "/sensor/1"); JSONObject hasValue3 = new JSONObject(); hasValue3.put("type", "ssn:ObservationValue"); hasValue3.put("value", ThreadLocalRandom.current().nextInt(1, 5 + 1) + "%"); hasValue3.put("qudt:unit", "qudt:Percent"); JSONObject observationResult3 = new JSONObject(); observationResult3.put("ssn:hasValue", hasValue3); observationResult3.put("type", "ssn:SensorOutput"); sysLoad.put("ssn:observationResult", observationResult3); sensorspool.put(sysLoad); } } } else if (filter.has("type")) { JSONArray types = filter.getJSONArray("type"); for (int i = 0; i < types.length(); i++) { String type = types.getString(i); BasicDBObject query = new BasicDBObject(); switch (type) { case CEPICOSENSOR_TYPE: //DBCollection coll2 = db.getCollection("cepsobservations"); // create an empty query BasicDBObject fieldscep = new BasicDBObject().append("_id", false).append("source", false) .append("query", false).append("complexEvent", false).append("data", false) .append("event", false).append("dolceSpecification", false); FindIterable<Document> coll2 = db.getCollection("cepsobservations").find(query) .projection(fieldscep); coll2.forEach(new Block<Document>() { @Override public void apply(final Document document) { String aux = document.toJson(); JSONObject sensoraux = new JSONObject(aux); sensorspool.put(sensoraux); } }); break; case MONITORINGSENSOR_TYPE: DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX"); JSONObject opState = new JSONObject(); opState.put("@context", "http://vital-iot.eu/contexts/measurement.jsonld"); opState.put("id", host + "/sensor/1/observation/1"); opState.put("type", "ssn:Observation"); opState.put("ssn:featureOfInterest", host + "/sensor/1"); JSONObject property = new JSONObject(); property.put("type", "vital:OperationalState"); opState.put("ssn:observationProperty", property); JSONObject resultTime = new JSONObject(); Date date = new Date(); resultTime.put("time:inXSDDateTime", dateFormat.format(date));//check format opState.put("ssn:observationResultTime", resultTime); //"time:inXSDDateTime": "2015-10-14T11:59:11+02:00" JSONObject hasValue = new JSONObject(); hasValue.put("type", "ssn:ObservationValue"); hasValue.put("value", "vital:Running"); JSONObject observationResult = new JSONObject(); observationResult.put("ssn:hasValue", hasValue); observationResult.put("type", "ssn:SensorOutput"); opState.put("ssn:observationResult", observationResult); sensorspool.put(opState); JSONObject sysUpTime = new JSONObject(); sysUpTime.put("@context", "http://vital-iot.eu/contexts/measurement.jsonld"); sysUpTime.put("id", host + "/sensor/1/observation/2"); sysUpTime.put("type", "ssn:Observation"); JSONObject property2 = new JSONObject(); property2.put("type", "vital:SysUptime"); sysUpTime.put("ssn:observationProperty", property2); JSONObject resultTime2 = new JSONObject(); Date date2 = new Date(); resultTime2.put("time:inXSDDateTime", dateFormat.format(date2));//check format sysUpTime.put("ssn:observationResultTime", resultTime2); sysUpTime.put("ssn:featureOfInterest", host + "/sensor/1"); JSONObject hasValue2 = new JSONObject(); hasValue2.put("type", "ssn:ObservationValue"); RuntimeMXBean rb = ManagementFactory.getRuntimeMXBean(); long uptime = rb.getUptime(); hasValue2.put("value", "" + uptime); hasValue2.put("qudt:unit", "qudt:Milliseconds"); JSONObject observationResult2 = new JSONObject(); observationResult2.put("ssn:hasValue", hasValue2); observationResult2.put("type", "ssn:SensorOutput"); sysUpTime.put("ssn:observationResult", observationResult2); sensorspool.put(sysUpTime); JSONObject sysLoad = new JSONObject(); sysLoad.put("@context", "http://vital-iot.eu/contexts/measurement.jsonld"); sysLoad.put("id", host + "/sensor/1/observation/3"); sysLoad.put("type", "ssn:Observation"); JSONObject property3 = new JSONObject(); property3.put("type", "vital:SysLoad"); sysLoad.put("ssn:observationProperty", property3); JSONObject resultTime3 = new JSONObject(); Date date3 = new Date(); resultTime3.put("time:inXSDDateTime", dateFormat.format(date3));//check format sysLoad.put("ssn:observationResultTime", resultTime3); sysLoad.put("ssn:featureOfInterest", host + "/sensor/1"); JSONObject hasValue3 = new JSONObject(); hasValue3.put("type", "ssn:ObservationValue"); hasValue3.put("value", ThreadLocalRandom.current().nextInt(1, 5 + 1) + "%"); hasValue3.put("qudt:unit", "qudt:Percent"); JSONObject observationResult3 = new JSONObject(); observationResult3.put("ssn:hasValue", hasValue3); observationResult3.put("type", "ssn:SensorOutput"); sysLoad.put("ssn:observationResult", observationResult3); sensorspool.put(sysLoad); break; case CEPFILTERSTATICDATASENSOR_TYPE: //DBCollection coll3 = db.getCollection("staticdatafiltersobservations"); BasicDBObject fields3 = new BasicDBObject().append("_id", false).append("query", false) .append("data", false).append("complexEvent", false).append("source", false) .append("event", false).append("dolceSpecification", false); FindIterable<Document> coll3 = db.getCollection("staticdatafiltersobservations").find(query) .projection(fields3); coll3.forEach(new Block<Document>() { @Override public void apply(final Document document) { String aux = document.toJson(); JSONObject sensoraux = new JSONObject(aux); sensorspool.put(sensoraux); } }); break; case CEPFILTERSTATICQUERYSENSOR_TYPE: //DBCollection coll4 = db.getCollection("staticqueryfiltersobservations"); BasicDBObject fields4 = new BasicDBObject().append("_id", false).append("query", false) .append("data", false).append("complexEvent", false).append("source", false) .append("event", false).append("dolceSpecification", false); FindIterable<Document> coll4 = db.getCollection("staticqueryfiltersobservations") .find(query).projection(fields4); coll4.forEach(new Block<Document>() { @Override public void apply(final Document document) { String aux = document.toJson(); JSONObject sensoraux = new JSONObject(aux); sensorspool.put(sensoraux); } }); break; case CEPFILTERSENSOR_TYPE: //DBCollection coll = db.getCollection("filtersobservations"); BasicDBObject fields = new BasicDBObject().append("_id", false).append("query", false) .append("data", false).append("complexEvent", false).append("source", false) .append("event", false).append("dolceSpecification", false); FindIterable<Document> coll = db.getCollection("filtersobservations").find(query) .projection(fields); coll.forEach(new Block<Document>() { @Override public void apply(final Document document) { String aux = document.toJson(); JSONObject sensoraux = new JSONObject(aux); sensorspool.put(sensoraux); } }); break; default: return Response.status(Response.Status.BAD_REQUEST).build(); } } } else { //DBCollection coll = db.getCollection("filtersobservations"); // create an empty query BasicDBObject query = new BasicDBObject(); BasicDBObject fields = new BasicDBObject().append("_id", false); FindIterable<Document> coll = db.getCollection("filtersobservations").find(query) .projection(fields); coll.forEach(new Block<Document>() { @Override public void apply(final Document document) { JSONObject curr = new JSONObject(); curr.put("@context", "http://vital-iot.eu/contexts/measurement.jsonld"); curr.put("id", document.get("id")); curr.put("type", "ssn:Observation"); curr.put("ssn:featureOfInterest", document.get("id")); JSONObject property = new JSONObject(); property.put("type", "vital:ComplexEvent"); curr.put("ssn:observationProperty", property); JSONObject resultTime = new JSONObject(); DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX"); Date date = new Date(); resultTime.put("time:inXSDDateTime", dateFormat.format(date));//check format curr.put("ssn:observationResultTime", resultTime); //"time:inXSDDateTime": "2015-10-14T11:59:11+02:00" JSONObject hasValue = new JSONObject(); hasValue.put("type", "ssn:ObservationValue"); hasValue.put("value", "vital:Running"); JSONObject observationResult = new JSONObject(); observationResult.put("ssn:hasValue", hasValue); observationResult.put("type", "ssn:SensorOutput"); curr.put("ssn:observationResult", observationResult); sensorspool.put(curr); } }); BasicDBObject fields3 = new BasicDBObject().append("_id", false); FindIterable<Document> coll3 = db.getCollection("filtersobservations").find(query) .projection(fields3); coll3.forEach(new Block<Document>() { @Override public void apply(final Document document) { JSONObject curr = new JSONObject(); curr.put("@context", "http://vital-iot.eu/contexts/measurement.jsonld"); curr.put("id", document.get("id")); curr.put("type", "ssn:Observation"); curr.put("ssn:featureOfInterest", document.get("ssn:featureOfInterest")); JSONObject property = new JSONObject(); property.put("type", "vital:ComplexEvent"); curr.put("ssn:observationProperty", property); JSONObject resultTime = new JSONObject(); DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX"); Date date = new Date(); resultTime.put("time:inXSDDateTime", dateFormat.format(date));//check format curr.put("ssn:observationResultTime", resultTime); //"time:inXSDDateTime": "2015-10-14T11:59:11+02:00" JSONObject hasValue = new JSONObject(); hasValue.put("type", "ssn:ObservationValue"); hasValue.put("value", "vital:Running"); JSONObject observationResult = new JSONObject(); observationResult.put("ssn:hasValue", hasValue); observationResult.put("type", "ssn:SensorOutput"); curr.put("ssn:observationResult", observationResult); sensorspool.put(curr); } }); BasicDBObject fields4 = new BasicDBObject().append("_id", false).append("query", false) .append("data", false).append("complexEvent", false).append("source", false) .append("event", false).append("dolceSpecification", false); FindIterable<Document> coll4 = db.getCollection("staticqueryfiltersobservations").find(query) .projection(fields4); coll4.forEach(new Block<Document>() { @Override public void apply(final Document document) { JSONObject curr = new JSONObject(); curr.put("@context", "http://vital-iot.eu/contexts/measurement.jsonld"); curr.put("id", document.get("id")); curr.put("type", "ssn:Observation"); curr.put("ssn:featureOfInterest", document.get("ssn:featureOfInterest")); JSONObject property = new JSONObject(); property.put("type", "vital:ComplexEvent"); curr.put("ssn:observationProperty", property); JSONObject resultTime = new JSONObject(); DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX"); Date date = new Date(); resultTime.put("time:inXSDDateTime", dateFormat.format(date));//check format curr.put("ssn:observationResultTime", resultTime); //"time:inXSDDateTime": "2015-10-14T11:59:11+02:00" JSONObject hasValue = new JSONObject(); hasValue.put("type", "ssn:ObservationValue"); hasValue.put("value", "vital:Running"); JSONObject observationResult = new JSONObject(); observationResult.put("ssn:hasValue", hasValue); observationResult.put("type", "ssn:SensorOutput"); curr.put("ssn:observationResult", observationResult); sensorspool.put(curr); } }); BasicDBObject fieldscep = new BasicDBObject().append("_id", false); FindIterable<Document> coll2 = db.getCollection("cepsobservations").find(query) .projection(fieldscep); coll2.forEach(new Block<Document>() { @Override public void apply(final Document document) { if (document.containsKey("id")) { JSONObject curr = new JSONObject(); curr.put("@context", "http://vital-iot.eu/contexts/measurement.jsonld"); curr.put("id", document.get("id")); curr.put("type", "ssn:Observation"); curr.put("ssn:featureOfInterest", document.get("ssn:featureOfInterest"));//ver JSONObject property = new JSONObject(); property.put("type", "vital:ComplexEvent"); curr.put("ssn:observationProperty", property); JSONObject resultTime = new JSONObject(); DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX"); Date date = new Date(); resultTime.put("time:inXSDDateTime", dateFormat.format(date));//check format curr.put("ssn:observationResultTime", resultTime); //"time:inXSDDateTime": "2015-10-14T11:59:11+02:00" JSONObject hasValue = new JSONObject(); hasValue.put("type", "ssn:ObservationValue"); hasValue.put("value", "vital:Running"); JSONObject observationResult = new JSONObject(); observationResult.put("ssn:hasValue", hasValue); observationResult.put("type", "ssn:SensorOutput"); curr.put("ssn:observationResult", observationResult); sensorspool.put(curr); } } }); JSONObject opState = new JSONObject(); opState.put("@context", "http://vital-iot.eu/contexts/measurement.jsonld"); opState.put("id", host + "/sensor/1/observation/1"); opState.put("type", "ssn:Observation"); opState.put("ssn:featureOfInterest", host + "/sensor/1"); JSONObject property = new JSONObject(); property.put("type", "vital:OperationalState"); opState.put("ssn:observationProperty", property); JSONObject resultTime = new JSONObject(); DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX"); Date date = new Date(); resultTime.put("time:inXSDDateTime", dateFormat.format(date));//check format opState.put("ssn:observationResultTime", resultTime); //"time:inXSDDateTime": "2015-10-14T11:59:11+02:00" JSONObject hasValue = new JSONObject(); hasValue.put("type", "ssn:ObservationValue"); hasValue.put("value", "vital:Running"); JSONObject observationResult = new JSONObject(); observationResult.put("ssn:hasValue", hasValue); observationResult.put("type", "ssn:SensorOutput"); opState.put("ssn:observationResult", observationResult); JSONObject sysUpTime = new JSONObject(); sysUpTime.put("@context", "http://vital-iot.eu/contexts/measurement.jsonld"); sysUpTime.put("id", host + "/sensor/1/observation/2"); sysUpTime.put("type", "ssn:Observation"); JSONObject property2 = new JSONObject(); property2.put("type", "vital:SysUptime"); sysUpTime.put("ssn:observationProperty", property2); JSONObject resultTime2 = new JSONObject(); Date date2 = new Date(); resultTime2.put("time:inXSDDateTime", dateFormat.format(date2));//check format sysUpTime.put("ssn:observationResultTime", resultTime2); sysUpTime.put("ssn:featureOfInterest", host + "/sensor/1"); JSONObject hasValue2 = new JSONObject(); hasValue2.put("type", "ssn:ObservationValue"); RuntimeMXBean rb = ManagementFactory.getRuntimeMXBean(); long uptime = rb.getUptime(); hasValue2.put("value", "" + uptime); hasValue2.put("qudt:unit", "qudt:Milliseconds"); JSONObject observationResult2 = new JSONObject(); observationResult2.put("ssn:hasValue", hasValue2); observationResult2.put("type", "ssn:SensorOutput"); sysUpTime.put("ssn:observationResult", observationResult2); JSONObject sysLoad = new JSONObject(); sysLoad.put("@context", "http://vital-iot.eu/contexts/measurement.jsonld"); sysLoad.put("id", host + "/sensor/1/observation/3"); sysLoad.put("type", "ssn:Observation"); JSONObject property3 = new JSONObject(); property3.put("type", "vital:SysLoad"); sysLoad.put("ssn:observationProperty", property3); JSONObject resultTime3 = new JSONObject(); Date date3 = new Date(); resultTime3.put("time:inXSDDateTime", dateFormat.format(date3));//check format sysLoad.put("ssn:observationResultTime", resultTime3); sysLoad.put("ssn:featureOfInterest", host + "/sensor/1"); JSONObject hasValue3 = new JSONObject(); hasValue3.put("type", "ssn:ObservationValue"); hasValue3.put("value", ThreadLocalRandom.current().nextInt(1, 5 + 1) + "%"); hasValue3.put("qudt:unit", "qudt:Percent"); JSONObject observationResult3 = new JSONObject(); observationResult3.put("ssn:hasValue", hasValue3); observationResult3.put("type", "ssn:SensorOutput"); sysLoad.put("ssn:observationResult", observationResult3); sensorspool.put(opState); sensorspool.put(sysUpTime); sensorspool.put(sysLoad); } } catch (JSONException ex) { return Response.status(Response.Status.BAD_REQUEST).build(); } return Response.status(Response.Status.OK).entity(sensorspool.toString()).build(); }
From source file:eu.vital.vitalcep.restApp.vuaippi.Sensor.java
private JSONArray getObservations(BasicDBList sensor, String property, String from, String to) { JSONArray aData = new JSONArray(); BasicDBObject query = new BasicDBObject(); final JSONArray oObservations = new JSONArray(); MongoClient mongo = new MongoClient(new MongoClientURI(mongoURL)); MongoDatabase db = mongo.getDatabase(mongoDB); if (!(to == null) && !(from == null)) { try {// w ww.ja va2 s . c o m String queryS = createQuery(sensor, property, from, to); Object queryO = com.mongodb.util.JSON.parse(queryS); query = (BasicDBObject) queryO; Block<Document> block = new Block<Document>() { @Override public void apply(final Document document) { JSONObject oCollector = new JSONObject(document.toJson()); oObservations.put(oCollector); } }; db.getCollection("cepicosobservations").find(query).projection(fields(excludeId())).forEach(block); db.getCollection("continuosfiltersobservations").find(query).projection(fields(excludeId())) .forEach(block); db.getCollection("alertsobservations").find(query).projection(fields(excludeId())).forEach(block); db.getCollection("staticdatafiltersobservations").find(query).projection(fields(excludeId())) .forEach(block); db.getCollection("staticqueryfiltersobservations").find(query).projection(fields(excludeId())) .forEach(block); } catch (Exception e) { String a = "a"; } finally { db = null; if (mongo != null) { mongo.close(); mongo = null; } } } else { try { Object queryO = com.mongodb.util.JSON.parse(createQuery(sensor, property, null, null)); query = (BasicDBObject) queryO; Block<Document> block = new Block<Document>() { @Override public void apply(final Document document) { JSONObject oCollector = new JSONObject(document.toJson()); oObservations.put(oCollector); } }; BasicDBObject sortObject = new BasicDBObject().append("_id", -1); db.getCollection("cepicosobservations").find(query).projection(fields(excludeId())).sort(sortObject) .limit(1).forEach(block); db.getCollection("continuosfiltersobservations").find(query).projection(fields(excludeId())) .sort(sortObject).limit(1).forEach(block); db.getCollection("alertsobservations").find(query).projection(fields(excludeId())).sort(sortObject) .limit(1).forEach(block); db.getCollection("staticdatafiltersobservations").find(query).projection(fields(excludeId())) .sort(sortObject).limit(1).forEach(block); db.getCollection("staticqueryfiltersobservations").find(query).projection(fields(excludeId())) .sort(sortObject).limit(1).forEach(block); } catch (Exception e) { String a = "a"; } finally { db = null; if (mongo != null) { mongo.close(); mongo = null; } } } return oObservations; }
From source file:eu.vital.vitalcep.restApp.vuaippi.System.java
@POST @Path("metadata") @Consumes(MediaType.APPLICATION_JSON)/*from w ww . ja v a 2 s.c o m*/ @Produces(MediaType.APPLICATION_JSON) public Response getSystemMetadata(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); BasicDBObject query = new BasicDBObject(); BasicDBObject fields = new BasicDBObject().append("_id", false); fields.append("dolceSpecification", false); FindIterable<Document> collStaticData = db.getCollection("staticdatafilters").find(query) .projection(fields); final JSONArray sensors = new JSONArray(); collStaticData.forEach(new Block<Document>() { @Override public void apply(final Document document) { sensors.put(document.get("id")); } }); FindIterable<Document> collStaticQuery = db.getCollection("staticqueryfilters").find(query) .projection(fields); collStaticQuery.forEach(new Block<Document>() { @Override public void apply(final Document document) { sensors.put(document.get("id")); } }); FindIterable<Document> collContinuous = db.getCollection("continuousfilters").find(query) .projection(fields); collContinuous.forEach(new Block<Document>() { @Override public void apply(final Document document) { sensors.put(document.get("id")); } }); BasicDBObject querycep = new BasicDBObject(); BasicDBObject fieldscep = new BasicDBObject().append("_id", false).append("dolceSpecification", false); FindIterable<Document> collcepicos = db.getCollection("cepicos").find(querycep).projection(fieldscep); // create an empty query collcepicos.forEach(new Block<Document>() { @Override public void apply(final Document document) { sensors.put(document.get("id")); } }); BasicDBObject queryalert = new BasicDBObject(); BasicDBObject fieldsalert = new BasicDBObject().append("_id", false).append("dolceSpecification", false); FindIterable<Document> collalerts = db.getCollection("alerts").find(queryalert).projection(fieldsalert); // create an empty query collalerts.forEach(new Block<Document>() { @Override public void apply(final Document document) { sensors.put(document.get("id")); } }); sensors.put(host + "/sensor/1"); JSONObject metadata = new JSONObject(); JSONArray services = new JSONArray(); services.put(host + "/service/monitoring"); services.put(host + "/service/cepicosmanagement"); services.put(host + "/service/filtering"); services.put(host + "/service/alertingmanagement"); services.put(host + "/service/observation"); metadata.put("@context", "http://vital-iot.eu/contexts/system.jsonld"); metadata.put("id", host); metadata.put("type", "vital:VitalSystem"); metadata.put("name", "CEP IoT system"); metadata.put("description", "This is a VITAL compliant IoT system."); metadata.put("operator", "elisa.herrmann@atos.net"); metadata.put("status", "vital:Running"); metadata.put("services", services); // metadata.put("sensors", sensors); metadata.append("sensors", sensors); db = null; if (mongo != null) { mongo.close(); mongo = null; } return Response.status(Response.Status.OK).entity(metadata.toString()).build(); }
From source file:eu.vre4eic.evre.telegram.commands.RegisterAuthCommand.java
License:Apache License
@Override public void execute(AbsSender absSender, User user, Chat chat, String[] arguments) { String userName = user.getFirstName() + " " + user.getLastName(); StringBuilder messageBuilder = new StringBuilder(); if (arguments.length != 2) { messageBuilder.append("Hi ").append(userName).append("\n"); messageBuilder.append("please use: /register username pwd"); } else {/* ww w .j a v a 2 s. c o m*/ MongoClient mongoClient = new MongoClient("localhost", 27017); MongoDatabase db = mongoClient.getDatabase("evre"); MongoCollection<Document> collection = db.getCollection("eVREUserProfile"); BasicDBObject searchQuery = new BasicDBObject(); searchQuery.put("userId", arguments[0]); FindIterable<Document> itcursor = collection.find(searchQuery); //FindIterable<Document> itcursor=collection.find(); MongoCursor<Document> cursor = itcursor.iterator(); if (cursor.hasNext()) { Document userCan = cursor.next(); String pwd = userCan.getString("password"); Binary binS = userCan.get("salt", org.bson.types.Binary.class); String salt = new String(binS.getData()); boolean validUser = false; if (pwd.equals(arguments[1])) validUser = true; if (salt != null && !checkEncryptedData(arguments[1], salt.getBytes()).equals(arguments[1])) validUser = true; //if(pwd.equals(arguments[1])){ if (validUser) { userCan.replace("authId", chat.getId()); BasicDBObject updateObj = new BasicDBObject(); updateObj.put("$set", userCan); //check this!!! collection.updateOne(searchQuery, updateObj); messageBuilder.append("Done ").append(userName).append(",\n"); messageBuilder.append( "this Telegram account is now registered as e-VRE Authenticator for " + arguments[0]); } else {//error credentials wrong messageBuilder.append("Hi ").append(userName).append("\n"); messageBuilder.append("credentials not valid!"); } } else {//error credentials wrong messageBuilder.append("Hi ").append(userName).append("\n"); messageBuilder.append("credentials not valid!"); } mongoClient.close(); } SendMessage answer = new SendMessage(); answer.setChatId(chat.getId().toString()); answer.setText(messageBuilder.toString()); try { absSender.sendMessage(answer); } catch (TelegramApiException e) { BotLogger.error(LOGTAG, e); } }
From source file:eu.vre4eic.evre.telegram.commands.RemoveAuthCommand.java
License:Apache License
@Override public void execute(AbsSender absSender, User user, Chat chat, String[] arguments) { String userName = user.getFirstName() + " " + user.getLastName(); StringBuilder messageBuilder = new StringBuilder(); if (arguments.length != 2) { messageBuilder.append("Hi ").append(userName).append("\n"); messageBuilder.append("please use: /remove username pwd"); } else {//from w ww. j av a2 s . c om MongoClient mongoClient = new MongoClient("localhost", 27017); MongoDatabase db = mongoClient.getDatabase("evre"); MongoCollection<Document> collection = db.getCollection("eVREUserProfile"); BasicDBObject searchQuery = new BasicDBObject(); searchQuery.put("userId", arguments[0]); FindIterable<Document> itcursor = collection.find(searchQuery); //FindIterable<Document> itcursor=collection.find(); MongoCursor<Document> cursor = itcursor.iterator(); if (cursor.hasNext()) { //System.out.println("################## "+cursor.next()); Document userCan = cursor.next(); String pwd = userCan.getString("password"); if (pwd.equals(arguments[1])) { String aId = userCan.getString("authId"); if (!aId.equals("0")) { // we don't check if the chat.getId() is the same, //because a user can remove this from another Telegram ID, // need to check this userCan.replace("authId", "0"); BasicDBObject updateObj = new BasicDBObject(); updateObj.put("$set", userCan); //check this!!! collection.updateOne(searchQuery, updateObj); messageBuilder.append("Done ").append(userName).append(", \n"); messageBuilder.append( "this Telegram account is no longer an e-VRE Authenticator for " + arguments[0]); } else {//the user with the provided credentials has no authenticator defined messageBuilder.append("Hi ").append(userName).append(",\n"); messageBuilder.append("something went wrong, please contact the administrator!"); } } else {//error credentials wrong messageBuilder.append("Hi ").append(userName).append("\n"); messageBuilder.append("credentials not valid!"); } } else {//error credentials wrong messageBuilder.append("Hi ").append(userName).append(",\n"); messageBuilder.append("credentials not valid!"); } mongoClient.close(); } SendMessage answer = new SendMessage(); answer.setChatId(chat.getId().toString()); answer.setText(messageBuilder.toString()); try { absSender.sendMessage(answer); } catch (TelegramApiException e) { BotLogger.error(LOGTAG, e); } }
From source file:example.Cap1BackupCode.java
public static void main(String[] args) throws IOException { String line, prev = ""; Example example = new Example(); String[] exclusions = { "100550310 - Food Technology", "100551710 - Oil and Paints Technology", "100552410 - Paper and Pulp Technology", "100552710 - Petro Chemical Engineering" }; // File file=new File("/home/sachin/Downloads/2014ENGG_Cutoff_CAP1.txt"); PdfReader reader = new PdfReader("/home/sachin/Downloads/2014ENGG_Cutoff_CAP1.pdf"); // System.out.println("This PDF has " + reader.getNumberOfPages() + " pages."); for (int i = 1; i < reader.getNumberOfPages(); i += 1) { String page = PdfTextExtractor.getTextFromPage(reader, i); InputStream is = new ByteArrayInputStream(page.getBytes()); // read it with BufferedReader BufferedReader br = new BufferedReader(new InputStreamReader(is)); int count = 1; while ((line = br.readLine()) != null) { if (count == 7) { // System.out.println("substring is"+line.substring(6)); // System.out.println("Prev college is"+example.getPrevCollege()); if (!line.substring(6).trim().equals(example.getPrevCollege())) { // System.out.println("College Name" + line); if (example.getPrevCollege() != "") { example.addObject(example.getSinglecollegedata()); }//w w w. j av a 2 s. c o m example.setPrevCollege(line.substring(6).trim()); CollegeDataObject object = new CollegeDataObject(); object.setCollegeName(line.substring(6).trim()); int temp; if ((temp = line.substring(6).trim().split(",").length) > 1) { object.setCity(line.substring(6).trim().split(",")[temp - 1].trim()); object.setCollegeName(line.substring(6).trim() .replace(line.substring(6).trim().split(",")[temp - 1].trim(), "").trim() .replace(",", "").trim()); } example.setSinglecollegedata(object); } else { } } if (count == 8) { // System.out.print("Branch name" + line); if (!line.contains("NT1") && !line.contains("NT2") && !line.contains("NT3") && !line.contains("OBC")) { if (example.getPrevBranch() != "") { example.getSinglecollegedata().AddObject(example.getCastDataObject()); CastDataObject object = new CastDataObject(); object.setBranchName(line.substring(11).trim()); example.setPrevBranch(line.substring(11).trim()); example.setCastDataObject(object); } else { CastDataObject object = new CastDataObject(); object.setBranchName(line.substring(11).trim()); example.setCastDataObject(object); example.setPrevBranch(line.substring(11).trim()); } } else { break; } } if (count == 11) { // System.out.println("open rank"+line); if (isNumeric(line.split(" ")[0])) { if (line.split(" ")[0].trim().equals(null)) line = "0"; example.getCastDataObject().setOpen(line.split(" ")[0].trim()); } } if (count == 14) { // System.out.println("sc rank is"+line); if (isNumeric(line)) { if (line.trim().equals(null)) line = "0"; example.getCastDataObject().setSc(line.trim()); } } if (count == 17) { // System.out.println("st rank is"+line); if (isNumeric(line)) { if (line.trim().equals(null)) line = "0"; example.getCastDataObject().setSt(line.trim()); } } if (count == 20) { if (isNumeric(line)) { if (line.trim().equals(null)) line = "0"; if (prev.equals("GVJO")) { // System.out.println("VJ rank is"+line); example.getCastDataObject().setVj(line.trim()); line = br.readLine(); line = br.readLine(); line = br.readLine(); count += 3; // System.out.println("NT1 rank is"+line); example.getCastDataObject().setNt1(line.trim()); } else { // System.out.println("NT1 rank is" + line); example.getCastDataObject().setNt1(line.trim()); count += 3; } } } // if (count==23) // { // System.out.println("NT1 rank is"+line); // } if (count == 26) { if (isNumeric(line)) { // System.out.println("NT2 rank is"+line); if (line.trim().equals(null)) line = "0"; example.getCastDataObject().setNt2(line.trim()); } } if (count == 29) { if (prev.equals("GNT3O")) { // System.out.println("NT3 rank is" + line); if (isNumeric(line)) { if (line.trim().equals(null)) line = "0"; example.getCastDataObject().setNt3(line.trim()); line = br.readLine(); line = br.readLine(); line = br.readLine(); // System.out.println("OBC rank is" + line); } if (isNumeric(line.split(" ")[0])) { if (line.split(" ")[0].trim().equals(null)) line = "0"; example.getCastDataObject().setOBC(line.split(" ")[0].trim()); } } else { // System.out.println("OBC rank is" + line); if (isNumeric(line.split(" ")[0])) { if (line.split(" ")[0].trim().equals(null)) line = "0"; example.getCastDataObject().setOBC(line.split(" ")[0].trim()); } } } count++; prev = line; } // if (count==7) // { // if (!line.substring(6).equals(example.getPrevCollege())) // System.out.println("College name is"+line.substring(6)); // example.setPrevCollege(line.substring(6)); // // } // if (count==8) // { // if (!line.contains("NT1") && !line.contains("NT2") && !line.contains("NT3") && !line.contains("OBC")) // System.out.println("Branch name is"+line.substring(12)); // } // count++; // System.out.println(line); } //example.getSinglecollegedata().AddObject(example.getCastDataObject()); example.getSinglecollegedata().AddObject(example.getCastDataObject()); example.addObject(example.getSinglecollegedata()); // System.out.println("Size is" + example.getObject().size()); // for (CollegeDataObject collegeDataObject :example.getObject()) { // System.out.println("College Name is " + collegeDataObject.getCollegeName()); // for (CastDataObject object : collegeDataObject.getObjects()) { // System.out.println("Branch name is " + object.getBranchName()); // // if (isNumeric(object.getOpen())) // System.out.println("Open rank is " + object.getOpen()); // // if (isNumeric(object.getSc())) // System.out.println("SC rank is " + object.getSc()); // // if (isNumeric(object.getSt())) // System.out.println("ST rank is " + object.getSt()); // // if (isNumeric(object.getVj())) // System.out.println("VJ rank is " + object.getVj()); // // if (isNumeric(object.getNt1())) // System.out.println("NT1 rank is " + object.getNt1()); // // if (isNumeric(object.getNt2())) // System.out.println("NT2 rank is " + object.getNt2()); // // if (isNumeric(object.getNt3())) // System.out.println("NT3 rank is " + object.getNt3()); // // if (isNumeric(object.getOBC())) // System.out.println("OBC rank is " + object.getOBC()); // } // } //BufferedReader reader=new Bufferef ll) //{ // System.out.println(line); //} MongoClient mongo1 = new MongoClient("localhost"); MongoDatabase db = mongo1.getDatabase("CollegeFinder"); MongoCollection<Document> coll = db.getCollection("project"); for (CollegeDataObject collegeDataObject : example.getObject()) { Document college = new Document(); college.append("college_name", collegeDataObject.getCollegeName()); college.append("city", collegeDataObject.getCity()); // System.out.println(collegeDataObject.getCollegeName() + " City "+collegeDataObject.getCity()); List<Document> branches = new ArrayList<>(); for (CastDataObject object : collegeDataObject.getObjects()) { Document branch = new Document(); branch.append("branch_name", object.getBranchName()); branch.append("open", object.getOpen()); branch.append("sc", object.getSc()); branch.append("st", object.getSt()); branch.append("vj", object.getVj()); branch.append("nt1", object.getNt1()); branch.append("nt2", object.getNt2()); branch.append("nt3", object.getNt3()); branch.append("obc", object.getOBC()); branches.add(branch); } college.append("Branch", branches); coll.insertOne(college); } // m.append("name","sachin"); // m.append("year", "first year"); // m.append("branch", "seond year"); // List <Document> list=new ArrayList<>(); // list.add(m); // Document s=new Document(); // s.append("name", "Arjun"); // s.append("year", "first year"); // s.append("branch", "seond year"); // list.add(s); // Document parent=new Document(); // parent.append("embed", list); // coll.insertOne(parent); // p // List <Document> list=new ArrayList<>(); // for (int i=0;i<10;i++) // { // list.add(new Document(m)); // } // coll.insertMany(list); // coll.insertOne(parent); // TODO code application logic here // coll.find(); }
From source file:example.Example.java
public static void main(String[] args) throws IOException { String line, prev = ""; Example example = new Example(); String[] exclusions = { "100550310 - Food Technology", "100551710 - Oil and Paints Technology", "100552410 - Paper and Pulp Technology", "100552710 - Petro Chemical Engineering" }; // File file=new File("/home/sachin/Downloads/2014ENGG_Cutoff_CAP1.txt"); PdfReader reader = new PdfReader("/home/sachin/Downloads/2014ENGG_Cutoff_CAP2.pdf"); // System.out.println("This PDF has " + reader.getNumberOfPages() + " pages."); for (int i = 1; i < reader.getNumberOfPages(); i += 1) { String page = PdfTextExtractor.getTextFromPage(reader, i); InputStream is = new ByteArrayInputStream(page.getBytes()); // read it with BufferedReader BufferedReader br = new BufferedReader(new InputStreamReader(is)); int count = 1; while ((line = br.readLine()) != null) { if (count == 7) { // System.out.println("substring is"+line.substring(6)); // System.out.println("Prev college is"+example.getPrevCollege()); if (!line.substring(6).trim().equals(example.getPrevCollege())) { // System.out.println("College Name" + line); if (example.getPrevCollege() != "") { example.addObject(example.getSinglecollegedata()); }/*from www . j a v a 2 s .com*/ example.setPrevCollege(line.substring(6).trim()); CollegeDataObject object = new CollegeDataObject(); object.setCollegeName(line.substring(6).trim()); int temp; if ((temp = line.substring(6).trim().split(",").length) > 1) { object.setCity(line.substring(6).trim().split(",")[temp - 1].trim()); object.setCollegeName(line.substring(6).trim() .replace(line.substring(6).trim().split(",")[temp - 1].trim(), "").trim() .replace(",", "").trim()); } example.setSinglecollegedata(object); } else { } } if (count == 8) { // System.out.print("Branch name" + line); if (!line.contains("NT1") && !line.contains("NT2") && !line.contains("NT3") && !line.contains("OBC")) { if (example.getPrevBranch() != "") { example.getSinglecollegedata().AddObject(example.getCastDataObject()); CastDataObject object = new CastDataObject(); object.setBranchName(line.substring(11).trim()); example.setPrevBranch(line.substring(11).trim()); example.setCastDataObject(object); } else { CastDataObject object = new CastDataObject(); object.setBranchName(line.substring(11).trim()); example.setCastDataObject(object); example.setPrevBranch(line.substring(11).trim()); } } else { break; } } if (count == 10) { // System.out.println("open rank"+line); if (line.contains("GOPENO") || line.contains("GOPENH")) { // if (isNumeric(line)) { // if (line.trim().equals(null)) // line = "0"; if (line.split(" ").length > 1) { if (isNumeric(line.split(" ")[1].trim())) example.getCastDataObject().setOpen(line.split(" ")[1].trim()); } else { line = br.readLine(); if (line.split(" ").length > 1) { if (isNumeric(line.split(" ")[1].trim())) example.getCastDataObject().setOpen(line.split(" ")[1].trim()); } else { if (isNumeric(line.trim())) example.getCastDataObject().setOpen(line.trim()); } } // } } while ((line = br.readLine()) != null) { if (line.contains("GSCO") || line.contains("GSCH")) { // if (isNumeric(line)) { // if (line.trim().equals(null)) // line = "0"; if (line.split(" ").length > 1) { if (isNumeric(line.split(" ")[1].trim())) example.getCastDataObject().setSc(line.split(" ")[1].trim()); } else { line = br.readLine(); if (line.split(" ").length > 1) { if (isNumeric(line.split(" ")[1].trim())) example.getCastDataObject().setSc(line.split(" ")[1].trim()); } else { if (isNumeric(line.trim())) example.getCastDataObject().setSc(line.trim()); } } //} } if (line.contains("GSTO") || line.contains("GSTH")) { // if (isNumeric(line)) { // if (line.trim().equals(null)) // line = "0"; if (line.split(" ").length > 1) { if (isNumeric(line.split(" ")[1].trim())) example.getCastDataObject().setSt(line.split(" ")[1].trim()); } else { line = br.readLine(); if (line.split(" ").length > 1) { if (isNumeric(line.split(" ")[1].trim())) example.getCastDataObject().setSt(line.split(" ")[1].trim()); } else { if (isNumeric(line.trim())) example.getCastDataObject().setSt(line.trim()); } } //} } if (line.contains("GVJO") || line.contains("GVJH")) { // if (isNumeric(line)) { // if (line.trim().equals(null)) // line = "0"; if (line.split(" ").length > 1) { if (isNumeric(line.split(" ")[1].trim())) example.getCastDataObject().setVj(line.split(" ")[1].trim()); } else { line = br.readLine(); if (line.split(" ").length > 1) { if (isNumeric(line.split(" ")[1].trim())) example.getCastDataObject().setVj(line.split(" ")[1].trim()); } else { if (isNumeric(line.trim())) example.getCastDataObject().setVj(line.trim()); } } //System.out.println("Line is"+line.trim()); // } } if (line.contains("GNT1O") || line.contains("GNT1H")) { // if (isNumeric(line)) { // if (line.trim().equals(null)) // line = "0"; if (line.split(" ").length > 1) { if (isNumeric(line.split(" ")[1].trim())) example.getCastDataObject().setNt1(line.split(" ")[1].trim()); } else { line = br.readLine(); if (line.split(" ").length > 1) { if (isNumeric(line.split(" ")[1].trim())) example.getCastDataObject().setNt1(line.split(" ")[1].trim()); } else { if (isNumeric(line.trim())) example.getCastDataObject().setNt1(line.trim()); } } // } } if (line.contains("GNT2O") || line.contains("GNT2H")) { // if (isNumeric(line)) { // if (line.trim().equals(null)) // line = "0"; if (line.split(" ").length > 1) { if (isNumeric(line.split(" ")[1].trim())) example.getCastDataObject().setNt2(line.split(" ")[1].trim()); } else { line = br.readLine(); if (line.split(" ").length > 1) { if (isNumeric(line.split(" ")[1].trim())) example.getCastDataObject().setNt2(line.split(" ")[1].trim()); } else { if (isNumeric(line.trim())) example.getCastDataObject().setNt2(line.trim()); } } // } } if (line.contains("GNT3O") || line.contains("GNT3H")) { // if (isNumeric(line)) { // if (line.trim().equals(null)) // line = "0"; if (line.split(" ").length > 1) { if (isNumeric(line.split(" ")[1].trim())) example.getCastDataObject().setNt3(line.split(" ")[1].trim()); } else { line = br.readLine(); if (line.split(" ").length > 1) { if (isNumeric(line.split(" ")[1].trim())) example.getCastDataObject().setNt3(line.split(" ")[1].trim()); } else { if (isNumeric(line.trim())) example.getCastDataObject().setNt3(line.trim()); } } // } } if (line.contains("GOBCO") || line.contains("GOBCH")) { // if (isNumeric(line)) { // if (line.trim().equals(null)) // line = "0"; if (line.split(" ").length > 1) { if (isNumeric(line.split(" ")[1].trim())) example.getCastDataObject().setOBC(line.split(" ")[1].trim()); } else { line = br.readLine(); if (line.split(" ").length > 1) { if (isNumeric(line.split(" ")[1].trim())) example.getCastDataObject().setOBC(line.split(" ")[1].trim()); } else { if (isNumeric(line.trim())) example.getCastDataObject().setOBC(line.trim()); } } // } } } } // if (count == 14) { // // System.out.println("sc rank is"+line); // if (isNumeric(line)) { // if (line.trim().equals(null)) // line = "0"; // example.getCastDataObject().setSc(line.trim()); // } // // // } // if (count == 17) { // // System.out.println("st rank is"+line); // if (isNumeric(line)) { // if (line.trim().equals(null)) // line = "0"; // example.getCastDataObject().setSt(line.trim()); // // } // } // if (count == 20) { // if (isNumeric(line)) { // if (line.trim().equals(null)) // line = "0"; // if (prev.equals("GVJO")) { // // System.out.println("VJ rank is"+line); // example.getCastDataObject().setVj(line.trim()); // line = br.readLine(); // line = br.readLine(); // line = br.readLine(); // count += 3; // // System.out.println("NT1 rank is"+line); // example.getCastDataObject().setNt1(line.trim()); // // } else { // // System.out.println("NT1 rank is" + line); // example.getCastDataObject().setNt1(line.trim()); // count += 3; // } // } // // } // if (count==23) // { // System.out.println("NT1 rank is"+line); // } // if (count == 26) { // // if (isNumeric(line)) { // // System.out.println("NT2 rank is"+line); // if (line.trim().equals(null)) // line="0"; // example.getCastDataObject().setNt2(line.trim()); // } // } // if (count == 29) { // // if (prev.equals("GNT3O")) { // // System.out.println("NT3 rank is" + line); // if (isNumeric(line)) { // if (line.trim().equals(null)) // line="0"; // example.getCastDataObject().setNt3(line.trim()); // line = br.readLine(); // line = br.readLine(); // line = br.readLine(); // // System.out.println("OBC rank is" + line); // } // if (isNumeric(line.split(" ")[0])) { // if (line.split(" ")[0].trim().equals(null)) // line="0"; // example.getCastDataObject().setOBC(line.split(" ")[0].trim()); // } // } else { // // System.out.println("OBC rank is" + line); // if (isNumeric(line.split(" ")[0])) { // if (line.split(" ")[0].trim().equals(null)) // line = "0"; // example.getCastDataObject().setOBC(line.split(" ")[0].trim()); // } // } // } count++; prev = line; } } // if (count==7) // { // if (!line.substring(6).equals(example.getPrevCollege())) // System.out.println("College name is"+line.substring(6)); // example.setPrevCollege(line.substring(6)); // // } // if (count==8) // { // if (!line.contains("NT1") && !line.contains("NT2") && !line.contains("NT3") && !line.contains("OBC")) // System.out.println("Branch name is"+line.substring(12)); // } // count++; // System.out.println(line); // } // } //example.getSinglecollegedata().AddObject(example.getCastDataObject()); example.getSinglecollegedata().AddObject(example.getCastDataObject()); example.addObject(example.getSinglecollegedata()); // System.out.println("Size is" + example.getObject().size()); // for (CollegeDataObject collegeDataObject :example.getObject()) { // System.out.println("College Name is " + collegeDataObject.getCollegeName()); // for (CastDataObject object : collegeDataObject.getObjects()) { // System.out.println("Branch name is " + object.getBranchName()); // // if (isNumeric(object.getOpen())) // System.out.println("Open rank is " + object.getOpen()); // // if (isNumeric(object.getSc())) // System.out.println("SC rank is " + object.getSc()); // // if (isNumeric(object.getSt())) // System.out.println("ST rank is " + object.getSt()); // // if (isNumeric(object.getVj())) // System.out.println("VJ rank is " + object.getVj()); // // if (isNumeric(object.getNt1())) // System.out.println("NT1 rank is " + object.getNt1()); // // if (isNumeric(object.getNt2())) // System.out.println("NT2 rank is " + object.getNt2()); // // if (isNumeric(object.getNt3())) // System.out.println("NT3 rank is " + object.getNt3()); // // if (isNumeric(object.getOBC())) // System.out.println("OBC rank is " + object.getOBC()); // } // } //BufferedReader reader=new Bufferef ll) //{ // System.out.println(line); //} MongoClient mongo1 = new MongoClient("localhost"); MongoDatabase db = mongo1.getDatabase("CollegeFinder"); MongoCollection<Document> coll = db.getCollection("cap_round2"); for (CollegeDataObject collegeDataObject : example.getObject()) { Document college = new Document(); college.append("college_name", collegeDataObject.getCollegeName()); college.append("city", collegeDataObject.getCity()); System.out.println(collegeDataObject.getCollegeName() + " City " + collegeDataObject.getCity()); List<Document> branches = new ArrayList<>(); for (CastDataObject object : collegeDataObject.getObjects()) { Document branch = new Document(); branch.append("branch_name", object.getBranchName()); branch.append("open", Integer.valueOf(object.getOpen())); branch.append("sc", Integer.valueOf(object.getSc())); branch.append("st", Integer.valueOf(object.getSt())); branch.append("vj", Integer.valueOf(object.getVj())); branch.append("nt1", Integer.valueOf(object.getNt1())); branch.append("nt2", Integer.valueOf(object.getNt2())); branch.append("nt3", Integer.valueOf(object.getNt3())); branch.append("obc", Integer.valueOf(object.getOBC())); branches.add(branch); } college.append("Branch", branches); coll.insertOne(college); } // m.append("name","sachin"); // m.append("year", "first year"); // m.append("branch", "seond year"); // List <Document> list=new ArrayList<>(); // list.add(m); // Document s=new Document(); // s.append("name", "Arjun"); // s.append("year", "first year"); // s.append("branch", "seond year"); // list.add(s); // Document parent=new Document(); // parent.append("embed", list); // coll.insertOne(parent); // p // List <Document> list=new ArrayList<>(); // for (int i=0;i<10;i++) // { // list.add(new Document(m)); // } // coll.insertMany(list); // coll.insertOne(parent); // TODO code application logic here // coll.find(); }
From source file:examples.tour.QuickTour.java
License:Apache License
/** * Run this main method to see the output of this quick example. * * @param args takes an optional single argument for the connection string *///from www .j a v a 2 s . co m public static void main(final String[] args) { MongoClient mongoClient; if (args.length == 0) { // connect to the local database server mongoClient = new MongoClient(); } else { mongoClient = new MongoClient(new MongoClientURI(args[0])); } // get handle to "mydb" database MongoDatabase database = mongoClient.getDatabase("mydb"); // get a handle to the "test" collection MongoCollection<Document> collection = database.getCollection("test"); // drop all the data in it collection.drop(); // make a document and insert it Document doc = new Document("name", "MongoDB").append("type", "database").append("count", 1).append("info", new Document("x", 203).append("y", 102)); collection.insertOne(doc); // get it (since it's the only one in there since we dropped the rest earlier on) Document myDoc = collection.find().first(); System.out.println(myDoc.toJson()); // now, lets add lots of little documents to the collection so we can explore queries and cursors List<Document> documents = new ArrayList<Document>(); for (int i = 0; i < 100; i++) { documents.add(new Document("i", i)); } collection.insertMany(documents); System.out.println( "total # of documents after inserting 100 small ones (should be 101) " + collection.count()); // find first myDoc = collection.find().first(); System.out.println(myDoc.toJson()); // lets get all the documents in the collection and print them out MongoCursor<Document> cursor = collection.find().iterator(); try { while (cursor.hasNext()) { System.out.println(cursor.next().toJson()); } } finally { cursor.close(); } for (Document cur : collection.find()) { System.out.println(cur.toJson()); } // now use a query to get 1 document out myDoc = collection.find(eq("i", 71)).first(); System.out.println(myDoc.toJson()); // now use a range query to get a larger subset cursor = collection.find(gt("i", 50)).iterator(); try { while (cursor.hasNext()) { System.out.println(cursor.next().toJson()); } } finally { cursor.close(); } // range query with multiple constraints cursor = collection.find(and(gt("i", 50), lte("i", 100))).iterator(); try { while (cursor.hasNext()) { System.out.println(cursor.next().toJson()); } } finally { cursor.close(); } // Query Filters myDoc = collection.find(eq("i", 71)).first(); System.out.println(myDoc.toJson()); // now use a range query to get a larger subset Block<Document> printBlock = new Block<Document>() { public void apply(final Document document) { System.out.println(document.toJson()); } }; collection.find(gt("i", 50)).forEach(printBlock); // filter where; 50 < i <= 100 collection.find(and(gt("i", 50), lte("i", 100))).forEach(printBlock); // Sorting myDoc = collection.find(exists("i")).sort(descending("i")).first(); System.out.println(myDoc.toJson()); // Projection myDoc = collection.find().projection(excludeId()).first(); System.out.println(myDoc.toJson()); // Aggregation collection .aggregate( asList(match(gt("i", 0)), project(Document.parse("{ITimes10: {$multiply: ['$i', 10]}}")))) .forEach(printBlock); myDoc = collection.aggregate(singletonList(group(null, sum("total", "$i")))).first(); System.out.println(myDoc.toJson()); // Update One collection.updateOne(eq("i", 10), set("i", 110)); // Update Many UpdateResult updateResult = collection.updateMany(lt("i", 100), inc("i", 100)); System.out.println(updateResult.getModifiedCount()); // Delete One collection.deleteOne(eq("i", 110)); // Delete Many DeleteResult deleteResult = collection.deleteMany(gte("i", 100)); System.out.println(deleteResult.getDeletedCount()); collection.drop(); // ordered bulk writes List<WriteModel<Document>> writes = new ArrayList<WriteModel<Document>>(); writes.add(new InsertOneModel<Document>(new Document("_id", 4))); writes.add(new InsertOneModel<Document>(new Document("_id", 5))); writes.add(new InsertOneModel<Document>(new Document("_id", 6))); writes.add( new UpdateOneModel<Document>(new Document("_id", 1), new Document("$set", new Document("x", 2)))); writes.add(new DeleteOneModel<Document>(new Document("_id", 2))); writes.add(new ReplaceOneModel<Document>(new Document("_id", 3), new Document("_id", 3).append("x", 4))); collection.bulkWrite(writes); collection.drop(); collection.bulkWrite(writes, new BulkWriteOptions().ordered(false)); //collection.find().forEach(printBlock); // Clean up database.drop(); // release resources mongoClient.close(); }
From source file:flipkart.mongo.node.discovery.NodeDiscovery.java
License:Apache License
/** * will connect to one of the shard in replica set and update and nodes in the replicaSet *///from ww w . j a v a 2s.c o m public ReplicaSetConfig discover() throws MongoDiscoveryException { List<Node> nodesInReplicaSet = Lists.newArrayList(); MongoClient client = MongoConnector.getMongoClient(mongoReplicaSet.getNodes()); MongoDatabase dbConnection = client.getDatabase(DB_FOR_DISCOVERY); Document replicaSetCmd = new Document("replSetGetStatus", "1"); Document replSetGetStatus = dbConnection.runCommand(replicaSetCmd); List<Document> memberDocuments = (List<Document>) replSetGetStatus.get("members"); for (Document member : memberDocuments) { Node replicaNodeWithState = getReplicaNodeWithState(member, mongoReplicaSet); nodesInReplicaSet.add(replicaNodeWithState); } ReplicaSetConfig replicaSetConfig = new ReplicaSetConfig(getShardName(replSetGetStatus), nodesInReplicaSet); logger.info("ReplicaSet found: " + replicaSetConfig); return replicaSetConfig; }