Example usage for com.mongodb MongoClient close

List of usage examples for com.mongodb MongoClient close

Introduction

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

Prototype

public void close() 

Source Link

Document

Closes all resources associated with this instance, in particular any open network connections.

Usage

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

/**
* Gets a filter./*  ww w . j  ava  2  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 w  ww  .j a v  a2s.com
 *
 * @param info
     * @param req
 * @return the filter 
 * @throws java.io.IOException 
 */
@POST
@Path("filterstaticquery")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response filterstaticquery(String info, @Context HttpServletRequest req) throws IOException {

    JSONObject jo = new JSONObject(info);

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

        JSONObject credentials = new JSONObject();

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

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

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

        }

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

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

            try {

                DolceSpecification ds = new DolceSpecification(str);

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

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

                CEP cepProcess = new CEP();

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

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

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

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

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

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

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

                JSONObject opState = createOperationalStateObservation(randomUUIDString);

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

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

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

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

                JSONArray aData = new JSONArray();

                try {

                    DMSManager oDMS = new DMSManager(dmsURL, cookie);

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

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

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

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

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

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

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

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

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

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

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

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

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

                sOutput = sOutput + "]";

                try {

                    DMSManager pDMS = new DMSManager(dmsURL, cookie);

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

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

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

                CepContainer.deleteCepProcess(cepProcess.PID);

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

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

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

    }

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

}

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

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

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

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

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

    MongoDatabase db = mongo.getDatabase(mongoDB);

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

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

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

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

}

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

@POST
@Path("stream/unsubscribe")
@Consumes(MediaType.APPLICATION_JSON)//from w  ww .  j  ava2  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  w w  .ja v a 2s.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

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  ava2s  .  c  o  m*/
            String queryS = createQuery(sensor, property, from, to);
            Object queryO = com.mongodb.util.JSON.parse(queryS);
            query = (BasicDBObject) queryO;

            Block<Document> block = new Block<Document>() {
                @Override
                public void apply(final Document document) {
                    JSONObject oCollector = new JSONObject(document.toJson());
                    oObservations.put(oCollector);

                }
            };

            db.getCollection("cepicosobservations").find(query).projection(fields(excludeId())).forEach(block);
            db.getCollection("continuosfiltersobservations").find(query).projection(fields(excludeId()))
                    .forEach(block);
            db.getCollection("alertsobservations").find(query).projection(fields(excludeId())).forEach(block);
            db.getCollection("staticdatafiltersobservations").find(query).projection(fields(excludeId()))
                    .forEach(block);
            db.getCollection("staticqueryfiltersobservations").find(query).projection(fields(excludeId()))
                    .forEach(block);

        } catch (Exception e) {
            String a = "a";
        } finally {
            db = null;
            if (mongo != null) {
                mongo.close();
                mongo = null;
            }
        }

    } else {
        try {
            Object queryO = com.mongodb.util.JSON.parse(createQuery(sensor, property, null, null));
            query = (BasicDBObject) queryO;

            Block<Document> block = new Block<Document>() {
                @Override
                public void apply(final Document document) {
                    JSONObject oCollector = new JSONObject(document.toJson());
                    oObservations.put(oCollector);

                }
            };

            BasicDBObject sortObject = new BasicDBObject().append("_id", -1);

            db.getCollection("cepicosobservations").find(query).projection(fields(excludeId())).sort(sortObject)
                    .limit(1).forEach(block);
            db.getCollection("continuosfiltersobservations").find(query).projection(fields(excludeId()))
                    .sort(sortObject).limit(1).forEach(block);
            db.getCollection("alertsobservations").find(query).projection(fields(excludeId())).sort(sortObject)
                    .limit(1).forEach(block);
            db.getCollection("staticdatafiltersobservations").find(query).projection(fields(excludeId()))
                    .sort(sortObject).limit(1).forEach(block);
            db.getCollection("staticqueryfiltersobservations").find(query).projection(fields(excludeId()))
                    .sort(sortObject).limit(1).forEach(block);

        } catch (Exception e) {
            String a = "a";
        } finally {
            db = null;
            if (mongo != null) {
                mongo.close();
                mongo = null;
            }
        }

    }

    return oObservations;

}

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

