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.csn.mongo.MongoQueries.java

License:Apache License

/**
 * //from  w w  w . jav  a  2s .co  m
 * @param edgeType
 * @return
 */
public static HashMap<String, Vector<InstallationInfo>> getInstallationsKL(int edgeType) {
    HashMap<String, Vector<InstallationInfo>> installations = new HashMap<String, Vector<InstallationInfo>>();
    DBCursor cursor = DBConn.getConn().getCollection("installations").find().limit(limit);
    Vector<InstallationInfo> instInfos = new Vector<InstallationInfo>();
    List<DBObject> insts = cursor.toArray();
    double[][] dataForKL = new double[Math.min(insts.size(), limit)][];
    cursor.close();
    for (int i = 0; i < Math.min(insts.size(), limit); i++) {
        DBObject obj = insts.get(i);
        String id = obj.get("_id").toString();
        String name = null;
        if (obj.containsField("name"))
            name = obj.get("name").toString();
        String instType = null;
        if (obj.containsField("type"))
            instType = obj.get("type").toString();
        InstallationInfo instInfo = new InstallationInfo(id, name, instType, null);
        instInfos.add(instInfo);
        DBCursor cursor2 = DBConn.getConn().getCollection("inst_results").find(new BasicDBObject("inst_id", id))
                .sort(new BasicDBObject("tick", 1));
        List<DBObject> res = cursor2.toArray();
        cursor2.close();
        double[] data1Inst = new double[res.size()];
        for (int j = 0; j < Math.min(insts.size(), limit); j++) {
            data1Inst[j] = Double.parseDouble(res.get(j).get("p").toString());
        }
        dataForKL[i] = data1Inst;
    }

    double[][] results = ConsumptionDetector.estimateKLD(dataForKL);

    for (int i = 0; i < instInfos.size(); i++) {
        instInfos.get(i).setKlValuesWithOtherInsts(results[i]);
    }
    installations.put("ALL", instInfos);

    return installations;
}

From source file:eu.cassandra.csn.mongo.MongoQueries.java

License:Apache License

/**
 * /*from w w w .j  ava  2 s  .c o m*/
 * @param edgeType
 * @param inst_id
 * @return
 */
