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:es.upv.dsic.elp.iJulienne.MongoDB.java

License:Open Source License

public static void saveData(String maudeInput, String maudeOutput) {
    MongoClient mongo;
    DB db;// ww w  .  j  a  v a  2  s  .c  o m

    //WARNING: Configure with your own data
    try {
        mongo = new MongoClient("YOUR_SERVER_ADDRESS", YOUR_SERVER_PORT);
    } catch (UnknownHostException e) {
        return;
    }

    db = mongo.getDB("ijulienne");
    //WARNING: Configure with your own data
    boolean auth = db.authenticate("YOUR_USER", "YOUR_PASSWORD".toCharArray());
    if (auth) {
        DBCollection table = db.getCollection("ijulienne");
        BasicDBObject document = new BasicDBObject();
        document.put("input", maudeInput);
        document.put("output", maudeOutput);
        table.insert(document);
    }
    mongo.close();
}

From source file:eu.vital.vitalcep.cep.CEP.java

public Boolean CEPStart(CEPType type, DolceSpecification dolceSpecification, String mqin, String mqout,
        String confFile, String sources, JSONObject credentials) throws FileNotFoundException, IOException {

    ConfigReader configReader = ConfigReader.getInstance();

    mongoURL = configReader.get(ConfigReader.MONGO_URL);
    mongoDB = configReader.get(ConfigReader.MONGO_DB);

    cp = new CepProcess(dolceSpecification.toString(), mqin, mqout, confFile);
    cp.startCEP();//from ww w.  j av a 2  s  .  co  m
    this.PID = cp.PID;

    CepContainer.putCepProc(cp);

    this.type = type.toString();
    String T = type.toString();

    if (cp.PID > 0) {

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

        try {

            Document doc = new Document();

            doc.put("PID", PID);
            doc.put("mqin", mqin);
            doc.put("mqout", mqout);
            doc.put("dolceSpecification", dolceSpecification.toString());
            doc.put("dolcefile", cp.cepFolder + "/" + cp.fileName);
            doc.put("cepType", T);
            doc.put("clientId", fileName);
            //doc.put("sensorId", id);
            doc.put("fileName", fileName);
            doc.put("cepFolder", cp.cepFolder);

            Date NOW = new Date();

            switch (T) {
            case "DATA":
                doc.put("data", sources);
                break;
            case "QUERY":
                doc.put("querys", sources);
                break;

            case "CEPICO":
            case "ALERT":
                doc.put("lastRequest", getXSDDateTime(NOW));
                BasicDBList sourcesCEPICO = (BasicDBList) JSON.parse(sources);
                doc.put("requests", sourcesCEPICO);
                doc.put("lastRequest", getXSDDateTime(NOW));
                doc.put("username", credentials.getString("username"));
                doc.put("password", encrypt(credentials.getString("password")));
                break;

            case "CONTINUOUS":

                BasicDBList sourcesB = (BasicDBList) JSON.parse(sources);
                BasicDBList propertiesB = (BasicDBList) JSON.parse(dolceSpecification.getEvents().toString());
                doc.put("sources", sourcesB);
                doc.put("properties", propertiesB);
                doc.put("lastRequest", getXSDDateTime(NOW));
                doc.put("username", credentials.getString("username"));
                doc.put("password", encrypt(credentials.getString("password")));
                break;
            }

            doc.put("status", "OK");
            db.getCollection("cepinstances").insertOne(doc);
            ObjectId idO = (ObjectId) doc.get("_id");
            this.id = idO.toString();

            if (id != null && !(T == "DATA" || T == "QUERY")) {
                Boolean insertIntoCollectorList = insertIntoCollectorList(doc, idO);

                if (!insertIntoCollectorList) {
                    db.getCollection("cepinstances").updateOne(doc,
                            new Document("$set", new Document("status", "no collector available")));
                    throw new ServerErrorException(500);
                }

            }

        } catch (JSONException | GeneralSecurityException | UnsupportedEncodingException
                | ServerErrorException ex) {
            String a = "";
        } finally {
            if (db != null)
                db = null;
            if (mongo != null) {
                mongo.close();
                mongo = null;
            }
        }

    } else {
        this.fileName = "";
        return false;
    }
    return true;

}

