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:org.eclipselabs.mongoemf.handlers.MongoURIHandlerImpl.java

License:Open Source License

@Override
public boolean exists(URI uri, Map<?, ?> options) {
    if (uri.query() != null)
        return false;

    try {/*from w  w  w.j av  a 2s. c o  m*/
        DBCollection collection = getCollection(uri, options);
        return collection.findOne(new BasicDBObject(Keywords.ID_KEY, MongoUtils.getID(uri))) != null;
    } catch (Throwable exception) {
        return false;
    }
}

From source file:org.eclipselabs.restlet.mongo.MongoResource.java

License:Open Source License

@Get
public JSONObject getJSON() throws MongoException, UnknownHostException {
    DBCollection collection = getCollection();
    DBObject dbObject = collection
            .findOne(new BasicDBObject("_id", new ObjectId((String) getRequestAttributes().get("id"))));

    if (dbObject != null)
        return new JSONObject(dbObject.toMap());
    else {/*from  w w  w .  j  a va 2  s .  c om*/
        getResponse().setStatus(Status.CLIENT_ERROR_NOT_FOUND);
        return null;
    }
}

From source file:org.exoplatform.mongo.service.impl.MongoBase64CryptDe.java

License:Open Source License

@Override
public boolean validate(String user, String password) {
    boolean isValid = false;
    if (!StringUtils.isNullOrEmpty(user) && !StringUtils.isNullOrEmpty(password)) {
        DB db = mongo.getDB("credentials");
        DBCollection collection = db.getCollection("data_service");
        DBObject credentials = new BasicDBObject();
        credentials.put("user", user.toLowerCase());
        credentials.put("password", EncodingUtils.encodeBase64(password));

        if (collection.findOne(credentials) != null) {
            isValid = true;//from w ww.ja v a2s .  c o  m
        }
    }
    return isValid;
}

From source file:org.exoplatform.mongo.service.impl.MongoRestServiceImpl.java

License:Open Source License

@GET
@Path("/databases/{dbName}/collections/{collName}/documents/{docId}")
@Override/*  w  w  w  .  j a  va  2 s.  c  o m*/
public Response findDocument(@PathParam("dbName") String dbName, @PathParam("collName") String collName,
        @PathParam("docId") String docId, @Context HttpHeaders headers, @Context UriInfo uriInfo,
        @Context SecurityContext securityContext) {
    if (shutdown) {
        return Response.status(ServerError.SERVICE_UNAVAILABLE.code())
                .entity(ServerError.SERVICE_UNAVAILABLE.message()).build();
    }
    Response response = null;
    String user = null;
    try {
        Credentials credentials = authenticateAndAuthorize(headers, uriInfo, securityContext);
        user = credentials.getUserName();
        String dbNamespace = constructDbNamespace(credentials.getUserName(), dbName);
        if (mongo.getDatabaseNames().contains(dbNamespace)) {
            DB db = mongo.getDB(dbNamespace);
            authServiceAgainstMongo(db);
            if (db.getCollectionNames().contains(collName)) {
                DBCollection dbCollection = db.getCollection(collName);
                DBObject query = new BasicDBObject();
                query.put("_id", new ObjectId(docId));
                DBObject found = dbCollection.findOne(query);
                if (found != null) {
                    org.exoplatform.mongo.entity.response.Document document = new org.exoplatform.mongo.entity.response.Document();
                    document.setJson(JSON.serialize(found));
                    response = Response.ok(document).build();
                } else {
                    response = Response.status(ClientError.NOT_FOUND.code())
                            .entity(docId + " does not exist in " + collName).build();
                }
            } else {
                response = Response.status(ClientError.NOT_FOUND.code())
                        .entity(collName + " does not exist in " + dbName).build();
            }
        } else {
            response = Response.status(ClientError.NOT_FOUND.code()).entity(dbName + " does not exist").build();
        }
    } catch (Exception exception) {
        response = lobException(exception, headers, uriInfo);
    } finally {
        updateStats(user, "findDocument");
    }
    return response;
}

From source file:org.exoplatform.mongo.service.impl.MongoRestServiceImpl.java

License:Open Source License