public static HashMap<String, Vector<InstallationInfo>> getInstallations(int edgeType, String inst_id) {
    if (edgeType == KL_SIM || edgeType == KL_DISSIM) {
        return getInstallationsKL(edgeType);
    } else {
        HashMap<String, Vector<InstallationInfo>> installations = new HashMap<String, Vector<InstallationInfo>>();
        if (DBConn.getConn() != null) {
            DBCursor cursor;
            if (inst_id == null)
                cursor = DBConn.getConn().getCollection("installations").find();
            else
                cursor = DBConn.getConn().getCollection("installations")
                        .find(new BasicDBObject("_id", new ObjectId(inst_id)));
            int cc = 0;
            while (cursor.hasNext()) {
                cc++;
                if (cc == 30)
                    break;
                DBObject obj = cursor.next();
                String id = obj.get("_id").toString();
                String name = null;
                if (obj.containsField("name"))
                    name = obj.get("name").toString();
                String instType = null;
                if (obj.containsField("type"))
                    instType = obj.get("type").toString();

                InstallationInfo instInfo = new InstallationInfo(id, name, instType, null);
                String keyType = null;
                if (edgeType == INSTALLATION_TYPE) {
                    keyType = instType;
                } else if (edgeType == PERSON_TYPE) {
                    DBObject person = DBConn.getConn().getCollection("persons")
                            .findOne(new BasicDBObject("inst_id", id));
                    String personType = null;
                    if (person.containsField("type"))
                        personType = person.get("type").toString();
                    keyType = personType;
                } else if (edgeType == AVERAGE_CONSUMPTION) {
                    DBCursor res = DBConn.getConn().getCollection("inst_results")
                            .find(new BasicDBObject("inst_id", id));
                    int counter = 0;
                    double avg = 0;
                    while (res.hasNext()) {
                        counter++;
                        double p = Double.parseDouble(res.next().get("p").toString());
                        avg += p;
                    }
                    res.close();
                    avg /= counter;
                    int avgConsumType = (int) (avg / 10);
                    keyType = String.valueOf(avgConsumType);
                } else if (edgeType == PEAK_CONSUMPTION) {
                    DBCursor res = DBConn.getConn().getCollection("inst_results").find()
                            .sort(new BasicDBObject("p", -1)).limit(1);
                    double totalMax = 0;
                    while (res.hasNext()) {
                        totalMax = Double.parseDouble(res.next().get("p").toString());
                    }
                    //                  res = DBConn.getConn().getCollection("inst_results").find().sort(new BasicDBObject( "p",1)).limit(2);
                    //                  double totalMin = 0;
                    //                  while(res.hasNext()) {
                    //                     totalMin = Double.parseDouble(res.next().get("p").toString());
                    //                  }
                    //                  System.out.println(totalMax + "\t" + totalMin);

                    res = DBConn.getConn().getCollection("inst_results").find(new BasicDBObject("inst_id", id))
                            .sort(new BasicDBObject("p", -1)).limit(1);
                    double max = 0;
                    while (res.hasNext()) {
                        max = Double.parseDouble(res.next().get("p").toString());
                    }
                    res.close();
                    System.out.println(totalMax + "\t" + max);
                    int maxConsumType = (int) (max * 5 / (totalMax));
                    keyType = String.valueOf(maxConsumType);
                } else {
                    keyType = id;
                }

                if (!installations.containsKey(keyType)) {
                    Vector<InstallationInfo> v = new Vector<InstallationInfo>();
                    v.add(instInfo);
                    installations.put(keyType, v);
                    System.out.println("installations.put " + keyType);
                } else {
                    Vector<InstallationInfo> v = installations.get(keyType);
                    v.add(instInfo);
                    installations.put(keyType, v);
                    System.out.println("installations.put " + keyType);
                }
            }
            cursor.close();
        }
        return installations;
    }
}

From source file:eu.cassandra.server.mongo.csn.MongoCluster.java

License:Apache License

/**
 * /*from w ww. j a v  a 2  s  .  c o m*/
 * @param message
 * @param httpHeaders
 * @return
 */
public DBObject cluster(String message) {
    JSONtoReturn jSON2Rrn = new JSONtoReturn();
    try {
        new JSONValidator().isValid(message, JSONValidator.CLUSTER_PARAM_SCHEMA);
        DBObject params = (DBObject) JSON.parse(message);
        String graph_id = params.get("graph_id").toString();
        String run_id = null;
        String name = params.get("name").toString();
        String clusterbasedon = params.get("clusterbasedon").toString();

        DBObject r = DBConn.getConn().getCollection(MongoGraphs.COL_GRAPHS)
                .findOne(new BasicDBObject("_id", new ObjectId(graph_id)));
        if (r.containsField("run_id")) {
            run_id = r.get("run_id").toString();
        }

        String clusterBasedOn = params.get("clusterbasedon").toString();
        Integer numberOfClusters = Integer.parseInt(params.get("n").toString());
        String clusterMethod = params.get("clustermethod").toString();
        if (clusterMethod.equalsIgnoreCase("kmeans")) {
            return clusterKmeans(message, graph_id, run_id, clusterBasedOn, numberOfClusters, name,
                    clusterbasedon);
        } else if (clusterMethod.equalsIgnoreCase("hierarchical")) {
            return clusterHierarchical(message, graph_id, run_id, clusterBasedOn, numberOfClusters, name,
                    clusterbasedon);
        } else if (clusterMethod.equalsIgnoreCase("graphedgebetweenness")) {
            return clusterGraphEgdetweenness(message, graph_id, run_id, clusterBasedOn, numberOfClusters, name,
                    clusterbasedon);
        } else
            return null;
    } catch (Exception e) {
        e.printStackTrace();
        return jSON2Rrn.createJSONError(message, e);
    }
}

From source file:eu.cassandra.server.mongo.csn.MongoEdges.java

