Example usage for com.mongodb.client MongoDatabase getCollection

List of usage examples for com.mongodb.client MongoDatabase getCollection

Introduction

In this page you can find the example usage for com.mongodb.client MongoDatabase getCollection.

Prototype

MongoCollection<Document> getCollection(String collectionName);

Source Link

Document

Gets a collection.

Usage

From source file:eu.vital.vitalcep.restApp.filteringApi.StaticFiltering.java

/**
* Gets a filter.//  w  w  w.j a v a2  s  . c om
*
* @param filterId
* @param req
* @return the filter 
*/
@POST
@Path("getstaticdatafilter")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response getstaticdatafilter(String filterId, @Context HttpServletRequest req) {

    StringBuilder ck = new StringBuilder();
    Security slogin = new Security();

    Boolean token = slogin.login(req.getHeader("name"), req.getHeader("password"), false, ck);
    if (!token) {
        return Response.status(Response.Status.UNAUTHORIZED).build();
    }
    this.cookie = ck.toString();
    JSONObject jo = new JSONObject(filterId);
    String idjo = jo.getString("id");

    MongoClient mongo = new MongoClient(new MongoClientURI(mongoURL));
    MongoDatabase db = mongo.getDatabase(mongoDB);

    try {
        db.getCollection("staticdatafilters");
    } catch (Exception e) {
        //System.out.println("Mongo is down");
        db = null;
        if (mongo != null) {
            mongo.close();
            mongo = null;
        }
        return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
    }

    BasicDBObject searchById = new BasicDBObject("id", idjo);
    String found;
    BasicDBObject fields = new BasicDBObject().append("_id", false).append("cepinstance", false);

    FindIterable<Document> coll = db.getCollection("staticdatafilters").find(searchById).projection(fields);

    try {
        found = coll.first().toJson();
        db = null;
        if (mongo != null) {
            mongo.close();
            mongo = null;
        }
    } catch (Exception e) {
        db = null;
        if (mongo != null) {
            mongo.close();
            mongo = null;
        }
        return Response.status(Response.Status.NOT_FOUND).build();
    }

    if (found == null) {
        return Response.status(Response.Status.NOT_FOUND).build();
    } else {
        return Response.status(Response.Status.OK).entity(found).build();
    }

}

From source file:eu.vital.vitalcep.restApp.filteringApi.StaticFiltering.java

/**
* Gets a filter.//from w  ww  .j  a  v  a2  s .c om
*
* @param filterId
* @param req
* @return the filter 
*/
@POST
@Path("getstaticqueryfilter")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response getstaticqueryfilter(String filterId, @Context HttpServletRequest req) {

    StringBuilder ck = new StringBuilder();
    Security slogin = new Security();

    Boolean token = slogin.login(req.getHeader("name"), req.getHeader("password"), false, ck);
    if (!token) {
        return Response.status(Response.Status.UNAUTHORIZED).build();
    }
    this.cookie = ck.toString();
    JSONObject jo = new JSONObject(filterId);
    String idjo = jo.getString("id");

    MongoClient mongo = new MongoClient(new MongoClientURI(mongoURL));
    MongoDatabase db = mongo.getDatabase(mongoDB);

    try {
        db.getCollection("staticqueryfilters");
    } catch (Exception e) {
        //System.out.println("Mongo is down");
        db = null;
        if (mongo != null) {
            mongo.close();
            mongo = null;
        }
        return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
    }

    BasicDBObject searchById = new BasicDBObject("id", idjo);
    String found;
    BasicDBObject fields = new BasicDBObject().append("_id", false).append("cepinstance", false);

    FindIterable<Document> coll = db.getCollection("staticqueryfilters").find(searchById).projection(fields);

    try {
        found = coll.first().toJson();
        db = null;
        if (mongo != null) {
            mongo.close();
            mongo = null;
        }
    } catch (Exception e) {
        return Response.status(Response.Status.NOT_FOUND).build();
    }

    if (found == null) {
        return Response.status(Response.Status.NOT_FOUND).build();
    } else {
        return Response.status(Response.Status.OK).entity(found).build();
    }

}

From source file:eu.vital.vitalcep.restApp.filteringApi.StaticFiltering.java

/**
 * Gets a filter.//from  ww w.  jav a  2s.  c  om
 *
 * @param info
     * @param req
 * @return the filter 
 * @throws java.io.IOException 
 */
