Example usage for com.mongodb Block Block

List of usage examples for com.mongodb Block Block

Introduction

In this page you can find the example usage for com.mongodb Block Block.

Prototype

Block

Source Link

Usage

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

/**
* Gets sensors status .// ww  w . j  a  va2 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 {//from www.j av a  2 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)//  w w  w .  j av a 2s. 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: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   w  w  w.ja va2  s .c  o  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:gridfs.GridFSTour.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
 * @throws FileNotFoundException if the sample file cannot be found
 * @throws IOException if there was an exception closing an input stream
 *///ww  w . j  av  a  2  s .co m
public static void main(final String[] args) throws FileNotFoundException, IOException {
    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");
    database.drop();

    GridFSBucket gridFSBucket = GridFSBuckets.create(database);

    /*
     * UploadFromStream Example
     */
    // Get the input stream
    InputStream streamToUploadFrom = new ByteArrayInputStream("Hello World".getBytes(StandardCharsets.UTF_8));

    // Create some custom options
    GridFSUploadOptions options = new GridFSUploadOptions().chunkSizeBytes(1024)
            .metadata(new Document("type", "presentation"));

    ObjectId fileId = gridFSBucket.uploadFromStream("mongodb-tutorial", streamToUploadFrom, options);
    streamToUploadFrom.close();
    System.out.println("The fileId of the uploaded file is: " + fileId.toHexString());

    /*
     * OpenUploadStream Example
     */

    // Get some data to write
    byte[] data = "Data to upload into GridFS".getBytes(StandardCharsets.UTF_8);

    GridFSUploadStream uploadStream = gridFSBucket.openUploadStream("sampleData");
    uploadStream.write(data);
    uploadStream.close();
    System.out.println("The fileId of the uploaded file is: " + uploadStream.getFileId().toHexString());

    /*
     * Find documents
     */
    gridFSBucket.find().forEach(new Block<GridFSFile>() {
        @Override
        public void apply(final GridFSFile gridFSFile) {
            System.out.println(gridFSFile.getFilename());
        }
    });

    /*
     * Find documents with a filter
     */
    gridFSBucket.find(eq("metadata.contentType", "image/png")).forEach(new Block<GridFSFile>() {
        @Override
        public void apply(final GridFSFile gridFSFile) {
            System.out.println(gridFSFile.getFilename());
        }
    });

    /*
     * DownloadToStream
     */
    FileOutputStream streamToDownloadTo = new FileOutputStream("/tmp/mongodb-tutorial.txt");
    gridFSBucket.downloadToStream(fileId, streamToDownloadTo);
    streamToDownloadTo.close();

    /*
     * DownloadToStreamByName
     */
    streamToDownloadTo = new FileOutputStream("/tmp/mongodb-tutorial.txt");
    GridFSDownloadByNameOptions downloadOptions = new GridFSDownloadByNameOptions().revision(0);
    gridFSBucket.downloadToStreamByName("mongodb-tutorial", streamToDownloadTo, downloadOptions);
    streamToDownloadTo.close();

    /*
     * OpenDownloadStream
     */
    GridFSDownloadStream downloadStream = gridFSBucket.openDownloadStream(fileId);
    int fileLength = (int) downloadStream.getGridFSFile().getLength();
    byte[] bytesToWriteTo = new byte[fileLength];
    downloadStream.read(bytesToWriteTo);
    downloadStream.close();

    System.out.println(new String(bytesToWriteTo, StandardCharsets.UTF_8));

    /*
     * OpenDownloadStreamByName
     */

    downloadStream = gridFSBucket.openDownloadStreamByName("sampleData");
    fileLength = (int) downloadStream.getGridFSFile().getLength();
    bytesToWriteTo = new byte[fileLength];
    downloadStream.read(bytesToWriteTo);
    downloadStream.close();

    System.out.println(new String(bytesToWriteTo, StandardCharsets.UTF_8));

    /*
     * Rename
     */
    gridFSBucket.rename(fileId, "mongodbTutorial");

    /*
     * Delete
     */
    gridFSBucket.delete(fileId);

    database.drop();
}