License:Apache License

/**
 * //from w  w  w  .j ava  2s. c o  m
 * @param inst1
 * @param inst2
 * @param instObjectKey
 * @param minWeight
 * @param httpHeaders
 * @return
 */
private DBObject decideIfToCreateEdge(DBObject inst1, DBObject inst2, String instObjectKey, Double minWeight) {
    //      Double v2 = Double.parseDouble(inst2.get(instObjectKey).toString());
    DBObject edge = null;
    if (instObjectKey.equalsIgnoreCase(TotalEnergyConsumption)
            || instObjectKey.equalsIgnoreCase(MaxHourlyEnergyConsumption)
            || instObjectKey.equalsIgnoreCase(MinHourlyEnergyConsumption)
            || instObjectKey.equalsIgnoreCase(AverageActivePowerPerHour)
            || instObjectKey.equalsIgnoreCase(AverageReactivePowerPerHour)
            || instObjectKey.equalsIgnoreCase(MaxReactivePowerPerHour)
            || instObjectKey.equalsIgnoreCase(MaxHourlyEnergyConsumption)
            || instObjectKey.equalsIgnoreCase(MinActivePowerPerHour)
            || instObjectKey.equalsIgnoreCase(MinReactivePowerPerHour)) {
        if (inst1.containsField(instObjectKey) && inst2.containsField(instObjectKey)) {
            Double v1 = Double.parseDouble(inst1.get(instObjectKey).toString());
            Double v2 = Double.parseDouble(inst2.get(instObjectKey).toString());
            double dif = Math.abs(v1 - v2);
            if (dif > minWeight) {
                edge = new BasicDBObject("type", instObjectKey);
                edge.put("minWeight", minWeight);
                edge.put("weight", dif);
            }
        }
    }
    return edge;
}

From source file:eu.cassandra.server.mongo.MongoCopyEntities.java

License:Apache License

private static void stripAppliances(DBObject obj) {
    if (obj.containsField("containsAppliances"))
        obj.removeField("containsAppliances");
}

From source file:eu.cassandra.server.mongo.MongoCopyEntities.java

License:Apache License

private static void alterAppliances(DBObject obj, Map<String, String> mapping) {
    if (obj.containsField("containsAppliances")) {
        BasicDBList alist = (BasicDBList) obj.get("containsAppliances");
        BasicDBList blist = new BasicDBList();
        for (int i = 0; i < alist.size(); i++) {
            String key = alist.get(i).toString();
            if (mapping.containsKey(key)) {
                String id = mapping.get(key);
                blist.add(id);//from  ww w.ja v a  2 s . c om
            }
        }
        obj.put("containsAppliances", blist);
        PrettyJSONPrinter.prettyPrint(obj);
    }
}

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

License:Apache License

/**
 * // w w  w.j a v  a  2 s  .c  o m
 * @param obj
 * @return
 */
private DBObject changeObjectIdToString(DBObject obj) {
    if (obj.containsField("_id") && (obj.get("_id") instanceof ObjectId)) {
        obj.put("_id", obj.get("_id").toString());
    }
    return obj;
}

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

License:Apache License

/**
 * /*w  ww. j av a  2s .  c om*/
 * @param dataToInsert
 * @param coll
 * @param refKeyName
 * @param schemaType
 * @return
 */
public DBObject insertNestedDocument(String dataToInsert, String coll, String refKeyName, int schemaType) {
    DBObject data;
    String _id;
    try {
        data = (DBObject) JSON.parse(dataToInsert);
        new JSONValidator().isValid(dataToInsert, schemaType);
        if (!data.containsField("cid"))
            data.put("cid", new ObjectId());
        ensureThatRefKeyExists(data, coll, refKeyName, false);
        _id = data.get(refKeyName).toString();
        DBObject q = new BasicDBObject("_id", new ObjectId(_id));
        DBObject o = new BasicDBObject().append("$set", new BasicDBObject("sim_param", data));
        DBConn.getConn().getCollection(coll).update(q, o);
    } catch (Exception e) {
        return jSON2Rrn.createJSONError(dataToInsert, e);
    }
    return jSON2Rrn.createJSONInsertPostMessage(coll + " with _id=" + _id + " updated with the following data",
            data);
}

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