From source file:eu.vital.vitalcep.collector.Collector.java

private void getCollectorList() {
    try {/*  ww  w .j a v  a2 s. com*/
        MongoClient mongo = new MongoClient(new MongoClientURI(mongoURL));

        final MongoDatabase db = mongo.getDatabase(mongoDB);

        BasicDBObject clause1 = new BasicDBObject("cepType", "CONTINUOUS").append("status", "OK");
        BasicDBObject clause2 = new BasicDBObject("cepType", "CEPICO");
        BasicDBObject clause3 = new BasicDBObject("cepType", "ALERT");
        BasicDBList or = new BasicDBList();
        or.add(clause1);
        or.add(clause2);
        or.add(clause3);
        BasicDBObject query = new BasicDBObject("$or", or);

        FindIterable<Document> coll;
        coll = db.getCollection("cepinstances").find(query);

        coll.forEach(new Block<Document>() {
            @Override
            public void apply(final Document document) {

                JSONObject oCollector = new JSONObject();

                oCollector.put("id", document.getObjectId("_id").toString());
                oCollector.put("mqin", document.getString("mqin"));
                oCollector.put("mqout", document.getString("mqout"));
                oCollector.put("cepType", document.getString("cepType"));

                if (document.getString("cepType").equals("CONTINUOUS")) {

                    final Document doc = new Document("sources", document.get("sources"));
                    final String jsonStringSources = doc.toJson();
                    JSONObject sources = new JSONObject(jsonStringSources);

                    final Document docproperties = new Document("properties", document.get("properties"));
                    final String jsonStringproperties = docproperties.toJson();
                    JSONObject sourcesproperties = new JSONObject(jsonStringproperties);

                    oCollector.put("sources", sources.getJSONArray("sources"));
                    oCollector.put("properties", sourcesproperties.getJSONArray("properties"));
                    oCollector.put("username", document.getString("username"));
                    oCollector.put("password", document.getString("password"));

                } else {

                    final Document doc = new Document("requests", document.get("requests"));
                    final String jsonStringRequests = doc.toJson();
                    JSONObject requestsObject = new JSONObject(jsonStringRequests);

                    oCollector.put("requests", requestsObject.getJSONArray("requests"));
                    oCollector.put("username", document.getString("username"));
                    oCollector.put("password", document.getString("password"));
                }
                oCollector.put("lastRequest", document.getString("lastRequest"));
                sensors.put(oCollector);

            }
        });

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

From source file:eu.vital.vitalcep.publisher.MessageProcessor_publisher.java

@Override
public boolean processMsg(MqttMsg mqttMsg) {

    Encoder encoder = new Encoder();
    Date date = new Date();
    String xsdTime = getXSDDateTime(date);
    UUID uuid = UUID.randomUUID();
    String id = uuid.toString();//from   w  ww  .  j a  v  a  2 s  . c o  m

    JSONObject observation = null;
    try {
        observation = encoder.dolceOutput2Jsonld(mqttMsg.msg, id, this.sensorId, xsdTime);
    } catch (ParseException ex) {
        java.util.logging.Logger.getLogger(MessageProcessor_publisher.class.getName())
                .log(java.util.logging.Level.SEVERE, null, ex);
    }

    Document doc = null;
    try {
        doc = encoder.dolceOutput2Document(mqttMsg.msg, id, this.sensorId, xsdTime);
    } catch (ParseException ex) {
        java.util.logging.Logger.getLogger(MessageProcessor_publisher.class.getName())
                .log(java.util.logging.Level.SEVERE, null, ex);
    }

    logger.debug("MQTTMessage received: " + mqttMsg.msg);

    MongoClient mongo = null;
    MongoDatabase db = null;
    try {
        mongo = new MongoClient(new MongoClientURI(this.mongoURL));
        db = mongo.getDatabase(this.mongoDB);
        db.getCollection(mongocollection).insertOne(doc);
    } catch (MongoException ex) {
        logger.error("observation not saved");
    } finally {
        if (db != null)
            db = null;
        if (mongo != null)
            mongo.close();
    }

    JSONArray body = new JSONArray();
    body.put(observation);

    DMSManager oDMS = new DMSManager(dms_URL, cookie);

    try {
        if (!oDMS.pushObservations(body.toString())) {
            logger.error("couldn't push to DMS");
            return false;
        } else {
            return true;
        }
    } catch (IOException | KeyManagementException | NoSuchAlgorithmException | KeyStoreException ex) {
        logger.error(ex);
    }

    return true;

}

From source file:eu.vital.vitalcep.restApp.alert.Alerts.java

/**
 * Gets the filters.//  w w  w  .  j av a2 s.c  o  m
 *
 * @return the filters
 */
@GET
@Path("getalerts")
@Produces(MediaType.APPLICATION_JSON)
public String getAlerts() {

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

    MongoDatabase db = mongo.getDatabase(mongoDB);

    BasicDBObject query = new BasicDBObject();
    BasicDBObject fields = new BasicDBObject().append("_id", false);
    fields.append("dolceSpecification", false);

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

    final JSONArray AllJson = new JSONArray();

    coll.forEach(new Block<Document>() {
        @Override
        public void apply(final Document document) {
            AllJson.put(document);
        }
    });
    if (db != null)
        db = null;
    if (mongo != null) {
        mongo.close();
        mongo = null;
    }
    return AllJson.toString();

}

From source file:eu.vital.vitalcep.restApp.alert.Alerts.java

/**
 * Creates a filter.//from ww w  .  jav  a 2 s.c  om
 *
 * @param cepico
 * @param req
 * @return the filter id 
 * @throws java.io.IOException 
 */
@PUT
@Path("createalert")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response createAlert(String cepico, @Context HttpServletRequest req) throws IOException {

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

    JSONObject credentials = new JSONObject();

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

    JSONObject jo = new JSONObject(cepico);
    if (!jo.has("source")) {
        return Response.status(Response.Status.BAD_REQUEST).build();
    }

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

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

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

    // create an empty query
    BasicDBObject query = new BasicDBObject();
    BasicDBObject fields = new BasicDBObject().append("_id", false);
    fields.append("dolceSpecification", false);

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

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

        try {

            DolceSpecification ds = new DolceSpecification(str);

            if (ds instanceof DolceSpecification) {
                UUID uuid = UUID.randomUUID();
                String randomUUIDString = uuid.toString();

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

                Date NOW = new Date();

                JSONArray requestArray;

                try {
                    requestArray = createAlertRequests(jo.getJSONArray("source"), ds.getEvents(),
                            getXSDDateTime(NOW));
                } catch (Exception e) {
                    return Response.status(Response.Status.BAD_REQUEST)
                            .entity("not available getObservation Service for this sensor ").build();
                }

                CEP cepProcess = new CEP();

                if (!(cepProcess.CEPStart(CEP.CEPType.ALERT, ds, mqin, mqout, confFile, requestArray.toString(),
                        credentials))) {
                    return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
                }

                String clientName = cepProcess.fileName;

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

                DBObject dbObject = createAlertSensor(cepico, randomUUIDString, dsjo, cepProcess.id);

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

                try {
                    db.getCollection("alerts").insertOne(doc);

                    JSONObject opState = createOperationalStateObservation(randomUUIDString);
                    String sensorId = host + "/sensor/" + randomUUIDString;

                    MessageProcessor_publisher Publisher_MsgProcc = new MessageProcessor_publisher(this.dmsURL,
                            cookie, sensorId, "alertsobservations", mongoURL, mongoDB);//555
                    MQTT_connector_subscriper publisher = new MQTT_connector_subscriper(mqout,
                            Publisher_MsgProcc);
                    MqttConnectorContainer.addConnector(publisher.getClientName(), publisher);

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

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

                    } catch (MongoException ex) {
                        return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
                    }

                    JSONObject aOutput = new JSONObject();
                    aOutput.put("id", host + "/sensor/" + randomUUIDString);
                    return Response.status(Response.Status.OK).entity(aOutput.toString()).build();

                } catch (MongoException ex) {
                    return Response.status(Response.Status.BAD_REQUEST).build();
                }

            } else {

                return Response.status(Response.Status.BAD_REQUEST).build();
            }
        } catch (JSONException | IOException e) {
            return Response.status(Response.Status.BAD_REQUEST).build();
        }
    }

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

}

