Example usage for com.mongodb BasicDBObject get

List of usage examples for com.mongodb BasicDBObject get

Introduction

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

Prototype

public Object get(final String key) 

Source Link

Document

Gets a value from this object

Usage

From source file:it.wami.map.mongodeploy.thread.WayRunnable.java

License:Apache License

/**
 * //from w w w.  ja  v a 2s  .  c  o  m
 * @param cursor {@link Cursor} the cursor of the response from the server
 * @param way {@link Way} the way object
 * @param nodes {@link BasicBSONList} the list containings the way's nodes
 * @return
 */
private Way updateWay(DBCursor cursor, Way way, BasicBSONList nodes) {
    boolean isCircularId = nodes.get(0) == nodes.get(nodes.size() - 1);
    double[][] coords = new double[nodes.size()][2];
    BasicDBObject loc;
    if (way.containsField("loc")) {
        loc = (BasicDBObject) way.get("loc");
    } else {
        loc = new BasicDBObject();
    }
    // for better performance
    List<DBObject> list = new ArrayList<DBObject>();
    while (cursor.hasNext()) {
        list.add(cursor.next());
    }
    cursor.close();
    // worst code ever n^2. for order the list as nodes
    int i = 0;
    for (Object nodeID : nodes) {// array to match to
        for (DBObject node : list) {// array being matched
            if (node != null && node.get("_id").equals(nodeID)) {
                BasicDBObject nodeLoc = (BasicDBObject) node.get("loc");
                BasicBSONList coordinates = (BasicBSONList) nodeLoc.get("coordinates");
                coords[i] = new double[] { (Double) coordinates.get(0), (Double) coordinates.get(1) };
                i++;
            }
        }
    }
    // if the lat and the lng are the same
    boolean isCircularLtLng = (coords[0][0] == coords[coords.length - 1][0])
            && (coords[0][1] == coords[coords.length - 1][1]);

    way.append("loc", loc);
    // fix
    if (isCircularId || isCircularLtLng) {
        if (coords.length > 3) {
            loc.append("type", "Polygon");
            double[][][] o = new double[1][][];
            o[0] = coords;
            loc.append("coordinates", o);
        } else {
            coords = Arrays.copyOf(coords, coords.length - 1);
            if (coords.length < 2) {
                way.remove("loc");
            } else {
                loc.append("type", "LineString");
                loc.append("coordinates", coords);
            }
        }
    } else {
        loc.append("type", "LineString");
        loc.append("coordinates", coords);
    }
    return way;
}

From source file:kiaanfx.Kiaanfx.java

