List of usage examples for com.mongodb DBCollection findOne
@Nullable public DBObject findOne(final Object id)
From source file:org.chililog.server.data.RepositoryEntryController.java
License:Apache License
/** * Tries to retrieve the specified entry by the id. If not found, null is returned. * /*from www .j a va2s .c om*/ * @param db * mongoDB connection * @param id * unique id for the document stored in mongoDB * @return <code>RepositoryEntryBO</code> representing the user or null if user is not found * @throws ChiliLogException * if database or data error */ public RepositoryEntryBO tryGet(DB db, ObjectId id) throws ChiliLogException { try { if (db == null) { throw new IllegalArgumentException("db cannot be null"); } if (id == null) { throw new IllegalArgumentException("id cannot be null"); } DBCollection coll = db.getCollection(this.getDBCollectionName()); BasicDBObject condition = new BasicDBObject(); condition.put(BO.DOCUMENT_ID_FIELD_NAME, id); DBObject dbo = coll.findOne(condition); if (dbo == null) { return null; } return new RepositoryEntryBO(dbo); } catch (MongoException ex) { throw new ChiliLogException(ex, Strings.MONGODB_QUERY_ERROR, ex.getMessage()); } }
From source file:org.chililog.server.data.UserController.java
License:Apache License
/** * Tries to retrieve the specified user by the id. If not found, null is returned. * //from w w w. j a v a 2 s. com * @param db * mongoDB connection * @param id * unique id for the document stored in mongoDB * @return <code>UserBO</code> representing the user or null if user is not found * @throws ChiliLogException * if database or data error */ public UserBO tryGet(DB db, ObjectId id) throws ChiliLogException { try { if (db == null) { throw new IllegalArgumentException("db cannot be null"); } if (id == null) { throw new IllegalArgumentException("id cannot be null"); } DBCollection coll = db.getCollection(MONGODB_COLLECTION_NAME); BasicDBObject condition = new BasicDBObject(); condition.put(BO.DOCUMENT_ID_FIELD_NAME, id); DBObject dbo = coll.findOne(condition); if (dbo == null) { return null; } return new UserBO(dbo); } catch (MongoException ex) { throw new ChiliLogException(ex, Strings.MONGODB_QUERY_ERROR, ex.getMessage()); } }
From source file:org.chililog.server.data.UserController.java
License:Apache License
/** * Tries to retrieve the specified user by the username. If not found, null is returned. * //from ww w . j ava2 s . co m * @param db * mongoDB connection * @param username * username of user to retrieve * @return <code>UserBO</code> representing the user or null if user is not found * @throws ChiliLogException * if database or data error */ public UserBO tryGetByUsername(DB db, String username) throws ChiliLogException { try { if (db == null) { throw new IllegalArgumentException("db cannot be null"); } if (StringUtils.isBlank(username)) { throw new IllegalArgumentException("username cannot be blank"); } DBCollection coll = db.getCollection(MONGODB_COLLECTION_NAME); BasicDBObject query = new BasicDBObject(); query.put(UserBO.USERNAME_FIELD_NAME, username); DBObject dbo = coll.findOne(query); if (dbo == null) { return null; } return new UserBO(dbo); } catch (MongoException ex) { throw new ChiliLogException(ex, Strings.MONGODB_QUERY_ERROR, ex.getMessage()); } }
From source file:org.chililog.server.data.UserController.java
License:Apache License
/** * Tries to retrieve the specified user by the email address. If not found, null is returned. * /*from w ww . j a v a 2 s . com*/ * @param db * mongoDB connection * @param emailAddress * Email address of user to retrieve * @return <code>UserBO</code> representing the user or null if user is not found * @throws ChiliLogException * if database or data error */ public UserBO tryGetByEmailAddress(DB db, String emailAddress) throws ChiliLogException { try { if (db == null) { throw new IllegalArgumentException("db cannot be null"); } if (StringUtils.isBlank(emailAddress)) { throw new IllegalArgumentException("emailAddress cannot be blank"); } DBCollection coll = db.getCollection(MONGODB_COLLECTION_NAME); BasicDBObject query = new BasicDBObject(); query.put(UserBO.EMAIL_ADDRESS_FIELD_NAME, emailAddress); DBObject dbo = coll.findOne(query); if (dbo == null) { return null; } return new UserBO(dbo); } catch (MongoException ex) { throw new ChiliLogException(ex, Strings.MONGODB_QUERY_ERROR, ex.getMessage()); } }
From source file:org.codinjutsu.tools.mongo.logic.MongoManager.java
License:Apache License
public DBObject findMongoDocument(ServerConfiguration configuration, MongoCollection mongoCollection, Object _id) {// ww w . j ava2 s . c om MongoClient mongo = null; try { String databaseName = mongoCollection.getDatabaseName(); mongo = createMongoClient(configuration); DB database = mongo.getDB(databaseName); DBCollection collection = database.getCollection(mongoCollection.getName()); return collection.findOne(new BasicDBObject("_id", _id)); } catch (UnknownHostException ex) { throw new ConfigurationException(ex); } finally { if (mongo != null) { mongo.close(); } } }
From source file:org.codinjutsu.tools.nosql.mongo.logic.MongoClient.java
License:Apache License
public DBObject findMongoDocument(ServerConfiguration configuration, MongoCollection mongoCollection, Object _id) {/*ww w . j a v a2 s . c om*/ com.mongodb.MongoClient mongo = null; try { String databaseName = mongoCollection.getDatabaseName(); mongo = createMongoClient(configuration); DB database = mongo.getDB(databaseName); DBCollection collection = database.getCollection(mongoCollection.getName()); return collection.findOne(new BasicDBObject("_id", _id)); } catch (UnknownHostException ex) { throw new ConfigurationException(ex); } finally { if (mongo != null) { mongo.close(); } } }
From source file:org.cryptorchat.json.JsonDBObject.java
License:Apache License
/** * Constructor with collection and objectId * Fetch an object from a collection//w w w. j a v a 2 s . co m * @param collection the input collection * @param objectId the object id to fetch */ public JsonDBObject(final DBCollection collection, final ObjectId objectId) { super(); final DBObject dbo = collection.findOne(objectId); final JsonDBObject tmp = new JsonDBObject(dbo); copy(tmp); }
From source file:org.datanucleus.store.mongodb.MongoDBUtils.java
License:Open Source License
/** * Convenience method that tries to find the object with the specified identity from all DBCollection objects * from the rootCmd and subclasses. Returns the class name of the object with this identity (or null if not found). * @param id The identity//www. java 2s . co m * @param rootCmd ClassMetaData for the root class in the inheritance tree * @param ec ExecutionContext * @param clr ClassLoader resolver * @return The class name of the object with this id */ public static String getClassNameForIdentity(Object id, AbstractClassMetaData rootCmd, ExecutionContext ec, ClassLoaderResolver clr) { Map<String, Set<String>> classNamesByDbCollectionName = new HashMap<String, Set<String>>(); StoreManager storeMgr = ec.getStoreManager(); Set rootClassNames = new HashSet<String>(); rootClassNames.add(rootCmd.getFullClassName()); classNamesByDbCollectionName.put(storeMgr.getNamingFactory().getTableName(rootCmd), rootClassNames); String[] subclassNames = ec.getMetaDataManager().getSubclassesForClass(rootCmd.getFullClassName(), true); if (subclassNames != null) { for (int i = 0; i < subclassNames.length; i++) { AbstractClassMetaData cmd = ec.getMetaDataManager().getMetaDataForClass(subclassNames[i], clr); String collName = storeMgr.getNamingFactory().getTableName(cmd); Set<String> classNames = classNamesByDbCollectionName.get(collName); if (classNames == null) { classNames = new HashSet<String>(); classNamesByDbCollectionName.put(collName, classNames); } classNames.add(cmd.getFullClassName()); } } ManagedConnection mconn = storeMgr.getConnection(ec); try { DB db = (DB) mconn.getConnection(); for (String dbCollName : classNamesByDbCollectionName.keySet()) { // Check each DBCollection for the id PK field(s) Set<String> classNames = classNamesByDbCollectionName.get(dbCollName); DBCollection dbColl = db.getCollection(dbCollName); BasicDBObject query = new BasicDBObject(); if (id instanceof OID) { // TODO Really ought to use cmd of the class using this dbCollection Object key = ((OID) id).getKeyValue(); if (storeMgr.isStrategyDatastoreAttributed(rootCmd, -1)) { query.put("_id", new ObjectId((String) key)); } else { query.put(storeMgr.getNamingFactory().getColumnName(rootCmd, ColumnType.DATASTOREID_COLUMN), key); } } else if (ec.getApiAdapter().isSingleFieldIdentity(id)) { Object key = ec.getApiAdapter().getTargetKeyForSingleFieldIdentity(id); int[] pkNums = rootCmd.getPKMemberPositions(); AbstractMemberMetaData pkMmd = rootCmd.getMetaDataForManagedMemberAtAbsolutePosition(pkNums[0]); String pkPropName = storeMgr.getNamingFactory().getColumnName(pkMmd, ColumnType.COLUMN); query.put(pkPropName, key); } else { int[] pkNums = rootCmd.getPKMemberPositions(); for (int i = 0; i < pkNums.length; i++) { AbstractMemberMetaData pkMmd = rootCmd .getMetaDataForManagedMemberAtAbsolutePosition(pkNums[i]); String pkPropName = storeMgr.getNamingFactory().getColumnName(pkMmd, ColumnType.COLUMN); Object pkVal = IdentityUtils.getValueForMemberInId(id, pkMmd); query.put(pkPropName, pkVal); } } if (NucleusLogger.DATASTORE_NATIVE.isDebugEnabled()) { NucleusLogger.DATASTORE_NATIVE .debug("Retrieving object for " + query + " from DBCollection with name " + dbCollName); } DBObject foundObj = dbColl.findOne(query); if (ec.getStatistics() != null) { // Add to statistics ec.getStatistics().incrementNumReads(); } if (foundObj != null) { if (classNames.size() == 1) { // Only one candidate so return it return classNames.iterator().next(); } else { if (rootCmd.hasDiscriminatorStrategy()) { String disPropName = storeMgr.getNamingFactory().getColumnName(rootCmd, ColumnType.DISCRIMINATOR_COLUMN); String discValue = (String) foundObj.get(disPropName); return ec.getMetaDataManager().getClassNameFromDiscriminatorValue(discValue, rootCmd.getDiscriminatorMetaData()); } else { // Fallback to the root class since no discriminator return rootCmd.getFullClassName(); } } } } } finally { mconn.release(); } return null; }
From source file:org.datanucleus.store.mongodb.MongoDBUtils.java
License:Open Source License
/** * Method to return the DBObject that equates to the provided object. * @param dbCollection The collection in which it is stored * @param op The ObjectProvider//from www .j a va 2 s.c om * @param checkVersion Whether to also check for a particular version * @param originalValue Whether to use the original value of fields (when using nondurable id and doing update). * @return The object (or null if not found) */ public static DBObject getObjectForObjectProvider(DBCollection dbCollection, ObjectProvider op, boolean checkVersion, boolean originalValue) { // Build query object to use as template for the find BasicDBObject query = new BasicDBObject(); AbstractClassMetaData cmd = op.getClassMetaData(); StoreManager storeMgr = op.getExecutionContext().getStoreManager(); if (cmd.getIdentityType() == IdentityType.APPLICATION) { // Application id - Add PK field(s) to the query object int[] pkPositions = cmd.getPKMemberPositions(); for (int i = 0; i < pkPositions.length; i++) { AbstractMemberMetaData pkMmd = cmd.getMetaDataForManagedMemberAtAbsolutePosition(pkPositions[i]); Object value = op.provideField(pkPositions[i]); if (value == null && storeMgr.isStrategyDatastoreAttributed(cmd, pkPositions[i])) { // PK field not yet set, so return null (needs to be attributed in the datastore) return null; } if (storeMgr.isStrategyDatastoreAttributed(cmd, pkPositions[i])) { query.put("_id", new ObjectId((String) value)); } else { Object storeValue = MongoDBUtils.getStoredValueForField(op.getExecutionContext(), pkMmd, value, FieldRole.ROLE_FIELD); query.put(storeMgr.getNamingFactory().getColumnName(pkMmd, ColumnType.COLUMN), storeValue); } } } else if (cmd.getIdentityType() == IdentityType.DATASTORE) { // Datastore id - Add "id" field to the query object OID oid = (OID) op.getInternalObjectId(); if (oid == null && storeMgr.isStrategyDatastoreAttributed(cmd, -1)) { // Not yet set, so return null (needs to be attributed in the datastore) return null; } Object value = oid.getKeyValue(); if (storeMgr.isStrategyDatastoreAttributed(cmd, -1)) { query.put("_id", new ObjectId((String) value)); } else { query.put(storeMgr.getNamingFactory().getColumnName(cmd, ColumnType.DATASTOREID_COLUMN), value); } } else { // Nondurable - Add all basic field(s) to the query object int[] fieldNumbers = cmd.getAllMemberPositions(); for (int i = 0; i < fieldNumbers.length; i++) { AbstractMemberMetaData mmd = cmd.getMetaDataForManagedMemberAtAbsolutePosition(fieldNumbers[i]); RelationType relationType = mmd.getRelationType(op.getExecutionContext().getClassLoaderResolver()); if (relationType == RelationType.NONE) { Object fieldValue = null; if (originalValue) { Object oldValue = op.getAssociatedValue( ObjectProvider.ORIGINAL_FIELD_VALUE_KEY_PREFIX + fieldNumbers[i]); if (oldValue != null) { fieldValue = oldValue; } else { fieldValue = op.provideField(fieldNumbers[i]); } } else { fieldValue = op.provideField(fieldNumbers[i]); } Object storeValue = MongoDBUtils.getStoredValueForField(op.getExecutionContext(), mmd, fieldValue, FieldRole.ROLE_FIELD); query.put(storeMgr.getNamingFactory().getColumnName(mmd, ColumnType.COLUMN), storeValue); } } } if (cmd.hasDiscriminatorStrategy()) { // Add discriminator to the query object query.put(storeMgr.getNamingFactory().getColumnName(cmd, ColumnType.DISCRIMINATOR_COLUMN), cmd.getDiscriminatorValue()); } if (checkVersion && cmd.isVersioned()) { // Add version to the query object Object currentVersion = op.getTransactionalVersion(); VersionMetaData vermd = cmd.getVersionMetaDataForClass(); if (vermd.getFieldName() != null) { // Version field in class AbstractMemberMetaData verMmd = cmd.getMetaDataForMember(vermd.getFieldName()); String fieldName = storeMgr.getNamingFactory().getColumnName(verMmd, ColumnType.COLUMN); query.put(fieldName, currentVersion); } else { // Surrogate version field String fieldName = storeMgr.getNamingFactory().getColumnName(cmd, ColumnType.VERSION_COLUMN); query.put(fieldName, currentVersion); } } if (NucleusLogger.DATASTORE_NATIVE.isDebugEnabled()) { NucleusLogger.DATASTORE_NATIVE.debug("Retrieving object for " + query); } DBObject dbObj = dbCollection.findOne(query); if (op.getExecutionContext().getStatistics() != null) { // Add to statistics op.getExecutionContext().getStatistics().incrementNumReads(); } return dbObj; }
From source file:org.eclipselabs.mongoemf.builders.EObjectBuilderImpl.java
License:Open Source License
/** * Builds an EMF proxy object from the reference DBObject * //w ww . j a va2s. c om * @param collection the collection containing the referencing object * @param dbReference the MongoDB reference - must be of the form { ECLASS_KEY : eClassURI, PROXY_KEY : proxyURI } * @param resourceSet the resource set to use for building the proxy * @param referenceResolvesProxies true if the reference resolves proxies; false otherwise * @return the proxy object when referenceResolvedProxies is true, the resolved object otherwise */ protected EObject buildProxy(DBCollection collection, DBObject dbReference, ResourceSet resourceSet, boolean referenceResolvesProxies) { EObject eObject; URI proxyURI = URI.createURI((String) dbReference.get(Keywords.PROXY_KEY)); URI resolvedProxyURI = uriHandler.resolve(proxyURI); if (!referenceResolvesProxies) { // When referenceResolvedProxies is false, we must resolve the proxy in place and get the referenced object eObject = resourceSet.getEObject(resolvedProxyURI, true); } else { eObject = createEObject(resourceSet, dbReference); ((InternalEObject) eObject).eSetProxyURI(resolvedProxyURI); if (includeAttributesForProxyReferences && proxyURI.isRelative() && "/".equals(proxyURI.fragment())) { DBCollection referenceCollection = null; if (proxyURI.segmentCount() == 3 && proxyURI.segment(0).equals("..")) { referenceCollection = collection.getDB().getCollection(proxyURI.segment(1)); } else if (proxyURI.segmentCount() == 1) { referenceCollection = collection; } if (referenceCollection != null) { DBObject referenceDBObject = new BasicDBObject(Keywords.ID_KEY, new ObjectId(proxyURI.lastSegment())); DBObject referencedDBObject = referenceCollection.findOne(referenceDBObject); if (referencedDBObject != null) { for (EAttribute attribute : eObject.eClass().getEAllAttributes()) { if (!attribute.isTransient() && !FeatureMapUtil.isFeatureMap(attribute)) buildAttribute(referenceCollection, referencedDBObject, null, eObject, attribute); } } } } } return eObject; }