Example usage for com.mongodb DBCollection findOne

List of usage examples for com.mongodb DBCollection findOne

Introduction

In this page you can find the example usage for com.mongodb DBCollection findOne.

Prototype

@Nullable
public DBObject findOne(final Object id) 

Source Link

Document

Get a single document from collection by '_id'.

Usage

From source file:fr.wseduc.gridfs.GridFSPersistor.java

License:Apache License

private void getChunk(Message<Buffer> message, JsonObject json) {
    String filesId = json.getString("files_id");
    if (filesId == null || filesId.trim().isEmpty()) {
        replyError(message, "Invalid file id.");
        return;//  w  w w .  ja  v  a2  s. c o  m
    }
    Long n = json.getLong("n");
    if (n == null) {
        replyError(message, "Invalid chunk number.");
        return;
    }
    DBCollection collection = db.getCollection(bucket + CHUNKS);
    DBObject chunk = collection.findOne(BasicDBObjectBuilder.start("files_id", filesId).add("n", n).get());
    if (chunk == null) {
        replyError(message, "Error getting chunk number " + n + " in file  " + filesId);
        return;
    }
    logger.debug("chunk : " + chunk);
    message.reply(new Buffer((byte[]) chunk.get("data")));
}

From source file:generate.ShowConceptMapAction.java

public String execute() throws ClassNotFoundException, SQLException, IOException {
    DBObject document = new BasicDBObject();
    System.out.println("Uinque ID Value:" + getIdd());
    try {//from w w w  . j a  v  a 2  s .c om
        MongoClient mongo = new MongoClient();
        DB db = mongo.getDB("Major");
        DBCollection collection = db.getCollection("ConceptMap");
        BasicDBObject query = new BasicDBObject();
        query.put("UniqueID", getIdd());
        document = collection.findOne(query);
    } catch (MongoException e) {
        System.out.println("ERRRRRORRR: " + e.getMessage());
        return ERROR;
    } catch (UnknownHostException ex) {
        Logger.getLogger(MapGenerateAction.class.getName()).log(Level.SEVERE, null, ex);
    }
    System.out.println("DB Output: " + document.get("OutputText").toString());
    setData(document.get("OutputText").toString());
    try {

        FileWriter file = new FileWriter("/home/chanakya/NetBeansProjects/Concepto/web/new_graph.json");
        file.write(getData());
        file.flush();
        file.close();

    } catch (IOException e) {
        return ERROR;
        //e.printStackTrace();
    }

    return SUCCESS;
}

From source file:GeoHazardServices.Inst.java

License:Apache License

private void loadSettings() {

    System.out.println("Load settings...");

    DBCollection coll = db.getCollection("settings");

    DBCursor cursor = coll.find(new BasicDBObject("type", "parameter"));
    for (DBObject obj : cursor) {
        String name = (String) obj.get("name");
        String value = (String) obj.get("value");

        GlobalParameter.map.put(name, value);
        System.out.println("Parameter " + name + ": " + value);
    }//from w ww.jav  a2 s.c o m
    cursor.close();

    cursor = coll.find(new BasicDBObject("type", "jet_color"));
    for (DBObject obj : cursor) {
        Double threshold = (Double) obj.get("threshold");
        String color = (String) obj.get("color");

        GlobalParameter.jets.put(threshold, color);
        System.out.println("Tsunami-Jet-Threshold " + threshold + ": " + color);
    }
    cursor.close();

    DBObject urls = coll.findOne(new BasicDBObject("type", "urls"));
    GlobalParameter.wsgi_url = (String) urls.get("wsgi");

    int j = 0;

    cursor = coll.find(new BasicDBObject("type", "worker"));
    for (DBObject obj : cursor) {

        String hardware = (String) obj.get("hardware");
        String user = (String) obj.get("user");
        String host = (String) obj.get("host");
        String dir = (String) obj.get("dir");
        String args = (String) obj.get("args");
        /* MongoDB stores all integer values as Long (bug?), so convert back here */
        Integer count = ((Long) obj.get("count")).intValue();
        int priority = ((Long) obj.get("priority")).intValue();
        boolean remote = (boolean) obj.get("remote");
        int slots[] = getSlots(obj.get("slots"), count);

        if (count == null)
            count = 1;

        System.out.print("Worker " + count + "x " + hardware + " @ " + priority);
        if (remote)
            System.out.print(", Remote: " + user + "@" + host + ":" + dir);
        System.out.println(", Args: " + args);

        for (int i = 0; i < count; i++, j++) {

            WorkerThread thread;
            try {
                thread = new WorkerThread(scheduler, mongoClient.getServerAddressList(), db.getName(),
                        GlobalParameter.map.get("localdir") + "/w" + j);
            } catch (IOException e) {
                System.err.println("Error: Could not create worker thread.");
                e.printStackTrace();
                continue;
            }

            thread.setHardware(hardware);
            thread.setArgs(args);
            thread.setRemote(user, host, dir + i);
            thread.setPriority(priority);
            thread.setSlot(slots[i]);

            worker.add(thread);
            thread.start();
        }

    }
    cursor.close();
}