private static void getBuy() {
    try {//from   w  w  w  .  j a v  a 2  s.  c o  m
        MongoClient mongoClient = new MongoClient("localhost", 27017);
        DB db = mongoClient.getDB("kiaan");
        DBCollection coll = db.getCollection("buy");
        //aggregate
        DBObject unwind = new BasicDBObject("$unwind", "$items");
        //$group            
        DBObject group_id = new BasicDBObject("_id", "$_id");
        group_id.put("num", "$num");
        group_id.put("person_id", "$person_id");
        group_id.put("discount", "$discount");
        group_id.put("increase", "$increase");
        //$group -> $multiply
        BasicDBList args = new BasicDBList();
        args.add("$items.value");
        args.add("$items.price");
        DBObject multiply = new BasicDBObject("$multiply", args);
        //$group -> $sum
        //            DBObject group_sum = new BasicDBObject("$sum", multiply);
        DBObject group_field = new BasicDBObject();
        group_field.put("_id", group_id);
        group_field.put("total", new BasicDBObject("$sum", multiply));
        DBObject group = new BasicDBObject("$group", group_field);
        //$project
        DBObject project_field = new BasicDBObject("_id", "$_id._id");
        project_field.put("person_id", "$_id.person_id");
        project_field.put("num", "$_id.num");
        BasicDBList arr = new BasicDBList();
        arr.add("$total");
        arr.add("$_id.discount");
        arr.add("$_id.increase");
        DBObject field_add = new BasicDBObject("$add", arr);
        project_field.put("sum", field_add);
        DBObject project = new BasicDBObject("$project", project_field);
        DBObject sort = new BasicDBObject("$sort", new BasicDBObject("_id", 1));
        List<DBObject> pipeline = Arrays.asList(unwind, group, project, sort);

        //            AggregationOutput output = coll.aggregate(pipeline);
        //            for (DBObject result : output.results()) {
        //                System.out.println(result);
        //            }

        AggregationOptions aggregationOptions = AggregationOptions.builder().batchSize(100)
                .outputMode(AggregationOptions.OutputMode.CURSOR).allowDiskUse(true).build();

        BasicDBObject dbo = new BasicDBObject();
        BasicDBList dbl = new BasicDBList();
        Cursor cursor = coll.aggregate(pipeline, aggregationOptions);
        //            
        DBCollection person_col = db.getCollection("persons");

        //            BasicDBObject query = new BasicDBObject("items.personId",1);             
        BasicDBObject fields = new BasicDBObject("items.$", 1).append("_id", false);

        //            BasicDBList l_per = (BasicDBList) person_col.findOne(query, fields).get("items");
        //            BasicDBObject[] lightArr = l_per.toArray(new BasicDBObject[0]);            
        //            System.out.println(lightArr[0].get("_id"));
        //            System.out.println(lightArr[0].get("first_name"));  

        //            BasicDBList result = new BasicDBList();
        while (cursor.hasNext()) {
            dbo = (BasicDBObject) cursor.next();
            //                System.out.println(dbo.toString());  
            DBObject query = new BasicDBObject("items._id", (ObjectId) dbo.get("person_id"));
            BasicDBList lst_person = (BasicDBList) person_col.findOne(query, fields).get("items");
            BasicDBObject[] lightArr = lst_person.toArray(new BasicDBObject[0]);
            //                System.out.println(lightArr[0].get("first_name"));

            Date date = ((ObjectId) lightArr[0].get("_id")).getDate();
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(date);
            persianCalendar persianCalendar = new persianCalendar(calendar);

            dbo.put("date", persianCalendar.getNumericDateFormatWithTime());
            dbo.put("personId", lightArr[0].get("personId").toString());
            dbo.put("first_name", lightArr[0].get("first_name").toString());
            dbo.put("last_name", lightArr[0].get("last_name").toString());

            data.add(new Person(dbo.get("num").toString(), dbo.get("date").toString(),
                    dbo.get("personId").toString(), dbo.get("first_name").toString(),
                    dbo.get("last_name").toString()));
            //                buy_data.add(new buys(dbo.get("num").toString(),
            //                        dbo.get("date").toString(), 
            //                        dbo.get("personId").toString(),
            //                        dbo.get("first_name").toString(),
            //                        dbo.get("last_name").toString(),
            //                        dbo.get("sum").toString()
            //                ));                                
            dbo.remove("person_id");
            //                result.add(dbo);                
            //                System.out.println(dbo.get("first_name"));                  
        }
        System.out.println(dbo.toString());

    } catch (Exception e) {
        System.err.println(e.getClass().getName() + ": " + e.getMessage());
    }
}

From source file:laboratorio_2_sd.IndiceInvertido.java

public IndiceInvertido(BasicDBObject DBObject) {
    this.idPalabra = DBObject.getInt("idPalabra");
    BasicDBList frecuenciasDB = (BasicDBList) DBObject.get("frecuencias");
    this.frecuencias = new ArrayList<>();
    for (Object f : frecuenciasDB) {
        Frecuencia fTemp = new Frecuencia((BasicDBObject) f);
        this.frecuencias.add(fTemp);
    }/* ww  w  . ja v  a  2 s .c o m*/
}

From source file:MDBInt.DBMongo.java

License:Apache License

/**
 * Returns an ArraList<String> where each String is a JSONObject in String
 * version.//from w  w  w  .  j  a v a  2  s.co  m
 *
 * @param tenant
 * @param geoShape
 * @return
 */