@PUT
@Path("/databases/{dbName}/collections/{collName}/documents/{docId}")
@Override/*from  w  w w  .j av  a2  s .  c  om*/
public Response updateDocument(@PathParam("dbName") String dbName, @PathParam("collName") String collName,
        @PathParam("docId") String docId, org.exoplatform.mongo.entity.request.Document document,
        @Context HttpHeaders headers, @Context UriInfo uriInfo, @Context SecurityContext securityContext) {
    if (shutdown) {
        return Response.status(ServerError.SERVICE_UNAVAILABLE.code())
                .entity(ServerError.SERVICE_UNAVAILABLE.message()).build();
    }
    Response response = null;
    String user = null;
    try {
        Credentials credentials = authenticateAndAuthorize(headers, uriInfo, securityContext);
        user = credentials.getUserName();
        String dbNamespace = constructDbNamespace(credentials.getUserName(), dbName);
        if (mongo.getDatabaseNames().contains(dbNamespace)) {
            DB db = mongo.getDB(dbNamespace);
            authServiceAgainstMongo(db);
            if (db.getCollectionNames().contains(collName)) {
                DBCollection dbCollection = db.getCollection(collName);
                String documentJson = document.getJson();
                if (!StringUtils.isNullOrEmpty(documentJson)) {
                    DBObject incomingDocument = (DBObject) JSON.parse(documentJson);
                    DBObject query = new BasicDBObject();
                    query.put("_id", new ObjectId(docId));
                    DBObject persistedDocument = dbCollection.findOne(query);
                    URI statusSubResource = null;
                    try {
                        if (persistedDocument == null) {
                            dbCollection.insert(incomingDocument, WriteConcern.SAFE);
                            statusSubResource = uriInfo.getBaseUriBuilder().path(MongoRestServiceImpl.class)
                                    .path("/databases/" + dbName + "/collections/" + collName + "/documents/"
                                            + ((DBObject) incomingDocument.get("_id")))
                                    .build();
                            response = Response.created(statusSubResource).build();
                        } else {
                            dbCollection.save(incomingDocument);
                            statusSubResource = uriInfo
                                    .getBaseUriBuilder().path(MongoRestServiceImpl.class).path("/databases/"
                                            + dbName + "/collections/" + collName + "/documents/" + docId)
                                    .build();
                            response = Response.ok(statusSubResource).build();
                        }
                    } catch (DuplicateKey duplicateObject) {
                        response = Response.status(ClientError.BAD_REQUEST.code())
                                .entity("Document already exists and could not be created").build();
                    }
                } else {
                    response = Response.status(ClientError.BAD_REQUEST.code())
                            .entity("Document JSON is required").build();
                }
            } else {
                response = Response.status(ClientError.NOT_FOUND.code())
                        .entity(collName + " does not exist in " + dbName).build();
            }
        } else {
            response = Response.status(ClientError.NOT_FOUND.code()).entity(dbName + " does not exist").build();
        }
    } catch (Exception exception) {
        response = lobException(exception, headers, uriInfo);
    } finally {
        updateStats(user, "updateDocument");
    }
    return response;
}

From source file:org.fastmongo.odm.bson.repository.BsonMongoTemplate.java

License:Apache License

private byte[] doFindById(String collectionName, Object id) {
    DBCollection collection = getCollection(collectionName);
    DBObject db = collection.findOne(new BasicDBObject(MongoUtils.OBJECT_ID_KEY, id));
    if (db == null) {
        return null;
    }//from   www.  j  av  a2s .co m

    return getData(db);
}

From source file:org.forgerock.openidm.repo.mongodb.impl.query.PredefinedQueries.java

License:Open Source License

/**
 * Query by primary key, the OpenIDM identifier.
 * //from  ww w.  j av  a 2 s.  co m
 * @param id the OpenIDM identifier for an object
 * @param database a handle to the MongoDB database object. No other thread must operate on this concurrently.
 * @return The DBObject if found, null if not found.
 * @throws BadRequestException if the passed identifier or type are invalid
 */
public DBObject getByID(final String id, DBCollection collection) throws BadRequestException {
    if (id == null) {
        throw new BadRequestException("Query by id the passed id was null.");
    }

    BasicDBObject query = new BasicDBObject().append(DocumentUtil.TAG_ID, id);
    DBObject doc = collection.findOne(query);
    logger.trace("Query: {} Result: {}", query, doc);
    return doc;
}

From source file:org.grails.datastore.mapping.mongo.engine.MongoEntityPersister.java

License:Apache License

@Override
protected DBObject retrieveEntry(final PersistentEntity persistentEntity, String family,
        final Serializable key) {
    return mongoTemplate.execute(new DbCallback<DBObject>() {
        public DBObject doInDB(DB con) throws MongoException, DataAccessException {
            DBCollection dbCollection = con.getCollection(getCollectionName(persistentEntity));
            return dbCollection.findOne(createDBObjectWithKey(key));
        }//from w w w .j  a  v  a 2  s.c  om
    });
}

From source file:org.grails.datastore.mapping.mongo.engine.MongoEntityPersister.java

License:Apache License

@Override
public void updateEntry(final PersistentEntity persistentEntity, final EntityAccess ea, final Object key,
        final DBObject entry) {
    mongoTemplate.execute(new DbCallback<Object>() {
        public Object doInDB(DB con) throws MongoException, DataAccessException {
            @SuppressWarnings("hiding")
            String collectionName = getCollectionName(persistentEntity, entry);
            DBCollection dbCollection = con.getCollection(collectionName);
            DBObject dbo = createDBObjectWithKey(key);

            if (isVersioned(ea)) {
                // TODO this should be done with a CAS approach if possible
                DBObject previous = dbCollection.findOne(dbo);
                checkVersion(ea, previous, persistentEntity, key);
            }//from  w  w  w.  ja va 2s .  co m

            MongoSession mongoSession = (MongoSession) session;
            dbCollection.update(dbo, entry, false, false, mongoSession.getWriteConcern());
            return null;
        }
    });
}

From source file:org.graylog2.cluster.Cluster.java

License:Open Source License

private boolean getBooleanNodeAttribute(String nodeId, String key) {
    DBCollection coll = localServer.getMongoConnection().getDatabase().getCollection("server_values");

    BasicDBObject q = new BasicDBObject();
    q.put("type", key);
    q.put("server_id", nodeId);

    DBObject result = coll.findOne(q);
    if (result == null) {
        return false;
    }/*from  ww  w. j a  v a 2s  .co  m*/

    if (result.get("value").equals(true)) {
        return true;
    }

    return false;
}