From source file:GeoHazardServices.Inst.java

License:Apache License

private Integer _status(String evtid, Integer raw) {
    /* Check if event exists. */
    DBCollection eqs = db.getCollection("eqs");
    BasicDBObject query = new BasicDBObject("_id", evtid);
    DBObject event = eqs.findOne(query);
    if (event == null)
        return null;
    /* Check if computation has been initiated. */
    Integer p;/*from   w  ww . j a  v  a  2 s .  c om*/
    if (raw > 0) {
        query.append("raw_progress", new BasicDBObject("$ne", null));
        event = eqs.findOne(query);
        if (event == null)
            return STATUS_NO_COMP;
        p = ((BasicDBObject) event).getInt("raw_progress");
    } else {
        query.append("process", new BasicDBObject("$ne", null));
        if (eqs.findOne(query) == null)
            return STATUS_NO_COMP;
        /* Check if computation was started successfully. */
        query.append("process", new BasicDBObject("$size", 1));
        if (eqs.findOne(query) == null)
            return STATUS_FAILED;
        /* Extract the progress from the database object with this clear command ;) */
        p = ((BasicDBObject) ((BasicDBList) event.get("process")).get(0)).getInt("progress");
    }
    return p;
}

From source file:GeoHazardServices.Inst.java

License:Apache License

private Integer _evtset_status(String setid) {
    /* Check if event-set exists. */
    DBCollection evtsets = db.getCollection("evtsets");
    BasicDBObject query = new BasicDBObject("_id", setid);
    DBObject evtset = evtsets.findOne(query);
    if (evtset == null)
        return null;
    if (evtset.get("abort") != null)
        return STATUS_ABORT;
    Double progress = (Double) getField(evtset, "progress");
    if (progress == null)
        return STATUS_NO_COMP;
    return progress.intValue();
}

From source file:GeoHazardServices.Inst.java

License:Apache License

@POST
@Path("/search")
@Produces(MediaType.APPLICATION_JSON)//from ww w  .j  av a2 s.c  o m
public String search(@Context HttpServletRequest request, @FormParam("text") String text,
        @CookieParam("server_cookie") String session) {

    /* check session key and find out if the request comes from an authorized user */
    User user = signedIn(session);

    /* create list of DB objects that contains all desired users */
    BasicDBList users = new BasicDBList();

    for (User curUser : institutions.values())
        users.add(new BasicDBObject("user", curUser.objId));

    if (user != null)
        users.add(new BasicDBObject("user", user.objId));

    DBCollection coll = db.getCollection("eqs");
    DBCollection msgColl = db.getCollection("messages_sent");
    DBCollection recvColl = db.getCollection("messages_received");
    DBCollection evtsetColl = db.getCollection("evtsets");

    List<DBObject> refinements = coll.find(new BasicDBObject("id", text)).toArray();

    BasicDBList list = new BasicDBList();
    list.add(new BasicDBObject("_id", text));
    list.add(new BasicDBObject("id", text));
    list.add(new BasicDBObject("root", text));
    list.add(new BasicDBObject("parent", text));

    for (DBObject obj : refinements) {
        String compId = (String) obj.get("_id");
        list.add(new BasicDBObject("root", compId));
        list.add(new BasicDBObject("parent", compId));
    }

    BasicDBList and = new BasicDBList();
    and.add(new BasicDBObject("$or", list));
    and.add(new BasicDBObject("$or", users));

    BasicDBObject inQuery = new BasicDBObject("$and", and);

    BasicDBObject sort = new BasicDBObject("timestamp", -1);
    sort.put("prop.date", -1);
    DBCursor cursor = coll.find(inQuery).sort(sort);

    List<DBObject> results = new ArrayList<DBObject>();
    results.addAll(cursor.toArray());

    cursor.close();

    /* TODO: generalize field names */
    list = new BasicDBList();
    list.add(new BasicDBObject("EventID", text));
    list.add(new BasicDBObject("ParentId", text));

    for (DBObject obj : refinements) {
        String compId = (String) obj.get("_id");
        list.add(new BasicDBObject("EventID", compId));
        list.add(new BasicDBObject("ParentId", compId));
    }

    and = new BasicDBList();
    and.add(new BasicDBObject("$or", list));
    and.add(new BasicDBObject("SenderID", user.objId));

    inQuery = new BasicDBObject("$and", and);

    cursor = msgColl.find(inQuery).sort(new BasicDBObject("CreatedTime", -1));

    for (DBObject obj : cursor) {

        obj.put("kind", "msg");
        obj.put("Dir", "out");
        results.add(obj);
    }

    cursor.close();

    and = new BasicDBList();
    and.add(new BasicDBObject("$or", list));
    and.add(new BasicDBObject("ReceiverID", user.objId));

    inQuery = new BasicDBObject("$and", and);

    cursor = recvColl.find(inQuery).sort(new BasicDBObject("CreatedTime", -1));

    for (DBObject obj : cursor) {

        obj.put("kind", "msg");
        obj.put("Dir", "in");
        results.add(obj);
    }

    cursor.close();

    DBObject evtset = evtsetColl.findOne(new BasicDBObject("_id", text));
    if (evtset != null) {
        List<DBObject> evts = coll.find(new BasicDBObject("id", new BasicDBObject("$in", evtset.get("evtids"))))
                .toArray();
        results.addAll(evts);
    }

    /* returning only cursor.toArray().toString() makes problems with the date fields */
    return gson.toJsonTree(results).toString();
}