public ArrayList<String> getDatacenters(String tenant, String geoShape) {
    DB database = this.getDB(tenant);
    DBCollection collection = database.getCollection("datacenters");

    BasicDBObject shape = (BasicDBObject) JSON.parse(geoShape);
    ArrayList<String> datacenters = new ArrayList();
    BasicDBObject geoJSON = (BasicDBObject) shape.get("geometry");
    BasicDBObject geometry = new BasicDBObject();
    BasicDBObject geoSpazialOperator = new BasicDBObject();
    BasicDBObject query = new BasicDBObject();
    BasicDBObject constrains = new BasicDBObject("_id", 0);
    Iterator<DBObject> it;
    DBCursor cursore;

    geometry.put("$geometry", geoJSON);
    geoSpazialOperator.put("$geoIntersects", geometry);
    query.put("geometry", geoSpazialOperator);
    cursore = collection.find(query, constrains);

    it = cursore.iterator();
    while (it.hasNext()) {
        datacenters.add(it.next().toString());

    }
    return datacenters;
}

From source file:mini_mirc_server.miniIRCHandler.java

/**
 * Register a user to the server (used in RegUser)
 * @param username//from   w  w w. j a va 2s. c  o m
 * @return code
 */
private int AddUser(String username) {
    int ret = 0;
    try {

        MongoClient mongoClient = new MongoClient();
        DB db = mongoClient.getDB("mirc");
        DBCollection coll = db.getCollection("activeUser");
        BasicDBObject query = new BasicDBObject("username", username);

        DBCursor cursor = coll.find(query);

        try {
            if (cursor.hasNext()) {
                Date now = new Date();
                long timestamp_now = now.getTime();
                long treshold = timestamp_now - (1000 * 10); //10
                BasicDBObject temp = (BasicDBObject) cursor.next();
                Date time_temp = (Date) temp.get("timestamp");
                long timestamp_temp = time_temp.getTime();
                if (timestamp_temp < treshold) {
                    ret = 2;
                    System.out.println(username + " has joined back!");
                } else {
                    ret = 1;
                    System.err.println(username + " has been used !");
                }
            } else {
                java.util.Date date = new java.util.Date();
                BasicDBObject doc = new BasicDBObject("username", username).append("timestamp", date);
                coll.insert(doc);
                System.out.println(username + " online !");
            }
        } finally {
            cursor.close();
        }

    } catch (UnknownHostException ex) {
        Logger.getLogger(miniIRCHandler.class.getName()).log(Level.SEVERE, null, ex);
    }
    return ret;
}

From source file:mini_mirc_server.miniIRCHandler.java

private int PutMessage(String username, String channelname, String msg) {
    int ret = 0;//w  ww  .j a va2s  . co m
    try {
        MongoClient mongoClient = new MongoClient();
        DB db = mongoClient.getDB("mirc");
        DBCollection coll = db.getCollection("inbox");
        DBCollection coll2 = db.getCollection("channelCollection");
        BasicDBObject query2 = new BasicDBObject("channel", channelname);
        BasicDBObject query = new BasicDBObject("channel", channelname).append("username", username);
        DBCursor cursor = coll2.find(query);
        try {
            if (cursor.hasNext()) {
                DBCursor cursor2 = coll2.find(query2);
                System.out.println("Got message from " + username);
                try {
                    java.util.Date date = new java.util.Date();
                    while (cursor2.hasNext()) {
                        ret = 1;
                        BasicDBObject temp = (BasicDBObject) cursor2.next();
                        String target = temp.get("username").toString();
                        BasicDBObject put = new BasicDBObject("target", target).append("username", username)
                                .append("channel", channelname).append("message", msg)
                                .append("timestamp", date.getTime());
                        coll.insert(put);
                        ret = 0;
                    }
                } finally {
                    cursor2.close();
                }
            } else {
                ret = 2;
                System.out.println(username + " not registered to Channel : " + channelname);
            }
        } finally {
            cursor.close();
        }

    } catch (UnknownHostException ex) {
        ret = 1;
        Logger.getLogger(miniIRCHandler.class.getName()).log(Level.SEVERE, null, ex);
    }
    return ret;
}

From source file:mini_mirc_server.Mini_mirc_server.java

