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:calliope.core.database.MongoConnection.java

License:Open Source License

/**
 * PUT a new json file to the database// w  w  w.  j av  a 2 s . c o m
 * @param collName the name of the collection
 * @param json the json to put there
 * @return the server response
 */
@Override
public String addToDb(String collName, String json) throws DbException {
    try {
        DBObject doc = (DBObject) JSON.parse(json);
        connect();
        DBCollection coll = getCollectionFromName(collName);
        if (doc.containsField(JSONKeys._ID)) {
            Object id = doc.get(JSONKeys._ID);
            DBObject query = new BasicDBObject(JSONKeys._ID, id);
            if (query != null) {
                WriteResult result = coll.update(query, doc, true, false);
                return result.toString();
            } else
                throw new Exception("Failed to update object " + id);
        } else {
            WriteResult result = coll.insert(doc, WriteConcern.ACKNOWLEDGED);
            // return the new document's id
            ObjectId id = (ObjectId) doc.get("_id");
            JSONObject jDoc = (JSONObject) JSONValue.parse(result.toString());
            jDoc.put("_id", id.toString());
            return jDoc.toJSONString();
        }
    } catch (Exception e) {
        throw new DbException(e);
    }
}

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

License:Open Source License

/**
 * List all the documents in a Mongo collection
 * @param collName the name of the collection
 * @param key the document key to retrieve by
 * @return a String array of document keys
 * @throws DbException /* w  w w  .jav a2s  .  c  om*/
 */
@Override
public String[] listCollectionByKey(String collName, String key) throws DbException {
    try {
        connect();
    } catch (Exception e) {
        throw new DbException(e);
    }
    DBCollection coll = getCollectionFromName(collName);
    BasicDBObject keys = new BasicDBObject();
    keys.put(key, 1);
    DBCursor cursor = coll.find(new BasicDBObject(), keys);
    if (cursor.length() > 0) {
        String[] docs = new String[cursor.length()];
        Iterator<DBObject> iter = cursor.iterator();
        int i = 0;
        while (iter.hasNext()) {
            DBObject dbObj = iter.next();
            Object obj = dbObj.get(key);
            if (key.equals(JSONKeys._ID)) {
                ObjectId id = (ObjectId) dbObj.get(JSONKeys._ID);
                obj = id.toStringMongod();
                docs[i++] = (String) obj;
            } else
                docs[i++] = obj.toString();
        }
        return docs;
    } else
        return new String[0];
}

From source file:calliope.db.MongoConnection.java

License:Open Source License

/**
 * Check that the database response is OK
 * @param response the json response from the MongoDB
 * @return true if its OK was 1.0 or the response has an _id field
 *///w w  w. j  a  v  a2  s .c  om
private boolean checkResponse(String response) {
    DBObject doc = (DBObject) JSON.parse(response);
    Object value = doc.get("ok");
    if (value instanceof Double && ((Double) value).doubleValue() == 1.0)
        return true;
    else {
        value = doc.get("_id");
        if (value != null)
            return true;
        else
            return false;
    }
}

From source file:cc.acs.mongofs.gridfs.CLI.java

License:Apache License

public static void main(String[] args) throws Exception {

    if (args.length < 1) {
        printUsage();/* w  ww  . j ava 2 s  . c o m*/
        return;
    }

    Mongo m = null;

    for (int i = 0; i < args.length; i++) {
        String s = args[i];

        if (s.equals("--db")) {
            db = args[i + 1];
            i++;
            continue;
        }

        if (s.equals("--host")) {
            host = args[i + 1];
            i++;
            continue;
        }

        if (s.equals("help")) {
            printUsage();
            return;
        }

        if (s.equals("list")) {
            GridFS fs = getGridFS();

            System.out.printf("%-60s %-10s\n", "Filename", "Length");

            for (DBObject o : fs.getFileList()) {
                System.out.printf("%-60s %-10d\n", o.get("filename"), ((Number) o.get("length")).longValue());
            }
            return;
        }

        if (s.equals("get")) {
            GridFS fs = getGridFS();
            String fn = args[i + 1];
            GridFSDBFile f = fs.findOne(fn);
            if (f == null) {
                System.err.println("can't find file: " + fn);
                return;
            }

            f.writeTo(f.getFilename());
            return;
        }

        if (s.equals("put")) {
            GridFS fs = getGridFS();
            String fn = args[i + 1];
            GridFSInputFile f = fs.createFile(new File(fn));
            f.save();
            f.validate();
            return;
        }

        if (s.equals("md5")) {
            GridFS fs = getGridFS();
            String fn = args[i + 1];
            GridFSDBFile f = fs.findOne(fn);
            if (f == null) {
                System.err.println("can't find file: " + fn);
                return;
            }

            MessageDigest md5 = MessageDigest.getInstance("MD5");
            md5.reset();
            DigestInputStream is = new DigestInputStream(f.getInputStream(), md5);
            int read = 0;
            while (is.read() >= 0) {
                read++;
                int r = is.read(new byte[17]);
                if (r < 0)
                    break;
                read += r;
            }
            byte[] digest = md5.digest();
            System.out.println("length: " + read + " md5: " + Util.toHex(digest));
            return;
        }

        System.err.println("unknown option: " + s);
        return;
    }

}