From source file:hulop.hokoukukan.utils.MongoAdapter.java

License:Open Source License

private JSONObject find(DBCollection col, String id) {
    try {//from w  ww .  j a v  a2  s  .  c o m
        DBObject obj = col.findOne(new BasicDBObject("_id", id));
        if (obj != null) {
            return new JSONObject(obj.toString());
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }
    return null;
}

From source file:io.liveoak.mongo.gridfs.GridFSBlobsDirResource.java

License:Open Source License

@Override
public Resource member(RequestContext ctx, String id) {
    DBCollection col = getUserspace().getFilesCollection();
    DBObject result = col.findOne(new ObjectId(id));
    if (result == null) {
        return null;
    }//w w w  .jav a  2s.c  o m

    return new GridFSBlobResource(ctx, this, id, new GridFSDBObject(result), path().append(id));
}

From source file:io.liveoak.mongo.gridfs.GridFSDirectoryResource.java

License:Open Source License

@Override
public Resource member(RequestContext ctx, String id) {

    GridFSResourcePath childPath = path().append(id);

    if (childPath.equals(ctx.resourcePath())) {

        // there are no more intermediary segments - this is the last parent,
        // here we lookup / generate the target GridFS file

        LinkedList<ResourcePath.Segment> segments = new LinkedList(ctx.resourcePath().segments());
        // skip app
        segments.removeFirst();// w  w  w .  j  a v a 2s  . c o m
        // skip gridfsroot
        segments.removeFirst();
        // init meta
        boolean meta = segments.getLast().matrixParameters().containsKey("meta");

        DBCollection col = getUserspace().getFilesCollection();

        DBObject result = null;
        GridFSDBObject last = null;
        int count = 0;
        for (ResourcePath.Segment segment : segments) {
            count++;

            // first segment represents root - root file has empty string for a name, and null parent
            String name = count == 1 ? "" : segment.name();
            ObjectId parentId = count == 1 ? null : last.getId();

            result = col.findOne(new BasicDBObject("filename", name).append("parent", parentId));
            if (result == null) {
                if (ctx.requestType() == RequestType.UPDATE) {
                    // create fileInfo for current segment
                    BasicDBObject fileInfo = new BasicDBObject("filename", name).append("owner",
                            ctx.securityContext().getSubject());
                    if (last != null) {
                        fileInfo.append("parent", last.getId());
                    }

                    // insert for directories but not for files
                    // files get inserted via GridFS API in GridFSBlobResource
                    if (count < segments.size()) {
                        fileInfo.append("dir", true);
                        // autocreate missing parent directories when putting a blob
                        col.insert(fileInfo);
                    }
                    result = fileInfo;
                } else {
                    return null;
                }
            }
            last = new GridFSDBObject(result);
        }

        // finally we got to the fileInfo representing the target resource
        if (last.isTrue("dir")) {
            // if target resource represents a directory
            return newChildDir(path(), last);
        } else {
            // if file
            if (meta) {
                // if last segment has matrix parameter 'meta' return meta info instead of blob content
                return newChildItem(last);
            } else {
                // if no ;meta, then return a blob
                return new GridFSBlobResource(ctx, this, id, last, childPath);
            }
        }
    } else if (childPath.segments().size() == ctx.resourcePath().segments().size()) {
        return null;
    } else {
        // pass-through segment
        return new GridFSDirectoryResource(ctx, this, id, childPath);
    }
}

From source file:io.liveoak.mongo.gridfs.GridFSFilesDirResource.java

License:Open Source License

@Override
public Resource member(RequestContext ctx, String id) {

    // processing the last uri segment
    DBCollection col = parent().getFilesCollection();
    DBObject result = col.findOne(new BasicDBObject("_id", new ObjectId(id)));
    if (result == null) {
        return null;
    }/*ww w . java 2s .c  o m*/

    GridFSDBObject info = new GridFSDBObject(result);
    if (info.isTrue("dir")) {
        // if directory
        return newChildDir(new GridFSResourcePath(id), info);
    } else {
        // if file
        return newChildItem(info);
    }
}