@POST
@Path("metadata")
@Consumes(MediaType.APPLICATION_JSON)/*from w  ww .j a  v  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: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 {//from w ww  . j  av a  2  s .  co  m
        MongoClient mongoClient = new MongoClient("localhost", 27017);
        MongoDatabase db = mongoClient.getDatabase("evre");
        MongoCollection<Document> collection = db.getCollection("eVREUserProfile");
        BasicDBObject searchQuery = new BasicDBObject();
        searchQuery.put("userId", arguments[0]);
        FindIterable<Document> itcursor = collection.find(searchQuery);
        //FindIterable<Document> itcursor=collection.find();
        MongoCursor<Document> cursor = itcursor.iterator();
        if (cursor.hasNext()) {

            Document userCan = cursor.next();
            String pwd = userCan.getString("password");

            Binary binS = userCan.get("salt", org.bson.types.Binary.class);
            String salt = new String(binS.getData());
            boolean validUser = false;
            if (pwd.equals(arguments[1]))
                validUser = true;

            if (salt != null && !checkEncryptedData(arguments[1], salt.getBytes()).equals(arguments[1]))
                validUser = true;

            //if(pwd.equals(arguments[1])){
            if (validUser) {

                userCan.replace("authId", chat.getId());
                BasicDBObject updateObj = new BasicDBObject();
                updateObj.put("$set", userCan);
                //check this!!!
                collection.updateOne(searchQuery, updateObj);

                messageBuilder.append("Done ").append(userName).append(",\n");
                messageBuilder.append(
                        "this Telegram account is now registered as e-VRE Authenticator for " + arguments[0]);

            } else {//error credentials wrong
                messageBuilder.append("Hi ").append(userName).append("\n");
                messageBuilder.append("credentials not valid!");
            }

        } else {//error credentials wrong
            messageBuilder.append("Hi ").append(userName).append("\n");
            messageBuilder.append("credentials not valid!");
        }
        mongoClient.close();
    }

    SendMessage answer = new SendMessage();
    answer.setChatId(chat.getId().toString());
    answer.setText(messageBuilder.toString());

    try {
        absSender.sendMessage(answer);
    } catch (TelegramApiException e) {
        BotLogger.error(LOGTAG, e);
    }

}

From source file:eu.vre4eic.evre.telegram.commands.RemoveAuthCommand.java

License:Apache License

@Override
public void execute(AbsSender absSender, User user, Chat chat, String[] arguments) {

    String userName = user.getFirstName() + " " + user.getLastName();
    StringBuilder messageBuilder = new StringBuilder();
    if (arguments.length != 2) {
        messageBuilder.append("Hi ").append(userName).append("\n");
        messageBuilder.append("please use: /remove username pwd");
    } else {//from  w  ww.j a  v  a 2s .  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()) {
            //System.out.println("################## "+cursor.next());
            Document userCan = cursor.next();
            String pwd = userCan.getString("password");
            if (pwd.equals(arguments[1])) {

                String aId = userCan.getString("authId");
                if (!aId.equals("0")) {
                    // we don't check if the chat.getId() is the same,
                    //because a user can remove this from another Telegram ID,
                    // need to check this

                    userCan.replace("authId", "0");
                    BasicDBObject updateObj = new BasicDBObject();
                    updateObj.put("$set", userCan);
                    //check this!!!
                    collection.updateOne(searchQuery, updateObj);

                    messageBuilder.append("Done ").append(userName).append(", \n");
                    messageBuilder.append(
                            "this Telegram account is no longer an e-VRE Authenticator for " + arguments[0]);
                } else {//the user with the provided credentials has no authenticator defined
                    messageBuilder.append("Hi ").append(userName).append(",\n");
                    messageBuilder.append("something went wrong, please contact the administrator!");
                }

            } else {//error credentials wrong
                messageBuilder.append("Hi ").append(userName).append("\n");
                messageBuilder.append("credentials not valid!");
            }

        } else {//error credentials wrong
            messageBuilder.append("Hi ").append(userName).append(",\n");
            messageBuilder.append("credentials not valid!");
        }
        mongoClient.close();
    }

    SendMessage answer = new SendMessage();
    answer.setChatId(chat.getId().toString());
    answer.setText(messageBuilder.toString());

    try {
        absSender.sendMessage(answer);
    } catch (TelegramApiException e) {
        BotLogger.error(LOGTAG, e);
    }
}

From source file:example.AggregationExample.java

License:Apache License

/**
 * Run this main method to see the output of this quick example.
 *
 * @param args takes no args/*ww  w.j  av  a 2s . com*/
 * @throws UnknownHostException if it cannot connect to a MongoDB instance at localhost:27017
 */
public static void main(final String[] args) throws UnknownHostException {
    // connect to the local database server
    MongoClient mongoClient = new MongoClient();

    // get handle to "mydb"
    DB db = mongoClient.getDB("mydb");

    // Authenticate - optional
    // boolean auth = db.authenticate("foo", "bar");

    // Add some sample data
    DBCollection coll = db.getCollection("aggregationExample");
    coll.insert(new BasicDBObjectBuilder().add("employee", 1).add("department", "Sales").add("amount", 71)
            .add("type", "airfare").get());
    coll.insert(new BasicDBObjectBuilder().add("employee", 2).add("department", "Engineering").add("amount", 15)
            .add("type", "airfare").get());
    coll.insert(new BasicDBObjectBuilder().add("employee", 4).add("department", "Human Resources")
            .add("amount", 5).add("type", "airfare").get());
    coll.insert(new BasicDBObjectBuilder().add("employee", 42).add("department", "Sales").add("amount", 77)
            .add("type", "airfare").get());

    // create our pipeline operations, first with the $match
    DBObject match = new BasicDBObject("$match", new BasicDBObject("type", "airfare"));

    // build the $projection operation
    DBObject fields = new BasicDBObject("department", 1);
    fields.put("amount", 1);
    fields.put("_id", 0);
    DBObject project = new BasicDBObject("$project", fields);

    // Now the $group operation
    DBObject groupFields = new BasicDBObject("_id", "$department");
    groupFields.put("average", new BasicDBObject("$avg", "$amount"));
    DBObject group = new BasicDBObject("$group", groupFields);

    // Finally the $sort operation
    DBObject sort = new BasicDBObject("$sort", new BasicDBObject("average", -1));

    // run aggregation
    List<DBObject> pipeline = Arrays.asList(match, project, group, sort);
    AggregationOutput output = coll.aggregate(pipeline);

    // Output the results
    for (DBObject result : output.results()) {
        System.out.println(result);
    }

    // Aggregation Cursor
    AggregationOptions aggregationOptions = AggregationOptions.builder().batchSize(100)
            .outputMode(AggregationOptions.OutputMode.CURSOR).allowDiskUse(true).build();

    Cursor cursor = coll.aggregate(pipeline, aggregationOptions);
    while (cursor.hasNext()) {
        System.out.println(cursor.next());
    }

    // clean up
    db.dropDatabase();
    mongoClient.close();
}