Example usage for com.mongodb DBObject put

List of usage examples for com.mongodb DBObject put

Introduction

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

Prototype

Object put(String key, Object v);

Source Link

Document

Sets a name/value pair in this object.

Usage

From source file:backend.facades.UserController.java

protected static String getNextId(DB db, String seq_name) {
    String sequence_collection = "seq"; // the name of the sequence collection
    String sequence_field = "seq"; // the name of the field which holds the sequence

    DBCollection seq = db.getCollection(sequence_collection); // get the collection (this will create it if needed)               

    if (seq == null) {
        seq = db.createCollection(sequence_collection, null);
    }/*from w ww  .j a  v a  2s.  c  o m*/

    // this object represents your "query", its analogous to a WHERE clause in SQL
    DBObject query = new BasicDBObject();
    query.put("_id", seq_name); // where _id = the input sequence name

    // this object represents the "update" or the SET blah=blah in SQL
    DBObject change = new BasicDBObject(sequence_field, 1);
    DBObject update = new BasicDBObject("$inc", change); // the $inc here is a mongodb command for increment

    // Atomically updates the sequence field and returns the value for you
    DBObject res = seq.findAndModify(query, new BasicDBObject(), new BasicDBObject(), false, update, true,
            true);
    return res.get(sequence_field).toString();
}

From source file:bank_server.Task.java