License:Apache License

/**
 * /*from   w  w w .  j  a  va 2  s  .c  o  m*/
 * @param httpHeaders
 * @param collection
 * @param dbObj1
 * @param dbObj2
 * @param successMsg
 * @param sort
 * @param limit
 * @param skip
 * @param count
 * @return
 */
public DBObject executeFindQuery(HttpHeaders httpHeaders, String dbName, String collection, DBObject dbObj1,
        DBObject dbObj2, String successMsg, String sort, int limit, int skip, boolean count) {
    try {
        if (dbName == null)
            dbName = getDbNameFromHTTPHeader(httpHeaders);
        DBCursor cursorDoc = null;
        if (count) {
            BasicDBObject dbObject = new BasicDBObject();
            dbObject.put("count", DBConn.getConn(dbName).getCollection(collection).find(dbObj1).count());
            return jSON2Rrn.createJSON(dbObject, successMsg);
        } else {
            if (dbObj2 == null) {
                cursorDoc = DBConn.getConn(dbName).getCollection(collection).find(dbObj1);
            } else {
                cursorDoc = DBConn.getConn(dbName).getCollection(collection).find(dbObj1, dbObj2);
            }
        }
        if (sort != null) {
            try {
                DBObject sortObj = (DBObject) JSON.parse(sort);
                cursorDoc = cursorDoc.sort(sortObj);
            } catch (Exception e) {
                return jSON2Rrn.createJSONError("Error in filtering JSON sorting object: " + sort, e);
            }
        }
        if (skip != 0)
            cursorDoc = cursorDoc.skip(skip);
        if (limit != 0)
            cursorDoc = cursorDoc.limit(limit);

        Vector<DBObject> recordsVec = new Vector<DBObject>();
        while (cursorDoc.hasNext()) {
            DBObject obj = cursorDoc.next();

            if (collection.equalsIgnoreCase(MongoDistributions.COL_DISTRIBUTIONS)
                    && dbObj1.containsField("_id")) {
                obj = getValues(obj, httpHeaders, dbName, obj.get("_id").toString(),
                        MongoDistributions.COL_DISTRIBUTIONS);
            } else if (collection.equalsIgnoreCase(MongoConsumptionModels.COL_CONSMODELS)
                    && dbObj1.containsField("_id")) {
                obj = getValues(obj, httpHeaders, dbName, obj.get("_id").toString(),
                        MongoConsumptionModels.COL_CONSMODELS);
            } else if (collection.equalsIgnoreCase(MongoPricingPolicy.COL_PRICING)) {
                PricingPolicy pp = new PricingPolicy(obj);
                double oneKw24Cost = pp.calcOneKw24();
                obj.put("onekw24", oneKw24Cost);
            }

            if (obj.containsField("_id"))
                obj = addChildrenCounts(httpHeaders, collection, obj);
            recordsVec.add(obj);
        }
        cursorDoc.close();
        return jSON2Rrn.createJSON(recordsVec, successMsg);
    } catch (Exception e) {
        e.printStackTrace();
        return jSON2Rrn.createJSONError("MongoQueryError: Cannot execute find query for collection: "
                + collection + " with qKey=" + dbObj1 + " and qValue=" + dbObj2, e);
    }
}

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

License:Apache License

/**
 * /*from  w w w.j  av  a 2 s .co  m*/
 * @param dBObject
 * @param httpHeaders
 * @param id
 * @return
 * @throws JSONSchemaNotValidException 
 * @throws BadParameterException 
 */