From source file:eu.vital.vitalcep.restApp.alert.Alerts.java

/**
 * Gets a filter.//  w w  w.j  a  va2s . c  om
 *
 * @return the filter 
 */
@POST
@Path("getAlert")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response getAlert(String id) {

    JSONObject jo = new JSONObject(id);
    String idjo = jo.getString("id");

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

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

    }

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

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

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

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

}

From source file:eu.vital.vitalcep.restApp.alert.Alerts.java

/**
 * Gets a filter.//from   w  w w .ja  v  a 2  s .co m
 *
 * @param filterId
 * @param req
 * @return the filter 
 */
@DELETE
@Path("deletealert")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response deleteAlert(String filterId, @Context HttpServletRequest req) throws IOException {
    MongoClient mongo = null;
    MongoDatabase db = null;

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

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

        JSONObject jo = new JSONObject(filterId);
        String idjo = jo.getString("id");

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

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

        MongoCollection<Document> coll = db.getCollection("alerts");

        Bson filter = Filters.eq("id", idjo);

        FindIterable<Document> iterable = coll.find(filter);

        String cepInstance;

        CEP cepProcess = new CEP();

        if (iterable != null && iterable.first() != null) {
            Document doc = iterable.first();
            cepInstance = doc.getString("cepinstance");

            MongoCollection<Document> collInstances = db.getCollection("cepinstances");

            ObjectId ci = new ObjectId(cepInstance);
            Bson filterInstances = Filters.eq("_id", ci);

            FindIterable<Document> iterable2 = collInstances.find(filterInstances);

            if (iterable2 != null) {
                Document doc2 = iterable2.first();
                cepProcess.PID = doc2.getInteger("PID");
                cepProcess.fileName = doc2.getString("fileName");
                cepProcess.cepFolder = doc2.getString("cepFolder");
                cepProcess.type = CEP.CEPType.ALERT.toString();
                CepProcess cp = new CepProcess(null, null, null, null);
                cp.PID = doc2.getInteger("PID");

                cepProcess.cp = cp;

                if (!cepProcess.cepDispose()) {
                    java.util.logging.Logger.getLogger(Alerts.class.getName()).log(Level.SEVERE,
                            "bcep Instance not terminated");
                } else {

                    Bson filter1 = Filters.eq("_id", ci);
                    Bson update = new Document("$set", new Document("status", "terminated"));
                    UpdateOptions options = new UpdateOptions().upsert(false);
                    UpdateResult updateDoc = db.getCollection("cepinstances").updateOne(filter1, update,
                            options);

                }
                ;
                CepContainer.deleteCepProcess(cp.PID);

            }
        } else {
            return Response.status(Response.Status.NOT_FOUND).build();
        }

        DeleteResult deleteResult = coll.deleteOne(eq("id", idjo));

        if (deleteResult.getDeletedCount() < 1) {
            return Response.status(Response.Status.NOT_FOUND).build();
        } else {
            return Response.status(Response.Status.OK).build();
        }
    } catch (Exception e) {
        return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
    } finally {
        db = null;
        if (mongo != null) {
            mongo.close();
            mongo = null;
        }
    }
}

