Example usage for com.mongodb DBObject containsField

List of usage examples for com.mongodb DBObject containsField

Introduction

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

Prototype

boolean containsField(String s);

Source Link

Document

Checks if this object contains a field with the given name.

Usage

From source file:eu.cassandra.server.mongo.util.MongoDBQueries.java

License:Apache License

/**
 * /*  ww w .  j ava 2s  .  co  m*/
 * @param qKey
 * @param qValue
 * @param jsonToUpdate
 * @param collection
 * @param successMsg
 * @param refColl
 * @param refKeyName
 * @param intDocKey
 * @return
 */
public DBObject updateDocument(String qKey, String qValue, String jsonToUpdate, String collection,
        String successMsg, String refColl, String refKeyName, String intDocKey, int schemaType) {
    Vector<String> keysUpdated = new Vector<String>();
    try {
        DBObject dbObject = (DBObject) JSON.parse(jsonToUpdate);
        if (dbObject.containsField("_id")) {
            dbObject.removeField("_id");
            jsonToUpdate = dbObject.toString();
        }
        new JSONValidator().isValid(jsonToUpdate, schemaType, true);
        if (intDocKey != null && refKeyName != null && dbObject.containsField(refKeyName)) {
            ensureThatRefKeysMatch(dbObject, collection, refKeyName, intDocKey, qValue);
        } else if ((refColl != null || refKeyName != null) && dbObject.get(refKeyName) != null) {
            ensureThatRefKeyExists(dbObject, refColl, refKeyName, false);
        }
        for (String key : dbObject.keySet()) {
            if (!key.equalsIgnoreCase("id")) {
                keysUpdated.add(key);
                BasicDBObject keyToUpdate;
                if (qKey.equalsIgnoreCase("_id") || qKey.endsWith(".cid")) {
                    keyToUpdate = new BasicDBObject().append(qKey, new ObjectId(qValue));
                } else {
                    keyToUpdate = new BasicDBObject().append(qKey, qValue);
                }
                String keyName = key;
                if (intDocKey != null)
                    keyName = intDocKey + "." + key;
                DBConn.getConn().getCollection(collection).update(keyToUpdate,
                        new BasicDBObject().append("$set", new BasicDBObject(keyName, dbObject.get(key))));
            }
        }
    } catch (Exception e) {
        return jSON2Rrn.createJSONError("Update Failed for " + jsonToUpdate, e);
    }
    return getEntity(null, collection, qKey, qValue, successMsg, false,
            keysUpdated.toArray(new String[keysUpdated.size()]));
}

From source file:eu.cassandra.server.mongo.util.MongoDBQueries.java

License:Apache License

/**
 * /*from   w ww.  j av a 2 s .  c o  m*/
 * @param coll
 * @param dataToInsert
 * @param successMessage
 * @param refColl
 * @param refKeyName
 * @param canBeNull
 * @param schemaType
 * @param httpHeaders
 * @return
 */
public DBObject insertData(String coll, String dataToInsert, String successMessage, String[] refColl,
        String[] refKeyName, boolean[] canBeNull, int schemaType, HttpHeaders httpHeaders) {
    DBObject data;
    try {
        data = (DBObject) JSON.parse(dataToInsert);
        if (data.containsField("_id")) {
            data.removeField("_id");
            dataToInsert = data.toString();
        }
        new JSONValidator().isValid(dataToInsert, schemaType);
        if (refColl != null && refKeyName != null) {
            for (int i = 0; i < refColl.length; i++) {
                ensureThatRefKeyExists(data, refColl[i], refKeyName[i], canBeNull[i]);
            }
        }
        if (httpHeaders == null)
            DBConn.getConn().getCollection(coll).insert(data);
        else
            DBConn.getConn(MongoDBQueries.getDbNameFromHTTPHeader(httpHeaders)).getCollection(coll)
                    .insert(data);
    } catch (com.mongodb.util.JSONParseException e) {
        return jSON2Rrn.createJSONError("Error parsing JSON input", e.getMessage());
    } catch (Exception e) {
        return jSON2Rrn.createJSONError(dataToInsert, e);
    }
    return jSON2Rrn.createJSONInsertPostMessage(successMessage, data);
}

From source file:eu.cassandra.server.mongo.util.MongoDBQueries.java

License:Apache License

/**
 * //  w  ww  .  j a  v  a 2 s .com
 * @param coll
 * @param fieldName
 * @param cid
 * @return
 */
