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.opendaylight.controller.samples.onftappingapp.TappingApp.java

License:Apache License

public PortChain getPortChainById(String portChainId) throws NotFoundException {
    DBCollection table = database.getCollection(DatabaseNames.getPortChainTableName());

    // Create a query to look for the existing PortChain by ID
    BasicDBObject searchQuery = new BasicDBObject();
    searchQuery.put("_id", new ObjectId(portChainId));

    // Check whether the port chain exists
    DBObject dbObj = table.findOne(searchQuery);
    if (dbObj == null)
        throw new NotFoundException();

    // Construct a new port chain from the DBobject and return it
    PortChain portChain = new PortChain(dbObj);
    return portChain;
}

From source file:org.opendaylight.controller.samples.onftappingapp.TappingApp.java

License:Apache License

public static CaptureDev getCaptureDevById(String captureDevId) throws NotFoundException {
    DBCollection table = database.getCollection(DatabaseNames.getCaptureDevTableName());

    // Create a query to look for the existing CaptureDev by ID
    BasicDBObject searchQuery = new BasicDBObject();
    searchQuery.put("_id", new ObjectId(captureDevId));

    // Check whether the captureDev exists
    DBObject dbObj = table.findOne(searchQuery);
    if (dbObj == null)
        throw new NotFoundException();

    // Construct a caprture dev from the DBobject and return it
    CaptureDev captureDev = new CaptureDev(dbObj);
    return captureDev;
}

From source file:org.openspotlight.storage.mongodb.MongoStorageSessionImpl.java

License:Open Source License

private DBObject findReferenceOrReturnNull(final PropertyContainer element) {
    DBObject basicDBObject = null;/* www  .  j ava  2  s  .  c  o m*/

    StorageNode node;
    if (element instanceof StorageNode) {
        node = (StorageNode) element;
    } else if (element instanceof StorageLink) {
        node = ((StorageLink) element).getSource();
    } else {
        throw new IllegalStateException();
    }

    final Pair<StorageNode, DBObject> p = Pair.<StorageNode, DBObject>newPair(node, null,
            Pair.PairEqualsMode.K1);
    if (transientObjects.get(element.getPartition()).contains(p)) {
        for (final Pair<StorageNode, DBObject> pair : transientObjects.get(element.getPartition())) {
            if (pair.equals(p)) {
                basicDBObject = pair.getK2();
                break;
            }
        }
    }
    NodeKey key;
    String collectionName;
    key = node.getKey();
    collectionName = node.getType();

    final Pair<NodeKey, DBObject> p1 = newPair(key, null, Pair.PairEqualsMode.K1);
    final int idx = objectCache.indexOf(p1);
    if (idx != -1) {
        basicDBObject = objectCache.get(idx).getK2();
    }
    if (basicDBObject == null) {
        final DBCollection coll = getCachedCollection(element.getPartition(), collectionName);
        final BasicDBObject queryObject = new BasicDBObject();
        queryObject.put(ID, key.getKeyAsString());
        basicDBObject = coll.findOne(queryObject);
        if (basicDBObject == null) {
            basicDBObject = new BasicDBObject();
            basicDBObject.put(ID, key.getKeyAsString());
        }
        objectCache.addFirst(newPair(key, basicDBObject, Pair.PairEqualsMode.K1));
        if (objectCache.size() > maxCacheSize) {
            objectCache.removeLast();
        }
    }
    return basicDBObject;
}

From source file:org.openspotlight.storage.mongodb.MongoStorageSessionImpl.java

License:Open Source License

public StorageNode internalGetNode(String key, Partition partition) throws Exception {
    final String nodeType = getNodeType(key);
    final BasicDBObject parameter = new BasicDBObject();
    parameter.put(ID, key);/*from  www . j  a  v  a 2  s .co  m*/
    final DBCollection collection = getCachedCollection(partition, nodeType);
    final DBObject result = collection.findOne(parameter);
    return convertToNode(partition, result);

}

From source file:org.opentaps.notes.repository.impl.NoteRepositoryImpl.java

License:Open Source License

/** {@inheritDoc} */
public Note getNoteById(String noteId) {
    DBCollection coll = getNotesCollection();
    BasicDBObject query = new BasicDBObject(NoteMongo.MONGO_ID_FIELD, new ObjectId(noteId));
    DBObject noteDoc = coll.findOne(query);
    return dbObjectToNote(noteDoc);
}

From source file:org.qi4j.entitystore.mongodb.MongoMapEntityStoreMixin.java

License:Apache License

