Example usage for com.mongodb DBObject get

List of usage examples for com.mongodb DBObject get

Introduction

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

Prototype

Object get(String key);

Source Link

Document

Gets a field from this object by a given name.

Usage

From source file:com.crosstreelabs.cognitio.service.mongo.MongoReferenceService.java

License:Apache License

protected Reference fromMongoObject(final DBObject obj) {
    Reference result = new Reference();
    result.id = obj.get("_id").toString();
    result.linker = obj.get("linker").toString();
    result.linkee = obj.get("linkee").toString();
    if (obj.get("discovered") != null) {
        result.discovered = new DateTime((Date) obj.get("discovered"));
    }//from  w w w  . j a  v  a 2  s  .com
    if (obj.get("defunct") != null) {
        result.defunct = new DateTime((Date) obj.get("defunct"));
    }
    return result;
}

From source file:com.cyslab.craftvm.rest.mongo.WriteServlet.java

License:GNU General Public License

@Override
protected void doDelete(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {

    log.trace("doDelete()");

    if (!can_write(req)) {
        res.sendError(SC_UNAUTHORIZED);//from  w w  w.j ava2 s.  co  m
        return;
    }

    InputStream is = req.getInputStream();
    String db_name = req.getParameter("dbname");
    String col_name = req.getParameter("colname");
    if (db_name == null || col_name == null) {
        String names[] = req2mongonames(req);
        if (names != null) {
            db_name = names[0];
            col_name = names[1];
        }
        if (db_name == null || col_name == null) {
            error(res, SC_BAD_REQUEST, Status.get("param name missing"));
            return;
        }
    }

    DB db = mongo.getDB(db_name);

    // mongo auth
    String user = req.getParameter("user");
    String passwd = req.getParameter("passwd");
    if (user != null && passwd != null && (!db.isAuthenticated())) {
        boolean auth = db.authenticate(user, passwd.toCharArray());
        if (!auth) {
            res.sendError(SC_UNAUTHORIZED);
            return;
        }
    }

    DBCollection col = db.getCollection(col_name);

    BufferedReader r = null;
    DBObject q = null;
    try {

        r = new BufferedReader(new InputStreamReader(is));
        String data = r.readLine();
        if (data == null) {
            error(res, SC_BAD_REQUEST, Status.get("no data"));
            return;
        }
        try {
            q = (DBObject) JSON.parse(data);
        } catch (JSONParseException e) {
            error(res, SC_BAD_REQUEST, Status.get("can not parse data"));
            return;
        }

    } finally {
        if (r != null)
            r.close();
    }

    // search
    if (do_search) {

        DBCursor c = col.find(q);
        long l = c.count();
        String todelete[] = new String[(int) l];
        int n = 0;

        while (c.hasNext()) {

            DBObject o = c.next();
            ObjectId oid = (ObjectId) o.get("_id");
            String id = oid.toStringMongod();
            todelete[n++] = id;

        }
        c.close();
        search.get_writer().delete(todelete);

    }

    WriteResult wr = col.remove(q, write_concern);

    // return operation status
    if (do_return) {
        out_str(req, wr.toString());
        if (wr.getError() == null) {
            res.setStatus(SC_BAD_REQUEST);
            return;
        }
    }

    res.setStatus(SC_OK);

}

From source file:com.cyslab.craftvm.rest.mongo.WriteServlet.java

License:GNU General Public License

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {

    log.trace("doPost()");

    if (!can_write(req)) {
        res.sendError(SC_UNAUTHORIZED);/*  www .  jav  a2s . c  o  m*/
        return;
    }

    InputStream is = req.getInputStream();
    String db_name = req.getParameter("dbname");
    String col_name = req.getParameter("colname");
    if (db_name == null || col_name == null) {
        String names[] = req2mongonames(req);
        if (names != null) {
            db_name = names[0];
            col_name = names[1];
        }
        if (db_name == null || col_name == null) {
            error(res, SC_BAD_REQUEST, Status.get("param name missing"));
            return;
        }
    }

    boolean upsert = Boolean.parseBoolean(req.getParameter("upsert"));
    boolean multi = Boolean.parseBoolean(req.getParameter("multi"));

    DB db = mongo.getDB(db_name);

    // mongo auth
    String user = req.getParameter("user");
    String passwd = req.getParameter("passwd");
    if (user != null && passwd != null && (!db.isAuthenticated())) {
        boolean auth = db.authenticate(user, passwd.toCharArray());
        if (!auth) {
            res.sendError(SC_UNAUTHORIZED);
            return;
        }
    }

    DBCollection col = db.getCollection(col_name);

    BufferedReader r = null;
    DBObject q = null, o = null;
    try {

        r = new BufferedReader(new InputStreamReader(is));
        String q_s = r.readLine();
        if (q_s == null) {
            error(res, SC_BAD_REQUEST, Status.get("no data"));
            return;
        }
        String o_s = r.readLine();
        if (o_s == null) {
            error(res, SC_BAD_REQUEST, Status.get("obj to update missing"));
            return;
        }
        try {
            q = (DBObject) JSON.parse(q_s);
            o = (DBObject) JSON.parse(o_s);
        } catch (JSONParseException e) {
            error(res, SC_BAD_REQUEST, Status.get("can not parse data"));
            return;
        }

    } finally {
        if (r != null)
            r.close();
    }
    //
    // search
    if (do_search) {

        String fn = col.getFullName();
        DBCursor c = col.find(q);
        int cnt = c.count();
        if (!multi)
            c.limit(1);
        long l = multi ? cnt : 1;
        String toupdate[] = new String[(int) l];
        int n = 0;
        boolean insert = false;

        if (upsert && !multi && cnt == 0)
            insert = true;

        while (c.hasNext()) {

            DBObject _o = c.next();
            ObjectId oid = (ObjectId) _o.get("_id");
            String id = oid.toStringMongod();
            toupdate[n++] = id;

        }
        c.close();

        List<String> flds = Config.search_index_fields.get(fn);
        boolean commit = false;
        Document doc = null;
        Search _writer = search.get_writer();
        if (flds != null && flds.size() > 0) {
            doc = new Document();
            try {
                for (String fld : flds) {
                    String val = (String) o.get(fld);
                    if (val == null)
                        continue;
                    _writer.add_searchable_s(doc, fld, val);
                    commit = true;
                }
                if (commit)
                    _writer.commit(doc);
            } catch (ClassCastException e) {
                error(res, SC_BAD_REQUEST, Status.get("searchable fields must be type String"));
                return;
            } catch (CorruptIndexException e) {
                error(res, SC_BAD_REQUEST, Status.get("Search corrupt index" + e));
                return;
            }
        }
        if (commit && insert)
            log.warn("upsert with search not implemented yet");
        else
            _writer.update(toupdate, doc);

    }

    WriteResult wr = col.update(q, o, upsert, multi, write_concern);

    // return operation status
    if (do_return) {
        out_str(req, wr.toString());
        if (wr.getError() == null) {
            res.setStatus(SC_BAD_REQUEST);
            return;
        }
    }

    res.setStatus(SC_CREATED);

}

From source file:com.cyslab.craftvm.rest.mongo.WriteServlet.java

License:GNU General Public License

@Override
protected void doPut(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {

    log.trace("doPut()");

    if (!can_write(req)) {
        res.sendError(SC_UNAUTHORIZED);//w w w . jav a2  s  . c  o m
        return;
    }

    InputStream is = req.getInputStream();
    String db_name = req.getParameter("dbname");
    String col_name = req.getParameter("colname");
    if (db_name == null || col_name == null) {
        String names[] = req2mongonames(req);
        if (names != null) {
            db_name = names[0];
            col_name = names[1];
        }
        if (db_name == null || col_name == null) {
            error(res, SC_BAD_REQUEST, Status.get("param name missing"));
            return;
        }
    }
    DB db = mongo.getDB(db_name);

    // mongo auth
    String user = req.getParameter("user");
    String passwd = req.getParameter("passwd");
    if (user != null && passwd != null && (!db.isAuthenticated())) {
        boolean auth = db.authenticate(user, passwd.toCharArray());
        if (!auth) {
            res.sendError(SC_UNAUTHORIZED);
            return;
        }
    }

    DBCollection col = db.getCollection(col_name);

    BufferedReader r = null;
    ArrayList<DBObject> ar = new ArrayList<DBObject>();
    try {

        r = new BufferedReader(new InputStreamReader(is));
        String data;
        while ((data = r.readLine()) != null) {
            if (data != null) {
                DBObject o;
                try {
                    o = (DBObject) JSON.parse(data);
                    ar.add(o);
                } catch (JSONParseException e) {
                    error(res, SC_BAD_REQUEST, Status.get("can not parse data"));
                    return;
                }
            }
        }

    } finally {
        if (r != null)
            r.close();
    }

    if (ar.size() == 0) {
        error(res, SC_BAD_REQUEST, Status.get("can not parse data"));
        return;
    }

    WriteResult wr = col.insert(ar, write_concern);

    // search
    if (do_search) {
        String fn = col.getFullName();
        List<String> flds = Config.search_index_fields.get(fn);
        if (flds != null && flds.size() > 0) {
            Search _writer = search.get_writer();
            try {
                for (DBObject o : ar) {
                    boolean commit = false;
                    Document doc = new Document();
                    for (String fld : flds) {
                        String val = (String) o.get(fld);
                        if (val == null)
                            continue;
                        _writer.add_searchable_s(doc, fld, val);
                        commit = true;
                    }
                    if (commit) {
                        ObjectId id = (ObjectId) o.get("_id");
                        String sid = id.toStringMongod();
                        _writer.add_storable(doc, "_id", sid);
                        _writer.add_searchable_s(doc, "_dbid_", fn);
                        _writer.commit(doc);
                    }
                }
            } catch (ClassCastException e) {
                error(res, SC_BAD_REQUEST, Status.get("searchable fields must be type String"));
                return;
            } catch (CorruptIndexException e) {
                error(res, SC_BAD_REQUEST, Status.get("Search corrupt index" + e));
                return;
            }
        }
    }

    // return operation status
    if (do_return) {
        out_str(req, wr.toString());
        if (wr.getError() == null) {
            res.setStatus(SC_BAD_REQUEST);
            return;
        }
    }

    res.setStatus(SC_CREATED);

}

From source file:com.damanzano.mongohw2_2.MongoHW2_2.java

public static void main(String[] args) throws UnknownHostException {
    MongoClient client = new MongoClient();
    DB db = client.getDB("students");
    DBCollection collection = db.getCollection("grades");

    DBCursor allGrades = collection.find(new BasicDBObject("type", "homework"))
            .sort(new BasicDBObject("student_id", 1).append("score", 1));
    try {//  w  w  w  .j a  v a2s.co m
        String studentId = "";
        while (allGrades.hasNext()) {
            DBObject grade = allGrades.next();
            System.out.println(grade);
            if (!studentId.equalsIgnoreCase(((Integer) grade.get("student_id")).toString())) {
                System.out.println("Deleting grade " + grade.get("_id").toString() + " for student "
                        + grade.get("student_id").toString());
                collection.remove(grade);
            }
            studentId = ((Integer) grade.get("student_id")).toString();
        }
    } finally {
        allGrades.close();
    }
}

From source file:com.daprota.m2.manager.MongoManager.java

License:Apache License

/**
 * Retrieves user via spceified userName.
 *
 * @param userName A user's userName./*from  w  ww  .j  a  v  a 2 s.  co  m*/
* @return user if exists. Otherwise returns null.
 */
public User findUserByUserName(String userName) throws MongoException {
    DBCursor dbCur = null;

    try {
        // get a user collection
        DBCollection coll = _db.getCollection("user");
        DBObject query = new BasicDBObject("userName", userName);
        dbCur = coll.find(query);
        boolean hasNext;
        try {
            logger.debug("Call dbCur.hasNext().");
            hasNext = dbCur.hasNext();
        } catch (MongoException ex) {
            logger.error("Search for user {} failed.\n" + ex.toString(), userName);
            throw new MongoException("Search for user " + userName + " failed.");
        }
        if (hasNext) {
            DBObject user = dbCur.next();
            ArrayList<BasicDBObject> roles = (ArrayList<BasicDBObject>) user.get("roles");
            ArrayList<Role> roles2 = new ArrayList<Role>();
            if (roles != null) {
                for (BasicDBObject role : roles) {
                    Role role3 = new Role(role.get("_id").toString(), (String) role.get("name"),
                            (String) role.get("description"));
                    roles2.add(role3);
                }
                logger.debug("User {} roles added.", userName);
            }
            return (new User(user.get("_id").toString(), (String) user.get("userName"),
                    (String) user.get("password"), roles2));
        } else {
            logger.warn("User {} could not be found", userName);
            return null;
        }
    } catch (MongoException ex) {
        logger.error("Search for user {} failed.\n" + ex.toString(), userName);
        throw new MongoException("Search for user " + userName + " failed.");
    } finally {
        dbCur.close();
    }
}

From source file:com.data.DAO.MetodoPagoDAO.java

public static ArrayList consultarRecibo(Integer idMetodoPago) {
    ArrayList reciboConsulta = new ArrayList();
    try {//from   www .j  a v  a  2  s . c o  m
        // To connect to mongo dbserver
        MongoClient mongoClient = new MongoClient("localhost", 27017);

        // Now connect to your databases
        DB db = mongoClient.getDB("hoex");
        System.out.println("Connect to database successfully");

        // Use an especific collection
        DBCollection coll = db.getCollection("Metodo_pago");
        System.out.println("Collection Metodo_pago selected successfully");

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

        DBCursor cursor = coll.find(whereQuery);

        while (cursor.hasNext()) {
            DBObject consultDocument = cursor.next();
            reciboConsulta.add(consultDocument.get("descripcion"));
            reciboConsulta.add(consultDocument.get("cuotas"));
            reciboConsulta.add(consultDocument.get("precio"));
            reciboConsulta.add(consultDocument.get("idReserva"));
        }
        System.out.println("Document consulted successfully");
    } catch (Exception e) {
        System.err.println(e.getClass().getName() + ": " + e.getMessage());
    }
    if (!reciboConsulta.isEmpty()) {
        return reciboConsulta;
    } else {
        return null;
    }
}

From source file:com.databank.mongodb.converter.UserConverter.java

public static User toUser(DBObject doc) {
    User u = new User();
    u.setFirstname((String) doc.get("firstname"));
    u.setLastname((String) doc.get("lastname"));
    u.setEmail((String) doc.get("Email"));
    u.setUsername((String) doc.get("Username"));
    u.setLocation((String) doc.get("location"));
    u.setPassword1((String) doc.get("password1"));
    ObjectId id = (ObjectId) doc.get("_id");
    u.setID(id.toString());/* ww  w  .  ja va2 s .  c om*/
    return u;

}

From source file:com.dawsonsystems.session.MongoSessionManager.java

License:Apache License

public Session loadSession(String id) throws IOException {

    if (id == null || id.length() == 0) {
        return createEmptySession();
    }/*from w w  w .ja v  a 2  s  . c o m*/

    StandardSession session = currentSession.get();

    if (session != null) {
        if (id.equals(session.getId())) {
            return session;
        } else {
            currentSession.remove();
        }
    }
    try {
        log.fine("Loading session " + id + " from Mongo");
        BasicDBObject query = new BasicDBObject();
        query.put("_id", id);

        DBObject dbsession = getCollection().findOne(query);

        if (dbsession == null) {
            log.fine("Session " + id + " not found in Mongo");
            StandardSession ret = getNewSession();
            ret.setId(id);
            currentSession.set(ret);
            return ret;
        }

        String map = dbsession.get("data").toString();
        Map<Object, Object> data = JSON.parseObject(map, new TypeReference<Map<Object, Object>>() {
        });
        ;

        session = (MongoSession) createEmptySession();
        session.setId(id);
        session.setManager(this);
        serializer.deserializeInto(data, session);

        session.setMaxInactiveInterval(-1);
        session.access();
        session.setValid(true);
        session.setNew(false);

        if (log.isLoggable(Level.FINE)) {
            log.fine("Session Contents [" + session.getId() + "]:");
            for (Object name : Collections.list(session.getAttributeNames())) {
                log.fine("  " + name);
            }
        }

        log.fine("Loaded session id " + id);
        currentSession.set(session);
        return session;
    } catch (IOException e) {
        log.severe(e.getMessage());
        throw e;
    } catch (ClassNotFoundException ex) {
        log.log(Level.SEVERE, "Unable to deserialize session ", ex);
        throw new IOException("Unable to deserializeInto session", ex);
    }
}

From source file:com.deafgoat.ml.prognosticator.Mongo2CSV.java

License:Apache License

/**
 * Writes the collectionection to a CSV file using the MongoExport command.
 * //from   w  w  w  .j  a  va2  s .c  o m
 * @param filename
 *            Th name of the file to write the collectionection to
 * @throws IOException
 *             If unable to write to file
 * @throws FileNotFoundException
 *             If the file is not found
 */
public void writeCSV(String filename) throws IOException, FileNotFoundException {
    BufferedWriter out = new BufferedWriter(new FileWriter(filename));
    DBCursor cursor = _collection.find();
    out.write(Mongo2CSV.join(Arrays.asList(_fields), _delimeter) + "\n");
    ArrayList<String> entry = new ArrayList<String>();
    DBObject obj;
    while (cursor.hasNext()) {
        obj = cursor.next();
        for (String field : _fields) {
            entry.add((String) obj.get(field));
        }
        out.write(join(entry, _delimeter) + "\n");
        entry.clear();
    }
    cursor.close();
    out.close();
}