public DBObject deleteDocumentField(String coll, String fieldName, String cid) {
    DBObject deletedField;
    try {
        deletedField = getEntity(null, coll, fieldName + ".cid", cid,
                "Simulation Parameter " + "with cid=" + cid + " removed successfully", false,
                new String[] { fieldName });
        if (!deletedField.containsField("data"))
            throw new MongoInvalidObjectId("InvalidObjectid: [" + cid + "]");
        Vector<?> data = (Vector<?>) deletedField.get("data");
        if (data.size() == 0)
            deletedField = null;
        DBObject q = new BasicDBObject(fieldName + ".cid", new ObjectId(cid));
        DBObject o = new BasicDBObject("$unset", new BasicDBObject(fieldName, 1));
        DBConn.getConn().getCollection(coll).update(q, o, false, true);
    } catch (Exception e) {
        return jSON2Rrn.createJSONError(
                "remove field db." + coll + "." + fieldName + " with cid=" + cid + "failed", e);
    }
    return jSON2Rrn.createJSONRemovePostMessage(coll + "." + fieldName + ".cid", cid, deletedField);
}

From source file:eu.cassandra.server.mongo.util.MongoDBQueries.java

License:Apache License

/**
 * //from   w w w . jav a 2  s. co m
 * @param key
 * @param data
 * @return
 * @throws MongoRefNotFoundException
 */
public String getRefKey(String key, DBObject data) throws MongoRefNotFoundException {
    if (!data.containsField(key))
        throw new MongoRefNotFoundException("RefNotFound: " + key + " not found");
    return data.get(key).toString();
}

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

/**
* Gets sensors metadata .//from   w w w .  j  av a 2s  .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.Sensor.java

/**
* Gets sensors metadata ./*from   www  .jav a  2s.c om*/
*
* @param req
* @return the metadata of the sensors 
* @throws java.io.FileNotFoundException 
*/
@POST
@Path("observation")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response getSensorsObservations(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();
    //        }

    DBObject request = (DBObject) JSON.parse(info);
    BasicDBList sensors;
    String property;

    if (!request.containsField("sensor") || !request.containsField("property")) {
        return Response.status(Response.Status.BAD_REQUEST).build();
    } else {

        try {
            sensors = (BasicDBList) request.get("sensor");
            property = (String) request.get("property");
        } catch (Exception e) {
            return Response.status(Response.Status.BAD_REQUEST).build();
        }

    }

    String sfrom = null;
    String sto = null;
    if (request.containsField("from") && request.containsField("to")) {

        if (!isDateValid((String) request.get("from")) || !isDateValid((String) request.get("to"))) {
            return Response.status(Response.Status.BAD_REQUEST).entity("wrong xsd:dateTime format").build();
        }

        try {
            sfrom = getXSDDateTimeSecure((String) request.get("from"));
            sto = getXSDDateTimeSecure((String) request.get("to"));
        } catch (ParseException e) {
            return Response.status(Response.Status.BAD_REQUEST).entity("wrong xsd:dateTime format").build();
        }

    } else if (request.containsField("from")) {

        if (!isDateValid((String) request.get("from"))) {
            return Response.status(Response.Status.BAD_REQUEST).build();
        }

        try {
            sfrom = getXSDDateTimeSecure((String) request.get("from"));
        } catch (ParseException e) {
            return Response.status(Response.Status.BAD_REQUEST).entity("wrong xsd:dateTime format").build();
        }

    }

    JSONArray observations = new JSONArray();

    if (request.containsField("from") && request.containsField("to")) {

        observations = getObservations(sensors, property, sfrom, sto);

    } else if (request.containsField("from")) {
        //now

        Date NOW = new Date();

        observations = getObservations(sensors, property, sfrom, getXSDDateTime(NOW));

    } else {

        observations = getObservations(sensors, property, null, null);

    }

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

}

From source file:firesystem.model.FireSensor.java

/**
 * Saves output every x ms based on the constant refresh rate. Saves in mongodb and uploads to server on the given server brain url.
 *///from   w w  w  . j  a  va2s . com