From source file:cc.acs.mongofs.gridfs.GridFSDBFile.java

License:Apache License

byte[] getChunk(int i) {
    if (_fs == null)
        throw new RuntimeException("no gridfs!");

    DBObject chunk = _fs._chunkCollection
            .findOne(BasicDBObjectBuilder.start("files_id", _id).add("n", i).get());
    if (chunk == null)
        throw new MongoException("can't find a chunk!  file id: " + _id + " chunk: " + i);

    return (byte[]) chunk.get("data");
}

From source file:cfel.service.PortalImportTask.java

License:Open Source License

private void fixThumbnailImages() {
    DBObject query = new BasicDBObject("card_image_url", new BasicDBObject("$exists", false));
    for (Iterator<DBObject> it = mPhotoCollection.find(query); it.hasNext();) {
        DBObject photo = it.next();
        if (!photo.containsField("portal_image_url")) {
            System.err.println("No portal_image_url in " + photo);
            continue;
        }/*from ww w.j a  v a 2s. c o m*/
        String portal_image_url = photo.get("portal_image_url").toString();
        if (!portal_image_url.matches("^https?://.*")) {
            portal_image_url = Config.ALBUM_ROOT + portal_image_url;
        }
        try {
            URL url = new URL(portal_image_url);
            System.err.println("Missing thumbnail images for " + url);
            BufferedImage[] images = ImageUtil.convertImage(url);
            if (images != null) {
                DBObject updates = new BasicDBObject();
                saveThumbnailImages(updates, images, url.getPath().replace(".", "_") + ".png");
                mPhotoCollection.update(photo, new BasicDBObject("$set", updates));
            } else {
                System.err.println(url + " corrupted");
            }
        } catch (MalformedURLException e) {
            System.err.println("Unknown image URL" + portal_image_url);
            continue;
        }
    }
}

From source file:cfel.service.PortalImportTask.java

License:Open Source License

private void fixActivities(Set<String> imageSet) {
    DBObject query = new BasicDBObject("$and",
            new DBObject[] { new BasicDBObject("portal_image_url", new BasicDBObject("$exists", true)),
                    new BasicDBObject("uploader_user_id", new BasicDBObject("$exists", true)) });
    for (Iterator<DBObject> it = mPhotoCollection.find(query); it.hasNext();) {
        DBObject photo = it.next();
        boolean temporary_removed = !imageSet.contains(photo.get("portal_image_url").toString());
        boolean removed = Boolean.TRUE.equals(photo.get("permanently_removed")) || temporary_removed;
        if (temporary_removed != Boolean.TRUE.equals(photo.get("temporary_removed"))) {
            mPhotoCollection.update(photo,
                    new BasicDBObject("$set", new BasicDBObject("temporary_removed", temporary_removed)));
        }/*from w w w  .  java 2 s. c om*/
        if (removed != Boolean.TRUE.equals(photo.get("removed"))) {
            mPhotoCollection.update(photo, new BasicDBObject("$set", new BasicDBObject("removed", removed)));
            System.out.println("removed:" + removed + " " + photo);
        }
    }
}

From source file:cfel.servlet.ImportCsvServlet.java

License:Open Source License