@POST
@Path("filterstaticquery")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response filterstaticquery(String info, @Context HttpServletRequest req) throws IOException {

    JSONObject jo = new JSONObject(info);

    if (jo.has("dolceSpecification") && jo.has("query")) {
        // && jo.has("data") for demo
        StringBuilder ck = new StringBuilder();
        Security slogin = new Security();

        JSONObject credentials = new JSONObject();

        Boolean token = slogin.login(req.getHeader("name"), req.getHeader("password"), false, ck);
        credentials.put("username", req.getHeader("name"));
        credentials.put("password", req.getHeader("password"));
        if (!token) {
            return Response.status(Response.Status.UNAUTHORIZED).build();
        }
        this.cookie = ck.toString();

        MongoClient mongo = new MongoClient(new MongoClientURI(mongoURL));
        MongoDatabase db = mongo.getDatabase(mongoDB);

        try {
            db.getCollection("staticqueryfilters");
        } catch (Exception e) {
            //System.out.println("Mongo is down");
            db = null;
            if (mongo != null) {
                mongo.close();
                mongo = null;
            }
            return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();

        }

        if (jo.has("dolceSpecification")) {

            //Filter oFilter = new Filter(filter);
            JSONObject dsjo = jo.getJSONObject("dolceSpecification");
            String str = dsjo.toString();//"{\"dolceSpecification\": "+ dsjo.toString()+"}";

            try {

                DolceSpecification ds = new DolceSpecification(str);

                if (!(ds instanceof DolceSpecification)) {
                    return Response.status(Response.Status.BAD_REQUEST).build();
                }

                String mqin = RandomStringUtils.randomAlphanumeric(8);
                String mqout = RandomStringUtils.randomAlphanumeric(8);

                CEP cepProcess = new CEP();

                if (!(cepProcess.CEPStart(CEP.CEPType.QUERY, ds, mqin, mqout, confFile, jo.getString("query"),
                        null))) {
                    return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
                }

                String clientName = "collector_" + RandomStringUtils.randomAlphanumeric(4);

                if (cepProcess.PID < 1) {
                    return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
                }

                UUID uuid = UUID.randomUUID();
                String randomUUIDString = uuid.toString();

                DBObject dbObject = createCEPFilterStaticSensorJsonld(info, randomUUIDString, jo, dsjo,
                        "vital:CEPFilterStaticQuerySensor");
                Document doc = new Document(dbObject.toMap());

                try {
                    db.getCollection("staticqueryfilters").insertOne(doc);
                    String id = doc.get("_id").toString();

                } catch (MongoException ex) {
                    db = null;
                    if (mongo != null) {
                        mongo.close();
                        mongo = null;
                    }
                    return Response.status(Response.Status.BAD_REQUEST).build();
                }

                JSONObject opState = createOperationalStateObservation(randomUUIDString);

                DBObject oPut = (DBObject) JSON.parse(opState.toString());
                Document doc1 = new Document(oPut.toMap());

                try {
                    db.getCollection("staticqueryfiltersobservations").insertOne(doc1);
                    String id = doc1.get("_id").toString();

                } catch (MongoException ex) {
                    db = null;
                    if (mongo != null) {
                        mongo.close();
                        mongo = null;
                    }
                    return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
                }

                /////////////////////////////////////////////////////
                // creates client and messages process
                //
                MqttAllInOne oMqtt = new MqttAllInOne();
                TMessageProc MsgProcc = new TMessageProc();

                JSONArray aData = new JSONArray();

                try {

                    DMSManager oDMS = new DMSManager(dmsURL, cookie);

                    aData = oDMS.getObservations(jo.getString("query"));

                    if (aData.length() < 1) {
                        CepContainer.deleteCepProcess(cepProcess.PID);

                        if (!cepProcess.cepDispose()) {
                            java.util.logging.Logger.getLogger(StaticFiltering.class.getName())
                                    .log(Level.SEVERE, "bcep Instance not terminated");
                        }
                        ;
                        db = null;
                        if (mongo != null) {
                            mongo.close();
                            mongo = null;
                        }
                        return Response.status(Response.Status.BAD_REQUEST).entity("no data to be filtered")
                                .build();
                    }

                } catch (KeyManagementException | KeyStoreException ex) {
                    java.util.logging.Logger.getLogger(StaticFiltering.class.getName()).log(Level.SEVERE, null,
                            ex);
                }

                //DMSManager oDMS = new DMSManager(dmsURL,req.getHeader("vitalAccessToken"));

                /////////////////////////////////////////////////////////////////////////
                // PREPARING DOLCE INPUT
                Decoder decoder = new Decoder();
                ArrayList<String> simpleEventAL = decoder.JsonldArray2DolceInput(aData);

                /////////////////////////////////////////////////////////////////////////////
                // SENDING TO MOSQUITTO
                oMqtt.sendMsg(MsgProcc, clientName, simpleEventAL, mqin, mqout, false);

                /////////////////////////////////////////////////////////////////////////////
                //RECEIVING FROM MOSQUITO
                ArrayList<MqttMsg> mesagges = MsgProcc.getMsgs();

                //FORMATTING OBSERVATIONS OUTPUT
                Encoder encoder = new Encoder();

                ArrayList<Document> outputL;
                outputL = new ArrayList<>();

                outputL = encoder.dolceOutputList2ListDBObject(mesagges, host, randomUUIDString);

                String sOutput = "[";
                for (int i = 0; i < outputL.size(); i++) {
                    Document element = outputL.get(i);

                    if (i == 0) {
                        sOutput = sOutput + element.toJson();
                    }
                    sOutput = sOutput + "," + element.toJson();
                }

                sOutput = sOutput + "]";

                try {

                    DMSManager pDMS = new DMSManager(dmsURL, cookie);

                    MongoCollection<Document> collection = db.getCollection("staticqueryfiltersobservations");

                    if (outputL.size() > 0) {
                        collection.insertMany(outputL);
                        if (!pDMS.pushObservations(sOutput)) {
                            java.util.logging.Logger.getLogger(StaticFiltering.class.getName())
                                    .log(Level.SEVERE, "coudn't save to the DMS");
                        }
                    }

                } catch (IOException | KeyManagementException | NoSuchAlgorithmException
                        | KeyStoreException ex) {
                    db = null;
                    if (mongo != null) {
                        mongo.close();
                        mongo = null;
                    }
                    java.util.logging.Logger.getLogger(StaticFiltering.class.getName()).log(Level.SEVERE, null,
                            ex);
                }

                CepContainer.deleteCepProcess(cepProcess.PID);

                if (!cepProcess.cepDispose()) {
                    java.util.logging.Logger.getLogger(StaticFiltering.class.getName()).log(Level.SEVERE,
                            "bcep Instance not terminated");
                }
                ;
                db = null;
                if (mongo != null) {
                    mongo.close();
                    mongo = null;
                }
                return Response.status(Response.Status.OK).entity(sOutput).build();

            } catch (IOException | JSONException | NoSuchAlgorithmException | java.text.ParseException e) {
                db = null;
                if (mongo != null) {
                    mongo.close();
                    mongo = null;
                }
                return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
            }
        }

        return Response.status(Response.Status.BAD_REQUEST).build();

    }

    return Response.status(Response.Status.BAD_REQUEST).build();

}