@Override
public void run() {
    while (true) {
        try {
            if (enabled == true) {

                //                    System.out.println(BRAIN_URL_STRING);
                //Create mongodb connection
                MongoClient mdb = new MongoClient(DatabaseConnectionPopup.getsHostName());

                DB db = mdb.getDB(DatabaseConnectionPopup.getsDbname());

                //Get relevant connections
                users = db.getCollection("users");
                temperatureCollection = db.getCollection(DatabaseConnectionPopup.getCollectionName());

                //Find my document in the users collection
                DBObject ME = findDocumentById(jsonId, users);

                //If document doesn't exist, add it to the users collection
                if (ME == null) {
                    ME = new BasicDBObject("_id", new ObjectId(jsonId));
                    users.insert(ME);
                }

                temperature = (int) (Math.random() * 100);
                humidity = (int) (Math.random() * 100);
                String mobile = "";
                String email = "";

                if (ME.containsField("mobile")) {
                    mobile = (String) ME.get("mobile");
                }
                if (ME.containsField("email")) {
                    email = (String) ME.get("email");
                }

                //Write temperature to mongodb
                temperatureCollection
                        .insert(new BasicDBObject("temperature", temperature).append("humidity", humidity));

                //Send temperature to server
                String temperatureJson = "{\"name\":\"sensor-" + number + "\",\"temperature\":" + temperature
                        + ",\"humidity\":" + humidity + ",\"mobile\":\"" + mobile + "\",\"email\":\"" + email
                        + "\"}";

                URL url = new URL(BRAIN_URL_STRING + "?temperature=" + temperatureJson + "&sensorId=" + number);

                url.openStream();
                //Hvis temperaturen er over 90 s send email og sms.
                if (temperature > 90) {
                    //Send sms
                    String message = "Room%20for%20sensor%20" + number + "%20is%20on%20fire!";
                    if (ME.containsField("mobile")) {
                        url = new URL(SMS_API_STRING + "?sMobileNumber=" + mobile + "&sMessage=" + message);

                        url.openStream();
                    }

                    //Send email
                    if (ME.containsField("email")) {
                        String subject = "FIRE";
                        url = new URL(EMAIL_API_STRING + "?email=" + email + "&subject=" + subject + "&message="
                                + message);

                        url.openStream();
                    }

                }

                mdb.close();
            }

            Thread.sleep(REFRESH_RATE);
        } catch (InterruptedException ex) {
            //
        } catch (IOException ex) {
            //
        } catch (Exception e) {
            enabled = false;
        }

    }
}

From source file:gr.forth.ics.icardea.pid.PrimKV.java

void fill_from_DBObject(DBObject o) {
    try {//from   w  w w.  j  a va  2s  .  c o m
        for (Field f : this.getClass().getDeclaredFields()) {
            String k = f.getName();
            if (!o.containsField(k))
                continue;
            //            if (List.class.isAssignableFrom(f.getType())) {
            //               
            //            }
            else if (PrimKV.class.isAssignableFrom(f.getType())) {
                PrimKV kv = (PrimKV) f.getType().newInstance();
                kv.fill_from_DBObject((DBObject) o.get(k));
                f.set(this, kv);
            } else
                f.set(this, o.get(k));
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:gr.forth.ics.icardea.pid.PrimKV.java

public static iCARDEA_Patient create_from_DBObject(DBObject o) {

    iCARDEA_Patient tr = new iCARDEA_Patient();
    for (String k : o.keySet()) {
        if ("name".equals(k))
            tr.name.fill_from_DBObject((DBObject) o.get(k));
        else if ("mothers_name".equals(k))
            tr.mothers_name.fill_from_DBObject((DBObject) o.get(k));
        else if ("addr".equals(k))
            tr.addr.fill_from_DBObject((DBObject) o.get(k));
        else if ("date_of_birth".equals(k))
            tr.date_of_birth = (String) o.get(k);
        else if ("sex".equals(k))
            tr.sex = (String) o.get(k);
        else if ("ssn".equals(k))
            tr.ssn = (String) o.get(k);
        else if ("tel_home".equals(k))
            tr.tel_home = (String) o.get(k);
        else if ("tel_work".equals(k))
            tr.tel_work = (String) o.get(k);
        else if ("drivers_lic".equals(k))
            tr.drivers_lic = (String) o.get(k);
        else if ("accnum".equals(k))
            tr.accnum = (String) o.get(k);
        else if ("ids".equals(k)) {
            for (DBObject i : (List<DBObject>) o.get(k)) {
                String ns = (String) (i.containsField("namespace") ? i.get("namespace") : null);
                String id = (String) (i.containsField("id") ? i.get("id") : null);
                tr.ids.add(new ID(ns, id));
            }/*w w  w .  j a  va2 s .co  m*/
        } else if (k.startsWith(ID_PREFIX)) {
            String ns = k.substring(ID_PREFIX.length());
            String id = (String) o.get(k);
            tr.ids.add(new ID(ns, id));
        }
    }
    return tr;
}

From source file:HAL.libraries.blackboard_client.data_classes.FieldUpdateSubscription.java

License:Open Source License

/**
 * @see rexos.HAL.libraries.blackboard_client.BasicOperationSubscription#matchesWithEntry(rexos.HAL.libraries.blackboard_client.OplogEntry)
 **//*www.ja  v a  2  s .c om*/
@Override
public boolean matchesWithEntry(OplogEntry entry) {
    if (!super.matchesWithEntry(entry)) {
        return false;
    }

    DBObject updateDoc = entry.getUpdateDocument();
    for (MongoUpdateLogOperation operator : subscribedOperations) {
        String operatorString = operator.getOperatorString();
        if (operatorString != null) {
            if (updateDoc.containsField(operator.getOperatorString())) {
                DBObject operatorObj = (DBObject) updateDoc.get(operator.getOperatorString());
                if (operatorObj.containsField(fieldName)) {
                    return true;
                }
            }
        } else if (updateDoc.containsField(fieldName)) {
            return true;
        }

    }

    return false;
}