@Override
public void applyChanges(MapChanges changes) throws IOException {
    db.requestStart();/*from   ww w .j  av a2  s  .  c om*/
    final DBCollection entities = db.getCollection(collectionName);

    changes.visitMap(new MapChanger() {

        @Override
        public Writer newEntity(final EntityReference ref, EntityDescriptor entityDescriptor)
                throws IOException {
            return new StringWriter(1000) {

                @Override
                public void close() throws IOException {
                    super.close();

                    String jsonState = toString();
                    System.out.println("############################################");
                    try {
                        System.out.println(new JSONObject(jsonState).toString(2));
                    } catch (JSONException ex) {
                        ex.printStackTrace();
                    }
                    System.out.println("############################################");
                    DBObject bsonState = (DBObject) JSON.parse(jsonState);

                    BasicDBObject entity = new BasicDBObject();
                    entity.put(IDENTITY_COLUMN, ref.identity());
                    entity.put(STATE_COLUMN, bsonState);
                    entities.save(entity, writeConcern);
                }

            };
        }

        @Override
        public Writer updateEntity(final EntityReference ref, EntityDescriptor entityDescriptor)
                throws IOException {
            return new StringWriter(1000) {

                @Override
                public void close() throws IOException {
                    super.close();

                    DBObject bsonState = (DBObject) JSON.parse(toString());

                    BasicDBObject entity = new BasicDBObject();
                    entity.put(IDENTITY_COLUMN, ref.identity());
                    entity.put(STATE_COLUMN, bsonState);
                    entities.update(byIdentity(ref), entity, true, false, writeConcern);
                }

            };
        }

        @Override
        public void removeEntity(EntityReference ref, EntityDescriptor entityDescriptor)
                throws EntityNotFoundException {
            DBObject entity = entities.findOne(byIdentity(ref));
            if (entity == null) {
                throw new EntityNotFoundException(ref);
            }
            entities.remove(entity, writeConcern);
        }

    });

    db.requestDone();
}

From source file:org.restheart.test.performance.LoadGetPT.java

License:Open Source License

/**
*
*//* www .java2  s.  com*/
public void dbdirectdoc() {
    final Database dbDao = new DbsDAO();
    DBCollection dbcoll = dbDao.getCollectionLegacy(db, coll);

    ObjectId oid;
    String sid;

    if (ObjectId.isValid(doc)) {
        sid = null;
        oid = new ObjectId(doc);
    } else {
        // the id is not an object id
        sid = doc;
        oid = null;
    }

    BasicDBObject query;

    if (oid != null) {
        query = new BasicDBObject("_id", oid);
    } else {
        query = new BasicDBObject("_id", sid);
    }

    DBObject data;

    try {
        data = dbcoll.findOne(query);
    } catch (Exception e) {
        System.out.println("error: " + e.getMessage());
        return;
    }

    assertNotNull(data);

    if (printData) {
        System.out.println(data);
    }
}

From source file:org.restlet.example.ext.oauth.server.LoginPageServerResource.java

License:LGPL

@Get("html")
@Post("html")/*from   w  w w . ja  v  a 2  s. c  o m*/
public Representation getPage() {
    getLogger().info("Get Login");
    String userId = getQueryValue("user_id");
    HashMap<String, Object> data = new HashMap<String, Object>();
    if (userId != null && !userId.isEmpty()) {
        String password = getQueryValue("password");
        getLogger().info("User=" + userId + ", Pass=" + password);
        DBCollection users = OAuth2Sample.getDefaultDB().getCollection("users");
        DBObject user = users.findOne(new BasicDBObject("_id", userId).append("password", password));
        if (user != null) {
            getLogger().info("Session: " + getAuthSession().getClient().getClientId());
            getAuthSession().setScopeOwner(userId);
            String uri = getQueryValue("continue");
            getLogger().info("URI: " + uri);
            redirectTemporary(uri);
            return new EmptyRepresentation();
        } else {
            data.put("error", "Authentication failed.");
            data.put("error_description", "ID or Password is invalid.");
        }
    }

    String continueURI = getQueryValue("continue");
    TemplateRepresentation response = getLoginPage("login.html");
    data.put("continue", continueURI);
    response.setDataModel(data);

    return response;
}

From source file:org.restlet.example.ext.oauth.server.MongoAuthenticatedUser.java

License:LGPL

@Override
public char[] getPassword() {
    DBCollection users = OAuth2Sample.getDefaultDB().getCollection("users");
    DBObject user = users.findOne(new BasicDBObject("_id", getId()));
    if (user != null) {
        return user.get("password").toString().toCharArray();
    }/*from   w ww .j  a va 2 s  . co m*/
    return null;
}

From source file:org.s1.mongodb.MongoDBQueryHelper.java

License:Apache License

/**
 * Select exactly one record from collection
 *
 * @param c/*from w ww  .  ja  v a  2s.c o  m*/
 * @param search
 * @throws NotFoundException
 * @throws MoreThanOneFoundException
 * @return
 */
public static Map<String, Object> get(CollectionId c, Map<String, Object> search)
        throws NotFoundException, MoreThanOneFoundException {
    ensureOnlyOne(c, search);

    DBCollection coll = MongoDBConnectionHelper.getConnection(c.getDatabase()).getCollection(c.getCollection());
    Map<String, Object> m = MongoDBFormat.toMap(coll.findOne(MongoDBFormat.fromMap(search)));
    if (LOG.isDebugEnabled())
        LOG.debug("MongoDB get result (" + c + ", search:" + search + "\n\t> " + m);
    return m;
}