Example usage for com.mongodb DBObject toMap

List of usage examples for com.mongodb DBObject toMap

Introduction

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

Prototype

Map toMap();

Source Link

Document

Returns a map representing this BSONObject.

Usage

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

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

    JSONObject jo = new JSONObject(info);

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

        JSONObject credentials = new JSONObject();

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

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

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

        }

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

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

            try {

                DolceSpecification ds = new DolceSpecification(str);

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

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

                CEP cepProcess = new CEP();

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

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

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

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

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

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

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

                JSONObject opState = createOperationalStateObservation(randomUUIDString);

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

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

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

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

                JSONArray aData = new JSONArray();

                try {

                    DMSManager oDMS = new DMSManager(dmsURL, cookie);

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

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

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

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

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

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

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

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

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

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

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

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

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

                sOutput = sOutput + "]";

                try {

                    DMSManager pDMS = new DMSManager(dmsURL, cookie);

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

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

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

                CepContainer.deleteCepProcess(cepProcess.PID);

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

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

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

    }

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

}

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

/**
* Gets sensors metadata .//from  w w w. j  a  va2s.c o m
*
* @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:io.leishvl.core.data.mongodb.MapKeyConverters.java

License:Apache License

/**
 * Reads a "raw" database object into a Java map, un-escapes MongoDB's unsupported characters in 
 * the map and write it back to a JSON string using Gson.
 * @param dbo - a database object//from ww w.j  av a2  s  . com
 * @return a JSON string created from the source object where the MongoDB's unsupported characters
 *         are mapped to their original values.
 */
public static String unescapeMongo(final DBObject dbo) {
    @SuppressWarnings("unchecked")
    final Map<String, Object> map = escapeMap(dbo.toMap(), KEY_UNESCAPE);
    final Type mapType = new TypeToken<Map<String, Object>>() {
    }.getType();
    return new Gson().toJson(map, mapType);
}

From source file:io.rhiot.cloudplatform.service.device.MongoDbDeviceRegistry.java

License:Apache License

private Device dbObjectToDevice(DBObject dbObject) {
    Map<String, Object> deviceMap = new HashMap<>();
    deviceMap.putAll(dbObject.toMap());
    deviceMap.put("id", dbObject.get("_id").toString());
    return objectMapper.convertValue(deviceMap, Device.class);
}

From source file:me.carbou.mathieu.tictactoe.db.DBCollection.java

License:Apache License

@SuppressWarnings("unchecked")
private Map<String, Object> postFind(Map where, DBObject obj, Function<Map, Map> transform) {
    if (obj == null)
        return null;
    Map o = transform.apply(obj.toMap());
    return (Map) convert(o, Clock.systemUTC());
}

From source file:me.yyam.mongodbutils.MongoDbOperater.java

public Map findOne(QueryInfo queryInfo) {
    DB db = mongoClient.getDB(queryInfo.dbName);
    DBCollection coll = db.getCollection(queryInfo.collName);
    DBObject record = null;
    //if (queryInfo.query != null) {
    record = coll.findOne(queryInfo.query, null, queryInfo.order);
    //} else {/*from  w  w  w . j a v  a2  s  .  co m*/
    //    record = coll.findOne();
    //}
    if (record == null) {
        return null;
    }
    return record.toMap();
}

From source file:me.yyam.mongodbutils.MongoDbOperater.java

public <T> T findOneObj(String dbName, String collName, Map queryMap, Class<T> clazz)
        throws InstantiationException, IllegalAccessException, InvocationTargetException {
    DB db = mongoClient.getDB(dbName);//from ww w.  j  a  v a 2  s. c om
    DBCollection coll = db.getCollection(collName);
    BasicDBObject query = new BasicDBObject(queryMap);
    DBObject map = coll.findOne(query);
    if (map == null) {
        return null;
    }
    T obj = clazz.newInstance();
    ConvertUtils.register(new DateConverter(null), Date.class);
    BeanUtils.populate(obj, map.toMap());
    return obj;
}

From source file:me.yyam.mongodbutils.MongoDbOperater.java

public Map findOne(String dbName, String collName, Map queryMap)
        throws InstantiationException, IllegalAccessException, InvocationTargetException {
    DB db = mongoClient.getDB(dbName);/*from   ww  w.  ja va2 s . c om*/
    DBCollection coll = db.getCollection(collName);
    BasicDBObject query = new BasicDBObject(queryMap);
    DBObject map = coll.findOne(query);
    if (map == null) {
        return null;
    }
    return map.toMap();
}

From source file:me.yyam.mongodbutils.MongoDbOperater.java

private List<Map> cursor2list(DBCursor cursor) {
    List<Map> list = new ArrayList();
    try {/* www  .  j a va 2s.c o m*/
        while (cursor.hasNext()) {
            DBObject obj = cursor.next();
            list.add(obj.toMap());
        }
    } finally {
        cursor.close();
    }
    return list;
}

From source file:mongodb.javaGroup.java

public static void displayGroup(DBObject result) {
    for (Object name : result.toMap().values()) {
        System.out.println(name);
    }/*from w  w w.ja  v a  2  s .co m*/
}