Example usage for com.mongodb BasicDBObject append

List of usage examples for com.mongodb BasicDBObject append

Introduction

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

Prototype

@Override
public BasicDBObject append(final String key, final Object val) 

Source Link

Document

Add a key/value pair to this object

Usage

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

/**
 * Creates a filter./*from  ww w .  j  a va2 s  . co m*/
 *
 * @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.cepRESTApi.CEPICO.java

/**
 * Gets the filters.//from   w w w . j a v  a  2  s  . co  m
 *
 * @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.filteringApi.ContinuosFiltering.java

/**
 * Gets the filters.//w  w  w.java 2  s  . c  om
 *
 * @return the filters
 */
@GET
@Path("getcontinuousfilters")
@Produces(MediaType.APPLICATION_JSON)
public Response getFilterings(@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(); 

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

    try {
        db.getCollection("continuousfilters");
    } 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();

    }

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

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

    final JSONArray AllJson = new JSONArray();

    coll.forEach(new Block<Document>() {
        @Override
        public void apply(final Document document) {
            String aux = document.toJson();
            JSONObject sensoraux = new JSONObject(aux);
            AllJson.put(sensoraux);
        }
    });
    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.filteringApi.StaticFiltering.java

/**
  * Gets the filters./*from  w w  w.  ja  v  a2  s . c o m*/
  *
  * @return the filters
  */
@GET
@Path("getstaticdatafilters")
@Produces(MediaType.APPLICATION_JSON)
public Response getStaticDataFilters(@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();

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

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

    }

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

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

    final JSONArray AllJson = new JSONArray();

    coll.forEach(new Block<Document>() {
        @Override
        public void apply(final Document document) {
            String aux = document.toJson();
            JSONObject sensoraux = new JSONObject(aux);
            AllJson.put(sensoraux);
        }
    });
    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.filteringApi.StaticFiltering.java

/**
 * Gets the filters./*from  ww  w.j  a v a 2s  .  c o  m*/
 *
 * @return the filters
 */
@GET
@Path("getstaticqueryfilters")
@Produces(MediaType.APPLICATION_JSON)
public Response getStaticQueryFilters(@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();

    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();

    }

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

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

    final JSONArray AllJson = new JSONArray();

    coll.forEach(new Block<Document>() {
        @Override
        public void apply(final Document document) {
            String aux = document.toJson();
            JSONObject sensoraux = new JSONObject(aux);
            AllJson.put(sensoraux);
        }
    });
    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.vuaippi.System.java

@POST
@Path("metadata")
@Consumes(MediaType.APPLICATION_JSON)/*from   ww w.  ja v a2s.com*/
@Produces(MediaType.APPLICATION_JSON)
public Response getSystemMetadata(String info, @Context HttpServletRequest req)
        throws FileNotFoundException, IOException {

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

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

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

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

    final JSONArray sensors = new JSONArray();

    collStaticData.forEach(new Block<Document>() {
        @Override
        public void apply(final Document document) {
            sensors.put(document.get("id"));
        }
    });

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

    collStaticQuery.forEach(new Block<Document>() {
        @Override
        public void apply(final Document document) {
            sensors.put(document.get("id"));
        }
    });

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

    collContinuous.forEach(new Block<Document>() {
        @Override
        public void apply(final Document document) {
            sensors.put(document.get("id"));
        }
    });

    BasicDBObject querycep = new BasicDBObject();
    BasicDBObject fieldscep = new BasicDBObject().append("_id", false).append("dolceSpecification", false);

    FindIterable<Document> collcepicos = db.getCollection("cepicos").find(querycep).projection(fieldscep);
    // create an empty query

    collcepicos.forEach(new Block<Document>() {
        @Override
        public void apply(final Document document) {
            sensors.put(document.get("id"));
        }
    });

    BasicDBObject queryalert = new BasicDBObject();
    BasicDBObject fieldsalert = new BasicDBObject().append("_id", false).append("dolceSpecification", false);

    FindIterable<Document> collalerts = db.getCollection("alerts").find(queryalert).projection(fieldsalert);
    // create an empty query

    collalerts.forEach(new Block<Document>() {
        @Override
        public void apply(final Document document) {
            sensors.put(document.get("id"));
        }
    });

    sensors.put(host + "/sensor/1");
    JSONObject metadata = new JSONObject();

    JSONArray services = new JSONArray();
    services.put(host + "/service/monitoring");
    services.put(host + "/service/cepicosmanagement");
    services.put(host + "/service/filtering");
    services.put(host + "/service/alertingmanagement");
    services.put(host + "/service/observation");

    metadata.put("@context", "http://vital-iot.eu/contexts/system.jsonld");
    metadata.put("id", host);
    metadata.put("type", "vital:VitalSystem");
    metadata.put("name", "CEP IoT system");
    metadata.put("description", "This is a VITAL compliant IoT system.");
    metadata.put("operator", "elisa.herrmann@atos.net");
    metadata.put("status", "vital:Running");
    metadata.put("services", services);
    //        metadata.put("sensors", sensors);
    metadata.append("sensors", sensors);

    db = null;
    if (mongo != null) {
        mongo.close();
        mongo = null;
    }
    return Response.status(Response.Status.OK).entity(metadata.toString()).build();
}