From source file:eu.vital.vitalcep.restApp.vuaippi.Observation.java

/**
* Gets sensors metadata .//from   w  w w . j a v a2s  . com
*
* @return the metadata of the sensors 
* @throws java.io.FileNotFoundException 
*/
@POST
@Path("stream/subscribe")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response subscribeToObservations(String info, @Context HttpServletRequest req)
        throws FileNotFoundException, IOException {

    StringBuilder ck = new StringBuilder();
    Security slogin = new Security();

    Boolean token = slogin.login(req.getHeader("name"), req.getHeader("password"), false, ck);
    if (!token) {
        return Response.status(Response.Status.UNAUTHORIZED).build();
    }

    MongoClient mongo = new MongoClient(new MongoClientURI(mongoURL));

    MongoDatabase db = mongo.getDatabase(mongoDB);

    DBObject dbObject = (DBObject) JSON.parse(info);

    if (!dbObject.containsField("sensor")) {
        return Response.status(Response.Status.BAD_REQUEST).build();
    }
    if (!dbObject.containsField("property")) {
        return Response.status(Response.Status.BAD_REQUEST).build();
    }
    if (!dbObject.containsField("url")) {
        return Response.status(Response.Status.BAD_REQUEST).build();
    }

    Document doc = new Document(dbObject.toMap());

    try {
        db.getCollection("subscriptions").insertOne(doc);
        String id = doc.get("_id").toString();
        return Response.status(Response.Status.OK).entity("{\"subscription\":\"" + id + "\"}").build();
    } catch (MongoException ex) {
        return Response.status(Response.Status.BAD_REQUEST).build();
    } finally {
        db = null;
        if (mongo != null) {
            mongo.close();
            mongo = null;
        }
    }

}

From source file:eu.vital.vitalcep.restApp.vuaippi.Observation.java

@POST
@Path("stream/unsubscribe")
@Consumes(MediaType.APPLICATION_JSON)//from   w w w  .  j av a2 s.c  o m
@Produces(MediaType.APPLICATION_JSON)
public Response unSubscribeToObservations(String info, @Context HttpServletRequest req)
        throws FileNotFoundException, IOException {
    JSONObject jObject = new JSONObject();
    try {
        jObject = new JSONObject(info);
        if (!jObject.has("subscription")) {
            return Response.status(Response.Status.BAD_REQUEST).build();
        }

    } catch (Exception e) {
        return Response.status(Response.Status.BAD_REQUEST).build();
    }

    StringBuilder ck = new StringBuilder();
    Security slogin = new Security();

    Boolean token = slogin.login(req.getHeader("name"), req.getHeader("password"), false, ck);
    if (!token) {
        return Response.status(Response.Status.UNAUTHORIZED).build();
    }

    MongoClient mongo = new MongoClient(new MongoClientURI(mongoURL));

    MongoDatabase db = mongo.getDatabase(mongoDB);

    Document doc = new Document("_id", new ObjectId(jObject.getString("subscription")));

    DeleteResult deleted = db.getCollection("subscriptions").deleteOne(doc);

    db = null;
    if (mongo != null) {
        mongo.close();
        mongo = null;
    }

    if (deleted.wasAcknowledged() != true || deleted.getDeletedCount() != 1) {
        return Response.status(Response.Status.NOT_FOUND).build();
    }

    return Response.status(Response.Status.OK).build();
}

From source file:eu.vital.vitalcep.restApp.vuaippi.Sensor.java

/**
* Gets sensors metadata .//from  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 ./*  w  w w.  ja  v  a2s  .  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  w  w.  j a  v  a2  s  .c om*/
            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 w w  .  j  a v  a  2s.com
@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  ava  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);
    }

}