From source file:eu.vital.vitalcep.restApp.cepRESTApi.CEPICO.java

/**
 * Gets the filters.//from   w  w  w. j ava  2  s  . c  om
 *
 * @return the filters
 */
@GET
@Path("getcepicos")
@Produces(MediaType.APPLICATION_JSON)
public Response getCEPICOs() {

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

    MongoDatabase db = mongo.getDatabase(mongoDB);

    BasicDBObject query = new BasicDBObject();
    BasicDBObject fields = new BasicDBObject().append("_id", false).append("cepinstance", false);
    fields.append("dolceSpecification", false);

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

    final JSONArray AllJson = new JSONArray();

    coll.forEach(new Block<Document>() {
        @Override
        public void apply(final Document document) {
            AllJson.put(document);
        }
    });

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

    return Response.status(Response.Status.OK).entity(AllJson.toString()).build();

}

From source file:eu.vital.vitalcep.restApp.cepRESTApi.CEPICO.java

/**
 * Creates a filter.//  w w  w  . j a v  a2 s . c  om
 *
 * @param cepico
 * @param req
 * @return the filter id 
 * @throws java.io.IOException 
 */
@PUT
@Path("createcepico")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response createCEPICO(String cepico, @Context HttpServletRequest req) throws IOException {

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

    JSONObject credentials = new JSONObject();

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

    JSONObject jo = new JSONObject(cepico);
    if (!jo.has("source")) {
        return Response.status(Response.Status.BAD_REQUEST).build();
    }

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

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

    }

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

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

        try {

            DolceSpecification ds = new DolceSpecification(str);

            if (ds instanceof DolceSpecification) {
                UUID uuid = UUID.randomUUID();
                String randomUUIDString = uuid.toString();

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

                Date NOW = new Date();

                JSONArray requestArray;

                try {
                    requestArray = createCEPICORequests(jo.getJSONArray("source"), ds.getEvents(),
                            getXSDDateTime(NOW));
                } catch (Exception e) {
                    mongo.close();
                    return Response.status(Response.Status.BAD_REQUEST)
                            .entity("not available getObservation Service for this sensor ").build();
                }

                CEP cepProcess = new CEP();

                if (!(cepProcess.CEPStart(CEP.CEPType.CEPICO, ds, mqin, mqout, confFile,
                        requestArray.toString(), credentials))) {
                    mongo.close();
                    return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
                }

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

                DBObject dbObject = createCEPSensor(cepico, randomUUIDString, dsjo, cepProcess.id);

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

                try {
                    db.getCollection("cepicos").insertOne(doc);

                    JSONObject opState = createOperationalStateObservation(randomUUIDString);

                    String sensorId = host + "/sensor/" + randomUUIDString;

                    MessageProcessor_publisher Publisher_MsgProcc = new MessageProcessor_publisher(this.dmsURL,
                            cookie, sensorId, "cepicosobservations", mongoURL, mongoDB);//555
                    MQTT_connector_subscriper publisher = new MQTT_connector_subscriper(mqout,
                            Publisher_MsgProcc);
                    MqttConnectorContainer.addConnector(publisher.getClientName(), publisher);

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

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

                    } catch (MongoException ex) {
                        mongo.close();
                        return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
                    }

                    JSONObject aOutput = new JSONObject();
                    aOutput.put("id", host + "/sensor/" + randomUUIDString);
                    return Response.status(Response.Status.OK).entity(aOutput.toString()).build();

                } catch (MongoException ex) {
                    return Response.status(Response.Status.BAD_REQUEST).build();
                }

            } else {
                mongo.close();
                return Response.status(Response.Status.BAD_REQUEST).build();
            }
        } catch (MongoException ex) {
            return Response.status(Response.Status.BAD_REQUEST).build();
        }

    } else {
        mongo.close();
        return Response.status(Response.Status.BAD_REQUEST).build();
    }

}