From source file:helpers.Canton.java

public static Canton getCantonByName(String name) {
    Canton obj = new Canton();

    MongoManager mongo = MongoManager.getInstance();

    FindIterable<Document> iterable = mongo.db.getCollection("canton").find(new Document("nombre", name));

    iterable.forEach(new Block<Document>() {
        @Override//from w  w  w .java 2  s  .  co m
        public void apply(final Document document) {

            obj.id = (ObjectId) document.get("_id");
            obj.idProvincia = (ObjectId) document.get("idprovincia");
            obj.nombre = document.get("nombre").toString();

            obj.leyendaProvincia = Provincia.getProvinciaById(obj.idProvincia).nombre;
            obj.leyendaPais = Pais.getPaisById(Provincia.getProvinciaById(obj.idProvincia).idPais).nombre;
        }

    });

    return obj;
}

From source file:helpers.Canton.java

public static Canton getCantonById(ObjectId id) {
    Canton obj = new Canton();

    MongoManager mongo = MongoManager.getInstance();

    FindIterable<Document> iterable = mongo.db.getCollection("canton").find(new Document("_id", id));

    iterable.forEach(new Block<Document>() {
        @Override/*  w w w.j av  a2  s. co m*/
        public void apply(final Document document) {

            obj.id = (ObjectId) document.get("_id");
            obj.idProvincia = (ObjectId) document.get("idprovincia");
            obj.nombre = document.get("nombre").toString();

            obj.leyendaProvincia = Provincia.getProvinciaById(obj.idProvincia).nombre;
            obj.leyendaPais = Pais.getPaisById(Provincia.getProvinciaById(obj.idProvincia).idPais).nombre;
        }

    });

    return obj;
}

From source file:helpers.Canton.java

public static List<Canton> getAllCanton() {
    List<Canton> res = new ArrayList<>();

    MongoManager mongo = MongoManager.getInstance();
    FindIterable<Document> iterable = mongo.db.getCollection("canton").find();
    iterable.forEach(new Block<Document>() {
        @Override//from w w  w .j a v  a  2 s . c o m
        public void apply(final Document document) {
            Canton obj = new Canton();
            obj.id = (ObjectId) document.get("_id");
            obj.idProvincia = (ObjectId) document.get("idprovincia");
            obj.nombre = document.get("nombre").toString();

            obj.leyendaProvincia = Provincia.getProvinciaById(obj.idProvincia).nombre;
            obj.leyendaPais = Pais.getPaisById(Provincia.getProvinciaById(obj.idProvincia).idPais).nombre;

            res.add(obj);
        }

    });

    return res;
}

From source file:helpers.Canton.java

public static List<Canton> getAllCantonByProvincia(ObjectId id) {
    List<Canton> res = new ArrayList<>();

    MongoManager mongo = MongoManager.getInstance();
    FindIterable<Document> iterable = mongo.db.getCollection("canton").find(new Document("idprovincia", id));
    iterable.forEach(new Block<Document>() {
        @Override// w  w  w .ja va  2s  .c  o  m
        public void apply(final Document document) {
            Canton obj = new Canton();
            obj.id = (ObjectId) document.get("_id");
            obj.idProvincia = (ObjectId) document.get("idprovincia");
            obj.nombre = document.get("nombre").toString();

            obj.leyendaProvincia = Provincia.getProvinciaById(obj.idProvincia).nombre;
            obj.leyendaPais = Pais.getPaisById(Provincia.getProvinciaById(obj.idProvincia).idPais).nombre;

            res.add(obj);
        }

    });

    return res;
}

From source file:helpers.Pais.java

public static Pais getPaisByName(String name) {
    Pais obj = new Pais();

    MongoManager mongo = MongoManager.getInstance();

    FindIterable<Document> iterable = mongo.db.getCollection("pais").find(new Document("nombre", name));

    iterable.forEach(new Block<Document>() {
        @Override/*from  ww w .java  2s . co  m*/
        public void apply(final Document document) {

            obj.id = (ObjectId) document.get("_id");
            obj.nombre = document.get("nombre").toString();
        }

    });

    return obj;
}