public static void cleaner() {
    try {//from   w  ww. java 2  s.c  o m
        boolean hard_clean = false;
        MongoClient mongoClient = new MongoClient();
        DB db = mongoClient.getDB("mirc");
        DBCollection coll = db.getCollection("activeUser");

        DBCursor cursor = coll.find();
        try {
            Date now = new Date();
            long timestamp_now = now.getTime();
            long treshold = timestamp_now - (1000 * 60 * 5); //5 minutes
            while (cursor.hasNext()) {
                hard_clean = true;
                BasicDBObject temp = (BasicDBObject) cursor.next();
                Date time_temp = (Date) temp.get("timestamp");
                long timestamp_temp = time_temp.getTime();
                if (timestamp_temp < treshold) {
                    String target = temp.getString("username");
                    handler.SoftDelete(target);
                }
            }
            HardClean();
        } finally {
            cursor.close();
        }

    } catch (UnknownHostException ex) {
        Logger.getLogger(Mini_mirc_server.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:Model.DAO_Devoir.java

@Override
public List<Devoir> findAll() {
    //On instancie la liste qui va contenir les clients retourns par la requte
    List<Devoir> listDevoir = new ArrayList<>();

    cursor = collection.find();/* www  .  java 2s.c  o  m*/

    try {
        //Pour chaque enregistrement trouv
        while (cursor.hasNext()) {
            //On instancie un objet
            DBObject objet = cursor.next();
            //On le cast en client en rentrant les parametres
            Devoir devoir = new Devoir(objet.get("libelle").toString(), objet.get("matiere").toString(),
                    (Date) objet.get("date"));
            //On ajoute l'id de l'enregistrement
            devoir.setId((ObjectId) objet.get("_id"));
            //On ajoute la liste des Rubriques

            List<Rubrique> lstRubrique = new ArrayList<Rubrique>();
            BasicDBList listBDRubrique = (BasicDBList) objet.get("lstRubrique");

            if (listBDRubrique != null) {
                Iterator itListBDRubrique = listBDRubrique.iterator();

                while (itListBDRubrique.hasNext()) {
                    List<Critere> lstCritere = new ArrayList<Critere>();
                    BasicDBObject objectCritere = (BasicDBObject) itListBDRubrique.next();
                    BasicDBList listBDCritere = (BasicDBList) objectCritere.get("lstCritere");
                    Iterator itListBDCritere = listBDCritere.iterator();
                    while (itListBDCritere.hasNext()) {//On ajoute la liste des Critere
                        BasicDBObject aDBObjectCritere = (BasicDBObject) itListBDCritere.next();
                        Critere unCritere = new Critere(aDBObjectCritere.get("libelle").toString(),
                                (Integer) aDBObjectCritere.get("poid"));

                        lstCritere.add(unCritere);
                    }
                    Rubrique uneRubrique = new Rubrique(objectCritere.get("libelle").toString(), lstCritere);
                    lstRubrique.add(uneRubrique);
                }
                devoir.setLstRubrique(lstRubrique);//ajout list Rubrique

                List<Groupe> lstGroupe = new ArrayList<Groupe>();
                BasicDBList listBDGroupe = (BasicDBList) objet.get("lstGroupe");
                Iterator itListBDGroupe = listBDGroupe.iterator();

                while (itListBDGroupe.hasNext()) {
                    List<Etudiant> lstEtudiant = new ArrayList<Etudiant>();
                    List<Note> lstNote = new ArrayList<Note>();
                    BasicDBObject objectsGroupe = (BasicDBObject) itListBDGroupe.next();
                    BasicDBList listBDEtudiant = (BasicDBList) objectsGroupe.get("lstEtudiant");
                    Iterator itListBDEtudiant = listBDEtudiant.iterator();
                    while (itListBDEtudiant.hasNext()) {//On ajoute la liste des Critere
                        BasicDBObject aDBObjectCritere = (BasicDBObject) itListBDEtudiant.next();
                        Etudiant unEtudiant = new Etudiant(aDBObjectCritere.get("prenom").toString(),
                                aDBObjectCritere.get("nom").toString(),
                                aDBObjectCritere.get("classe").toString());

                        lstEtudiant.add(unEtudiant);
                    }
                    BasicDBList listBDNote = (BasicDBList) objectsGroupe.get("lstNote");
                    Iterator itListBDNote = listBDNote.iterator();
                    while (itListBDNote.hasNext()) {//On ajoute la liste des Critere
                        BasicDBObject aDBObjectNote = (BasicDBObject) itListBDNote.next();
                        Note uneNote = new Note(aDBObjectNote.get("libelle").toString(),
                                (Integer) aDBObjectNote.get("poid"), (Double) aDBObjectNote.get("note"));
                        //1.5);

                        lstNote.add(uneNote);
                    }
                    Groupe unGroupe = new Groupe(objectsGroupe.get("libelle").toString(), lstEtudiant, lstNote);
                    lstGroupe.add(unGroupe);
                }
                devoir.setLstGroupe(lstGroupe);
            }
            //On ajoute le client  la liste
            listDevoir.add(devoir);
        }
    } finally {
        cursor.close();
    }
    return listDevoir;
}

From source file:models.utils.Mongo2gson.java

License:Apache License

/**
 * Convert the given mongo BasicDBObject to JsonObject.
 *
 * @param object BasicDBObject/*from   ww w  .jav a2 s.c om*/
 * @return JsonObject
 */
public static JsonObject getAsJsonObject(DBObject object) {
    if (!(object instanceof BasicDBObject)) {
        throw new IllegalArgumentException("Expected BasicDBObject as argument type!");
    }
    BasicDBObject dbObject = (BasicDBObject) object;
    Set<String> keys = dbObject.keySet();
    Iterator<String> iterator = keys.iterator();
    JsonObject jsonObject = new JsonObject();
    while (iterator.hasNext()) {
        String key = iterator.next();
        Object innerObject = dbObject.get(key);
        if (innerObject instanceof BasicDBList) {
            jsonObject.add(key, getAsJsonArray((BasicDBList) innerObject));
        } else if (innerObject instanceof BasicDBObject) {
            jsonObject.add(key, getAsJsonObject((BasicDBObject) innerObject));
        } else {
            jsonObject.add(key, getAsJsonPrimitive(innerObject));
        }
    }
    return jsonObject;
}

From source file:mongodb.MongoDBOperations.java

License:Apache License

public void geoFindAndUpdate(DBCollection coll, BasicDBObject queryObject) {
    int query_count = 0;
    int processed_count = 0;
    int updated_count = 0;
    DBCursor cursor = coll.find(queryObject);
    try {// w ww .  jav a  2  s.  c om
        query_count = cursor.count();
        while (cursor.hasNext()) {
            BasicDBObject myDoc = (BasicDBObject) cursor.next();
            Object userLocationObj = myDoc.get("user_location");
            String location = String.valueOf(userLocationObj);

            ObjectId ID = (ObjectId) myDoc.get("_id");
            System.out.println("Queried Document: " + myDoc);

            GeoCodingClient gcc = new GeoCodingClient(this.conf);
            Thread.sleep(200);
            DBObject update = gcc.getGeoCode(location);
            //System.out.println(update);

            if (update == null) {
                System.out.print("No updates (update==null)");
                break;
            } else {
                Set<String> keyset = update.keySet();
                if (keyset == null) {
                    System.out.print("No updates (keyset==null)");
                } else if (keyset.contains("geocode")) {
                    updated_count++;
                    coll.update(new BasicDBObject().append("_id", ID),
                            myDoc.append("geocode", update.get("geocode")));
                    System.out.println(
                            "Updated Doc:\n" + coll.find(new BasicDBObject().append("_id", ID)).next());
                    System.out.println("In this run: (" + processed_count + " records processed, "
                            + updated_count + " records updated.)");
                } else if (keyset.contains("status")
                        && update.get("status").toString().contains("OVER_QUERY_LIMIT")) {
                    break;
                }
            }
            processed_count++;
        }
    } catch (InterruptedException e) {
        e.printStackTrace();
    } catch (InvalidKeyException e) {
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } finally {
        cursor.close();
        System.out.println("In this run:");
        System.out.println("Total:" + query_count + " record(s) found.");
        System.out.println("Total:" + processed_count + " record(s) processed.");
        System.out.println("Total:" + updated_count + " record(s) updated.");
    }

}