From source file:ezbake.IntentQuery.Sample.MongoDatasource.Server.MongoExternalDataSourceHandler.java

License:Apache License

/************************************************
struct TBinaryPredicate {/*from  w w w  . j av  a 2s . c  o  m*/
// Column on which the predicate is applied.
1: required TColumnDesc col
        
// Comparison operator.
2: required TComparisonOp op
        
// Value on the right side of the binary predicate.
3: required ImpalaTypes.TColumnValue value
   }
*************************************************/
private BasicDBObject BuildDBObjectFromBinaryPredicate(TBinaryPredicate p) {
    TColumnDesc col_desc = p.getCol();

    String col_name = col_desc.getName();
    TColumnType col_type = col_desc.getType();
    TPrimitiveType col_primitive_type = col_type.getType();

    TComparisonOp op = p.getOp(); // need translation
    String opString = MapOpEnumToString(op);

    TColumnValue value = p.getValue();

    BasicDBObject queryObject = new BasicDBObject();

    if (opString.isEmpty()) {
        switch (col_primitive_type) {
        case BOOLEAN:
            queryObject.append(col_name, value.boolVal);
            break;
        case TINYINT:
        case SMALLINT:
        case INT:
            queryObject.append(col_name, value.intVal);
            break;
        case BIGINT:
            queryObject.append(col_name, value.longVal);
            break;
        case FLOAT:
        case DOUBLE:
        case DECIMAL:
            queryObject.append(col_name, value.doubleVal);
            break;
        case STRING:
            queryObject.append(col_name, value.stringVal);
            break;
        default:
            break;
        }
    } else { // opString not empty
        switch (col_primitive_type) {
        case BOOLEAN:
            queryObject.append(col_name, new BasicDBObject(opString, value.boolVal));
            break;
        case TINYINT:
        case SMALLINT:
        case INT:
            queryObject.append(col_name, new BasicDBObject(opString, value.intVal));
            break;
        case BIGINT:
            queryObject.append(col_name, new BasicDBObject(opString, value.longVal));
            break;
        case FLOAT:
        case DOUBLE:
        case DECIMAL:
            queryObject.append(col_name, new BasicDBObject(opString, value.doubleVal));
            break;
        case STRING:
            queryObject.append(col_name, new BasicDBObject(opString, value.stringVal));
            break;
        default:
            break;
        }
    }

    return queryObject;
}

From source file:ezbake.services.centralPurge.helpers.EzCentralPurgeServiceHelpers.java

License:Apache License

public static BasicDBList encodeURISet(Set<Long> longSet) {
    BasicDBList basicDBList = new BasicDBList();

    for (Long uri : longSet) {
        BasicDBObject dbURI = new BasicDBObject();
        dbURI.append(URI, uri);
        basicDBList.add(dbURI);/*from www.j  a va  2 s  .  c  o m*/
    }
    return basicDBList;
}

From source file:ezbake.services.centralPurge.helpers.EzCentralPurgeServiceHelpers.java

License:Apache License

public static DBObject encodePurgeInitiationResult(PurgeInitiationResult purgeInitiationResult) {
    BasicDBList basicDBList = new BasicDBList();
    for (String uri : purgeInitiationResult.getUrisNotFound()) {
        BasicDBObject dbURI = new BasicDBObject();
        dbURI.append(URI, uri);
        basicDBList.add(dbURI);/*from  w  w w.j av  a 2s  .  co m*/
    }

    DBObject setToBePurged = encodeURISet(purgeInitiationResult.getToBePurged());

    BasicDBObjectBuilder purgeInitiationResultBuilder = BasicDBObjectBuilder.start()
            .add(PurgeId, purgeInitiationResult.getPurgeId()).add(ToBePurged, setToBePurged)
            .add(URIsNotFoundSet, basicDBList);

    return purgeInitiationResultBuilder.get();
}

From source file:ezbake.services.centralPurge.helpers.EzCentralPurgeServiceHelpers.java

License:Apache License

public static BasicDBList encodeApplicationPurgeState(ApplicationPurgeState applicationPurgeState) {
    BasicDBList basicDBList = new BasicDBList();
    Map<String, ServicePurgeState> servicePurgeStateMap = applicationPurgeState.getServicePurgestates();

    for (String serviceName : servicePurgeStateMap.keySet()) {
        BasicDBObject dbServicePurgestate = new BasicDBObject();
        dbServicePurgestate.append(ServiceName, serviceName);
        dbServicePurgestate.append(PurgeStateString,
                encodeServicePurgeState(servicePurgeStateMap.get(serviceName)));
        basicDBList.add(dbServicePurgestate);
    }/*from  ww  w. j a v a  2s  .c om*/

    return basicDBList;
}