/**
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
 *      response)//from ww w.  ja  va2 s .  c o m
 */
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    DBCollection collection = mDS.getCollection("photo");
    if (collection == null) {
        response.sendError(404, "No photo collection");
        return;
    }
    InputStream is = null;
    try {
        is = request.getInputStream();
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        String line = br.readLine(); // Ignore header
        while ((line = br.readLine()) != null) {
            String[] values = getStrings(line);
            if (values.length == 2) {
                String portal_image_url = values[0];
                String class_id = values[1];
                System.out.println("url=" + portal_image_url + ", season=" + class_id);
                DBObject query = new BasicDBObject("portal_image_url", portal_image_url);
                DBObject photo = collection.findOne(query);
                if (photo == null) {
                    continue;
                }
                Object guessObj = photo.get("guess");
                if (guessObj instanceof List<?>) {
                    System.out.println(guessObj);
                    List<?> guess = (List<?>) guessObj;
                    Object lastGuess = guess.get(guess.size() - 1);
                    if (lastGuess instanceof DBObject
                            && class_id.equals(((DBObject) lastGuess).get("class_id"))) {
                        continue;
                    }
                }
                DBObject newGuess = new BasicDBObject();
                newGuess.put("updated", new Date());
                newGuess.put("class_id", class_id);
                DBObject update = new BasicDBObject("$push", new BasicDBObject("guess", newGuess));
                collection.update(photo, update, true, false);
            } else {
                System.err.println("Unknown data: " + line);
            }
        }

    } finally {
        if (is != null) {
            is.close();
        }
    }
    response.setStatus(200);
}

From source file:cfel.servlet.ServiceServlet.java

License:Open Source License

/**
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
 *      response)//from w  w  w.ja v a 2  s  . co  m
 * 
 *      Insert a new resource
 */
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String type = request.getParameter("type");
    String id = request.getParameter("id");
    String data = request.getParameter("data");
    System.out.println("doPost: type=" + type + " id=" + id + " data=" + data);

    if ("file".equals(type)) {
        // Save a file with id
        doPut(request, response);
        return;
    }

    DBCollection collection = mDS.getCollection(type);
    if (collection == null) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, String.format("Unknown collection %s", type));
        return;
    }

    String action = request.getParameter("action");
    if (action != null) {
        // Manipulate database
        if ("update".equals(action)) {
            String query = request.getParameter("query");
            String update = request.getParameter("update");
            String upsert = request.getParameter("upsert");
            String multi = request.getParameter("multi");
            DBObject queryObj = null;
            if (id != null) {
                queryObj = new BasicDBObject("_id", new ObjectId(id));
            } else if (query != null) {
                queryObj = (DBObject) JSON.parse(query);
            }
            DBObject updateObj = update != null ? (DBObject) JSON.parse(update) : null;
            if (queryObj == null || updateObj == null) {
                response.sendError(HttpServletResponse.SC_BAD_REQUEST, "No query or update parameters");
                return;
            }
            sendJSON(collection.update(queryObj, updateObj, "true".equals(upsert), "true".equals(multi)),
                    response);
        } else {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, String.format("Unknown action %s", action));
        }
        return;
    }

    if (data == null) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, "No data specified");
        return;
    }

    // Insert a document
    DBObject dataObject = (DBObject) JSON.parse(data);
    Object dataID = dataObject.get("_id");
    if (dataID != null && collection.findOne(dataID) != null) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Duplicated id");
        return;
    }
    collection.insert(dataObject);
    sendJSON(dataObject, response);
}

From source file:cfel.servlet.ServiceServlet.java

License:Open Source License

/**
 * @see HttpServlet#doPut(HttpServletRequest, HttpServletResponse)
 * /*  w w  w. j a  va  2  s  .c o  m*/
 *      Update a resource with id
 */
protected void doPut(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String type = request.getParameter("type");
    String id = request.getParameter("id");
    String data = request.getParameter("data");
    System.out.println("doPut: type=" + type + " id=" + id);

    if ("file".equals(type)) {
        // Save a file
        if (id == null) {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, "No file id specified");
            return;
        }
        InputStream is = null;
        try {
            mDS.saveFile(id, is = request.getInputStream(), request.getContentType());
        } finally {
            if (is != null) {
                is.close();
            }
        }
        return;
    }

    DBCollection collection = mDS.getCollection(type);
    if (collection == null) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, String.format("Unknown collection %s", type));
        return;
    }
    if (data == null) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, "No data specified");
        return;
    }

    // Update a document
    DBObject dataObject = (DBObject) JSON.parse(data);
    Object idObj = dataObject.get("_id"); // = id in source
    if (idObj == null && id != null) {
        idObj = new ObjectId(id); // = id in URI
    }
    if (idObj == null) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, "No document id specified");
        return;
    }
    collection.update(new BasicDBObject("_id", idObj), dataObject, true, false);
    sendJSON(dataObject, response);
}