@Override
public void run() {
    try {//from ww w.  j a  v  a2  s . c  om
        oos = new ObjectOutputStream(cSock.getOutputStream());
        ois = new ObjectInputStream(cSock.getInputStream());
        if (ois == null || oos == null)
            System.exit(1);
        else
            System.out.println("Flux crs");

        List names = collection.distinct("banque.name");
        List idsTMP = collection.distinct("_id");
        Set<Integer> ids = new HashSet<>();

        for (Object id : idsTMP)
            ids.add(Integer.parseInt(id.toString().replace(".0", "")));

        Request req = (Request) ois.readObject();
        Response rep = new Response();
        rep.setName(req.getName());
        Boolean fin = null;
        String banque = null;
        int IDBanque = 0;
        if (names.contains(req.getContent())) {
            rep.setStatus(true);
            oos.writeObject(rep);
            fin = false;
            banque = req.getContent();
            DBObject proj = new BasicDBObject("banque._id", 1);
            DBObject query = new BasicDBObject("banque.name", banque);
            DBObject doc = collection.findOne(query, proj);
            String str1[] = doc.toString().split("\"banque\" : \\{ \"_id\" : ");
            String str2[] = str1[1].split(".0}");
            IDBanque = Integer.parseInt(str2[0]);
            System.out.println(banque + " : " + IDBanque);
        } else {
            rep.setStatus(false);
            oos.writeObject(rep);
            fin = true;
        }

        while (fin != true) {
            req = (Request) ois.readObject();
            DBObject document = new BasicDBObject();

            Date d = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String date = sdf.format(d);

            switch (req.getName()) {
            case "END": {
                System.out.println("Closing Connection");
                fin = true;
            }
                break;
            case "credit": {
                Integer id = 0;
                while (ids.contains(id))
                    id++;
                ids.add(id);
                System.out.println("id choisi : " + id);
                document.put("_id", id);
                document.put("type", "credit");
                document.put("montant", req.getMontant());
                document.put("valide", "false");
                document.put("date", date);
                document.put("banque", new BasicDBObject("_id", IDBanque).append("name", banque));
                collection.insert(document);

                rep = new Response();
                rep.setName(req.getName());
                rep.setStatus(true);
            }
                break;
            case "debit": {
                Integer id = 0;
                while (ids.contains(id))
                    id++;
                ids.add(id);
                System.out.println("id choisi : " + id);
                document.put("_id", id);
                document.put("type", "debit");
                document.put("montant", req.getMontant());
                document.put("valide", "false");
                document.put("date", date);
                document.put("banque", new BasicDBObject("_id", IDBanque).append("name", banque));
                collection.insert(document);

                rep = new Response();
                rep.setName(req.getName());
                rep.setStatus(true);
            }
                break;
            case "etat": {
                rep = new Response();
                rep.setName(req.getName());
                try {
                    Integer id = Integer.parseInt(req.getContent());
                    if (!ids.contains(id))
                        throw new NumberFormatException();
                    document = collection.findOne(new BasicDBObject("_id", id));
                    System.out.println(document);
                    String[] str1 = document.toString().split("\"name\" : \"");
                    String[] str2 = str1[1].split("\"");
                    if (banque.equalsIgnoreCase(str2[0])) {
                        rep.setStatus(true);
                        str1 = document.toString().split("\"montant\" : ");
                        str2 = str1[1].split(" , ");
                        rep.setMontant(Integer.parseInt(str2[0].replace(".0", "")));
                        str1 = document.toString().split("\"valide\" : \"");
                        str2 = str1[1].split("\"");
                        if (str2[0].equalsIgnoreCase("true"))
                            rep.setValide(true);
                        else
                            rep.setValide(false);
                    } else {
                        rep.setStatus(false);
                        rep.setValide(false);
                    }
                } catch (NumberFormatException ex) {
                    //System.out.println("Etat : bad id request");
                    rep.setStatus(false);
                    rep.setValide(true);
                }
            }
                break;
            }
            oos.writeObject(rep);
        }
        oos.close();
        ois.close();
        cSock.close();
    } catch (IOException | ClassNotFoundException ex) {
        Logger.getLogger(Task.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:bank_server.Task2.java

@Override
public void run() {
    try {// w w w .j ava 2 s  .  c o  m
        SecretKey KS = new SecretKeySpec("cisco789".getBytes(), "DES");
        Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE, KS);
        System.out.println("KS " + KS);

        oos = new ObjectOutputStream(cSock.getOutputStream());
        System.out.println(oos);
        ois = new ObjectInputStream(cSock.getInputStream());
        System.out.println(ois);
        if (ois == null || oos == null)
            System.exit(1);
        else
            System.out.println("Flux crs");

        Boolean fin = false;
        Pull pull = null;
        Push push = null;
        while (fin != true) {
            pull = (Pull) ois.readObject();
            cipher.init(Cipher.DECRYPT_MODE, KS);
            SealedObject so = pull.getTicket().getKCS();
            KCS unsealed = null;
            unsealed = (KCS) so.getObject(cipher);
            SecretKey KCS = unsealed.getKcs();
            // Verification timestamp
            long validity = unsealed.getValidity().getTime();
            long now = new Date().getTime();
            if ((validity - now) < 0)
                throw new BadTimestampException();
            else
                System.out.println("Timestamp valide");

            switch (pull.getName()) {
            case "Hello": {
                push = new Push();
                push.setName("Hello");
            }
                break;
            case "END": {
                System.out.println("Closing Connection");
                fin = true;
            }
                break;
            case "recherche": {
                push = new Push();
                push.setName("recherche");
                DBObject query = new BasicDBObject();
                if (pull.getValide().equalsIgnoreCase("true") || pull.getValide().equalsIgnoreCase("false"))
                    query.put("valide", pull.getValide());
                if (!pull.getBanque().equals(""))
                    query.put("banque.name", pull.getBanque());

                DBCursor cursor = collection.find(query);
                iterateOverCursor(cursor, push);
                cursor.close();
            }
                break;
            case "validation": {
                for (int i = 0; i < pull.getIds().size(); i++) {
                    //System.out.println(pull.getIds().get(i));
                    DBObject query = new BasicDBObject("_id", Integer.parseInt(pull.getIds().get(i)));
                    DBObject update = new BasicDBObject();
                    update.put("$set", new BasicDBObject("valide", "true"));
                    collection.update(query, update);
                }

                push = new Push();
                push.setName("validOK");

            }
                break;
            }
            cipher.init(Cipher.DECRYPT_MODE, KCS);
            AuthenticatorTGS auth = (AuthenticatorTGS) pull.getAuthenticator().getObject(cipher);
            cipher.init(Cipher.ENCRYPT_MODE, KCS);
            push.setTimestamp(new SealedObject(auth.getCurrentTime(), cipher));

            oos.writeObject(push);
        }
        oos.close();
        ois.close();
        cSock.close();
    } catch (BadTimestampException ex) {
        System.out.println("BadTimeStampExc");
    } catch (Exception ex) {
        Logger.getLogger(Task.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:br.ufabc.impress.mongo.manager.DBHelper.java

@Override
public String addDefault(String tableName, String json) {
    if (tableName == null || tableName.equals("") || json == null || json.equals("")) {
        return "501";
    }// w  w w. j ava  2 s . co  m
    DBCollection table = db.getCollection(tableName);
    DBObject dbObject = (DBObject) JSON.parse(json);
    dbObject.put("status", "active");
    dbObject.put("createDate", System.currentTimeMillis() + "");
    dbObject.put("updateDate", System.currentTimeMillis() + "");
    WriteResult wRes = table.insert(dbObject);
    return ((ObjectId) dbObject.get("_id")).toString();
}

From source file:br.ufabc.impress.mongo.manager.DBHelper.java

@Override
public boolean modify(String tableName, String json, String _id) {
    if (tableName == null || tableName.equals("") || json == null || json.equals("") || _id == null
            || _id.equals("")) {
        return false;
    }/*  w  ww . ja  va2s . co  m*/
    DBCollection table = db.getCollection(tableName);
    BasicDBObject searchQuery = new BasicDBObject();
    searchQuery.put("_id", new ObjectId(_id));
    DBObject dbObject = (DBObject) JSON.parse(json);
    dbObject.put("update", System.currentTimeMillis() + "");
    WriteResult result = table.update(searchQuery, dbObject);
    return result.isUpdateOfExisting();
}

From source file:br.ufabc.impress.mongo.manager.DBHelper.java

@Override
public boolean modifyByCondition(String tableName, String json, Map condition) {
    if (tableName == null || tableName.equals("") || json == null || json.equals("") || condition == null
            || condition.isEmpty()) {/*from  w  w w. j  a va  2 s. co m*/
        return false;
    }
    DBCollection table = db.getCollection(tableName);
    BasicDBObject searchQuery = new BasicDBObject(condition);
    DBObject dbObject = (DBObject) JSON.parse(json);
    dbObject.put("update", System.currentTimeMillis() + "");
    WriteResult result = table.update(searchQuery, dbObject);
    return result.isUpdateOfExisting();
}

From source file:BusinessLogic.Service.RestaurantService.java

public String update(
        //String name, String direccion, String phone) {
        Restaurant rs) {/*from www.jav a  2  s.c  o  m*/
    String name = rs.getName();
    String direccion = rs.getAddress();
    String phone = rs.getPhone();
    String reservationUpdate = null;
    try {
        // To connect to mongo dbserver
        MongoConnection dbSingleton = MongoConnection.getInstance();
        DB db = dbSingleton.getTestdb();
        DBCollection coll = db.getCollection(collName);

        System.out.println("Collection restaurants selected successfully");

        BasicDBObject whereQuery = new BasicDBObject();
        // Sentence to search one account number
        whereQuery.put("name", name);

        DBCursor cursor = coll.find(whereQuery);

        while (cursor.hasNext()) {

            DBObject updateDocument = cursor.next();
            updateDocument.put("name", name);
            updateDocument.put("direccion", direccion);
            updateDocument.put("phone", phone);

            coll.update(whereQuery, updateDocument);

        }
        System.out.println("Document updated successfully");
        reservationUpdate = "Success";

    } catch (Exception e) {
        System.err.println(e.getClass().getName() + ": " + e.getMessage());
    }
    if (reservationUpdate != null) {
        return "The restaurant has been updated successfully!";
    } else {
        return "The restaurant has not been updated!";
    }
}

From source file:calliope.core.database.MongoConnection.java

License:Open Source License

DBObject getThreeFieldQuery(String field1, String value1, String field2, String value2, String field3,
        String value3) {/*from  w w w  . ja  v  a2 s .  co  m*/
    DBObject query;
    if (field1.equals(JSONKeys._ID)) {
        ObjectId objId = new ObjectId(value1);
        query = new BasicDBObject(field1, objId);
    } else
        query = new BasicDBObject(field1, value1);
    if (field2.equals(JSONKeys._ID)) {
        ObjectId objId = new ObjectId(value2);
        query.put(field2, objId);
    } else
        query.put(field2, value2);
    if (field3.equals(JSONKeys._ID)) {
        ObjectId objId = new ObjectId(value3);
        query.put(field3, objId);
    } else
        query.put(field3, value3);
    return query;
}

From source file:calliope.core.database.MongoConnection.java

License:Open Source License

/**
 * PUT a json file to the database//w w  w.jav  a 2  s  . c o m
 * @param collName the name of the collection
 * @param docID the docid of the resource 
 * @param json the json to put there
 * @return the server response
 */
@Override
public String putToDb(String collName, String docID, String json) throws DbException {
    try {
        DBObject doc = (DBObject) JSON.parse(json);
        doc.put(JSONKeys.DOCID, docID);
        connect();
        DBCollection coll = getCollectionFromName(collName);
        DBObject query = new BasicDBObject(JSONKeys.DOCID, docID);
        WriteResult result = coll.update(query, doc, true, false);
        //return removeFromDb( path );
        return result.toString();
    } catch (Exception e) {
        throw new DbException(e);
    }
}

From source file:calliope.core.database.MongoConnection.java

License:Open Source License

/**
 * PUT a json file to the database using dbase, docid and version
 * @param collName the name of the collection
 * @param dbase the name of the database 
 * @param docid the document identifier/*from  www.j  a  v  a2s.co m*/
 * @param version the version of the document
 * @param json the json to put there
 * @return the server response
 */
@Override
public String putToDb(String collName, String dbase, String docid, String version, String json)
        throws DbException {
    try {
        DBObject doc = (DBObject) JSON.parse(json);
        doc.put(JSONKeys.DOCID, docid);
        connect();
        DBObject query = getThreeFieldQuery(JSONKeys.DBASE, dbase, JSONKeys.DOCID, docid, JSONKeys.VERSION1,
                version);
        DBCollection coll = getCollectionFromName(collName);
        WriteResult result = coll.update(query, doc, true, false);
        //return removeFromDb( path );
        return result.toString();
    } catch (Exception e) {
        throw new DbException(e);
    }
}