private DBObject getValues(DBObject dBObject, HttpHeaders httpHeaders, String dbName, String id, String coll)
        throws JSONSchemaNotValidException, BadParameterException {
    if (dbName == null)
        dbName = getDbNameFromHTTPHeader(httpHeaders);
    if (coll.equalsIgnoreCase(MongoDistributions.COL_DISTRIBUTIONS)) {
        double values[] = null;
        if (dBObject.containsField("parameters")) {
            String type = MongoActivityModels.REF_DISTR_STARTTIME;
            if (DBConn.getConn(dbName).getCollection("act_models")
                    .findOne(new BasicDBObject("duration._id", new ObjectId(id))) != null) {
                type = MongoActivityModels.REF_DISTR_DURATION;
            } else if (DBConn.getConn(dbName).getCollection("act_models")
                    .findOne(new BasicDBObject("repeatsNrOfTime._id", new ObjectId(id))) != null) {
                type = MongoActivityModels.REF_DISTR_REPEATS;
            }
            values = new GUIDistribution(type, dBObject).getValues();
        }
        if (values == null && dBObject.containsField("values")) {
            BasicDBList t = (BasicDBList) dBObject.get("values");
            values = Utils.dblist2doubleArr(t);
        }
        if (values != null) {
            int exp = Utils.checkExp(values);
            Utils.upscale(values, exp);
            BasicDBList list = new BasicDBList();
            for (int i = 0; i < values.length; i++) {
                BasicDBObject dbObj = new BasicDBObject("x", i);
                dbObj.put("y", values[i]);
                list.add(dbObj);
            }
            dBObject.put("values", list);
            dBObject.put("exp", exp);
        }
    } else if (coll.equalsIgnoreCase(MongoConsumptionModels.COL_CONSMODELS)) {
        double pvalues[] = null;
        double qvalues[] = null;
        double ppoints[] = null;
        double qpoints[] = null;
        BasicDBList list = new BasicDBList();
        if (dBObject.containsField("pmodel")) {
            if (((DBObject) dBObject.get("pmodel")).containsField("params")) {
                GUIConsumptionModel p = new GUIConsumptionModel((DBObject) dBObject.get("pmodel"), "p");
                Double[] pvaluesConsModel = p.getValues(GUIConsumptionModel.P);
                Double[] pointsConsModel = p.getPoints(pvaluesConsModel.length);
                pvalues = new double[pvaluesConsModel.length];
                ppoints = new double[pointsConsModel.length];
                for (int i = 0; i < pvaluesConsModel.length; i++) {
                    pvalues[i] = pvaluesConsModel[i];
                    ppoints[i] = pointsConsModel[i];
                }
            }
        }
        if (dBObject.containsField("qmodel")) {
            if (((DBObject) dBObject.get("qmodel")).containsField("params")) {
                GUIConsumptionModel q = new GUIConsumptionModel((DBObject) dBObject.get("qmodel"), "q");
                Double[] qvaluesConsModel = q.getValues(GUIConsumptionModel.Q);
                Double[] pointsConsModel = q.getPoints(qvaluesConsModel.length);
                qvalues = new double[qvaluesConsModel.length];
                qpoints = new double[pointsConsModel.length];
                for (int i = 0; i < qvaluesConsModel.length; i++) {
                    qvalues[i] = qvaluesConsModel[i];
                    qpoints[i] = pointsConsModel[i];
                }
            }
        }
        if (pvalues != null && qvalues != null) {
            for (int i = 0; i < Math.min(pvalues.length, qvalues.length); i++) {
                BasicDBObject dbObj = new BasicDBObject("x", ppoints[i]);
                dbObj.put("p", pvalues[i]);
                dbObj.put("q", qvalues[i]);
                list.add(dbObj);
            }
        }
        dBObject.put("values", list);
        // Obsolete?
        //         if((pvalues == null || pvalues.length==0) && dBObject.containsField("pvalues")) {; 
        //            BasicDBList t = (BasicDBList)dBObject.get("pvalues");
        //            pvalues = Utils.dblist2doubleArr(t); 
        //         }
        //         if((qvalues == null || qvalues.length==0) && dBObject.containsField("qvalues")) {; 
        //            BasicDBList t = (BasicDBList)dBObject.get("qvalues");
        //            qvalues = Utils.dblist2doubleArr(t); 
        //         }
    }

    return dBObject;
}