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.socialhistoryservices.security.MongoTokenStore.java

License:Open Source License

public OAuth2AccessToken readAccessToken(String tokenValue) {

    OAuth2AccessToken accessToken = (isFresh(tokenValue)) ? this.accessTokenStore.get(tokenValue) : null;
    if (accessToken == null) {
        // select token_id, token from oauth_access_token where token_id = ?
        final BasicDBObject query = new BasicDBObject("token_id", tokenValue);
        final DBCollection collection = getCollection(OAUTH_ACCESS_TOKEN);
        DBObject document = collection.findOne(query);
        if (document == null) {
        } else {//from   w ww. j a  v  a  2 s.c  om
            accessToken = deserialize((byte[]) document.get("token"));
            this.accessTokenStore.put(tokenValue, accessToken);
            expiration(tokenValue);
        }
    }
    return accessToken;
}

From source file:org.socialhistoryservices.security.MongoTokenStore.java

License:Open Source License

public OAuth2Authentication readAuthentication(OAuth2AccessToken token) {

    final String tokenValue = token.getValue();
    OAuth2Authentication authentication = (isFresh(tokenValue)) ? this.authenticationTokenStore.get(tokenValue)
            : null;//from w  ww  .  jav  a 2 s .com
    if (authentication == null) {
        // select token_id, authentication from oauth_access_token where token_id = ?
        final BasicDBObject query = new BasicDBObject();
        query.put("token_id", token.getValue());
        final DBCollection collection = getCollection(OAUTH_ACCESS_TOKEN);
        final DBObject document = collection.findOne(query);
        if (document == null) {
        } else {
            authentication = deserialize((byte[]) document.get("authentication"));
            this.authenticationTokenStore.put(tokenValue, authentication);
            expiration(tokenValue);
        }
    }
    return authentication;
}

From source file:org.socialhistoryservices.security.MongoTokenStore.java

License:Open Source License

public ExpiringOAuth2RefreshToken readRefreshToken(String token) {

    // select token_id, token from oauth_refresh_token where token_id = ?
    ExpiringOAuth2RefreshToken refreshToken = null;
    final BasicDBObject query = new BasicDBObject("token_id", token);
    final DBCollection collection = getCollection(OAUTH_REFRESH_TOKEN);
    final DBObject document = collection.findOne(query);
    if (document == null) {
    } else {//from   w w  w.  ja  va2 s . co  m
        refreshToken = deserialize((byte[]) document.get("token"));
    }
    return refreshToken;
}

From source file:org.socialhistoryservices.security.MongoTokenStore.java

License:Open Source License

public OAuth2Authentication readAuthentication(ExpiringOAuth2RefreshToken token) {

    // select token_id, authentication from oauth_refresh_token where token_id = ?
    OAuth2Authentication authentication = null;
    final BasicDBObject query = new BasicDBObject("token_id", token.getValue());
    final DBCollection collection = getCollection(OAUTH_REFRESH_TOKEN);
    final DBObject document = collection.findOne(query);
    if (document == null) {
    } else {//from   www.ja  v a  2 s. c om
        authentication = deserialize((byte[]) document.get("authentication"));
    }
    return authentication;
}

From source file:org.socialhistoryservices.security.MongoUserDetailService.java

License:Open Source License

public void createUser(MongoUserDetails user) {

    if (user.getPassword() != null)
        user.setPassword(HashPassword.encrypt(HASH, user.getPassword()));

    final DBCollection coll = coll();
    BasicDBObject query = new BasicDBObject("username", user.getUsername());
    DBObject tmp = coll.findOne(query);
    if (tmp != null) {
        if (user.getPassword() == null) {
            user.setPassword((String) tmp.get("password"));
        }//from   w ww .  j av a2 s .  com
        if (user.getAuthorities().size() == 0) {
            BasicDBList authorities = (BasicDBList) tmp.get("authorities");
            for (Object authority : authorities) {
                user.getAuthorities()
                        .add(new org.socialhistoryservices.security.MongoAuthority((String) authority));
            }
        }
    }

    BasicDBObject document = new BasicDBObject();
    document.put("username", user.getUsername());
    document.put("password", user.getPassword());
    document.put("enabled", user.isEnabled());
    document.put("accountNonExpired", user.isAccountNonExpired());
    document.put("accountNonLocked", user.isAccountNonLocked());
    document.put("credentialsNonExpired", user.isCredentialsNonExpired());
    BasicDBList authorities = new BasicDBList();
    for (GrantedAuthority authority : user.getAuthorities()) {
        authorities.add(authority.getAuthority());
    }
    document.put("authorities", authorities);
    final WriteResult result = coll.update(query, document, true, false, WriteConcern.SAFE);
    if (result.getN() == 0)
        log.error(new Exception("Adding the user failed: " + result.getError()));
    log.info("Persisted:\n" + document.toString());
}

From source file:org.socialhistoryservices.security.MongoUserDetailService.java

License:Open Source License

/**
 * There should normally only be one matching user.
 * Authorities are mapped to Spring roles
 *///w  ww  .  jav  a  2 s .com
private UserDetails getUser(String username) {

    final DBCollection coll = coll();
    final BasicDBObject query = new BasicDBObject("username", username);
    final DBObject document = coll.findOne(query);
    if (document == null)
        return null;
    final MongoUserDetails userDetails = new MongoUserDetails();

    userDetails.setUsername((String) document.get("username"));
    userDetails.setPassword((String) document.get("password"));
    userDetails.setEnabled(getBoolean(document.get("enabled"), MongoUserDetails.ENABLED));
    userDetails.setAccountNonExpired(
            getBoolean(document.get("accountNonExpired"), MongoUserDetails.ACCOUNT_NON_EXPIRED));
    userDetails.setAccountNonLocked(
            getBoolean(document.get("accountNonLocked"), MongoUserDetails.ACCOUNT_NON_LOCKED));
    userDetails.setCredentialsNonExpired(
            getBoolean(document.get("credentialsNonExpired"), MongoUserDetails.CREDENTIALS_NON_EXPIRED));

    Object o = document.get("authorities");
    if (o != null) {
        BasicDBList authorities = (BasicDBList) o;
        List<GrantedAuthority> grants = new ArrayList<GrantedAuthority>(authorities.size());
        for (Object authority : authorities) {
            MongoAuthority grant = new MongoAuthority(ROLE_PREFIX + authority);
            grants.add(grant);
        }
        userDetails.setAuthorities(grants);
    }
    return userDetails;
}

From source file:org.springframework.data.mongodb.crossstore.MongoChangeSetPersister.java

License:Apache License

public Object persistState(ChangeSetBacked entity, ChangeSet cs) throws DataAccessException {
    if (cs == null) {
        log.debug("Flush: changeset was null, nothing to flush.");
        return 0L;
    }/*from  w ww  .  j a  v  a  2s. c  om*/

    if (log.isDebugEnabled()) {
        log.debug("Flush: changeset: {}", cs.getValues());
    }

    String collName = getCollectionNameForEntity(entity.getClass());
    if (mongoTemplate.getCollection(collName) == null) {
        mongoTemplate.createCollection(collName);
    }

    for (String key : cs.getValues().keySet()) {
        if (key != null && !key.startsWith("_") && !key.equals(ChangeSetPersister.ID_KEY)) {
            Object value = cs.getValues().get(key);
            final DBObject dbQuery = new BasicDBObject();
            dbQuery.put(ENTITY_ID, getPersistentId(entity, cs));
            dbQuery.put(ENTITY_CLASS, entity.getClass().getName());
            dbQuery.put(ENTITY_FIELD_NAME, key);
            DBObject dbId = mongoTemplate.execute(collName, new CollectionCallback<DBObject>() {
                public DBObject doInCollection(DBCollection collection)
                        throws MongoException, DataAccessException {
                    return collection.findOne(dbQuery);
                }
            });
            if (value == null) {
                if (log.isDebugEnabled()) {
                    log.debug("Flush: removing: {}", dbQuery);
                }
                mongoTemplate.execute(collName, new CollectionCallback<Object>() {
                    public Object doInCollection(DBCollection collection)
                            throws MongoException, DataAccessException {
                        collection.remove(dbQuery);
                        return null;
                    }
                });
            } else {
                final DBObject dbDoc = new BasicDBObject();
                dbDoc.putAll(dbQuery);
                if (log.isDebugEnabled()) {
                    log.debug("Flush: saving: {}", dbQuery);
                }
                mongoTemplate.getConverter().write(value, dbDoc);
                dbDoc.put(ENTITY_FIELD_CLASS, value.getClass().getName());
                if (dbId != null) {
                    dbDoc.put("_id", dbId.get("_id"));
                }
                mongoTemplate.execute(collName, new CollectionCallback<Object>() {
                    public Object doInCollection(DBCollection collection)
                            throws MongoException, DataAccessException {
                        collection.save(dbDoc);
                        return null;
                    }
                });
            }
        }
    }
    return 0L;
}

From source file:org.springframework.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>() {
        @Override//from  w w w . j  a  va  2  s . c om
        public DBObject doInDB(DB con) throws MongoException, DataAccessException {
            DBCollection dbCollection = con.getCollection(getCollectionName(persistentEntity));

            DBObject dbo = new BasicDBObject();
            if (hasNumericalIdentifier) {
                dbo.put(MONGO_ID_FIELD, key);
            } else {
                if (key instanceof ObjectId) {
                    dbo.put(MONGO_ID_FIELD, key);
                } else {
                    dbo.put(MONGO_ID_FIELD, new ObjectId(key.toString()));
                }

            }
            return dbCollection.findOne(dbo);

        }
    });
}

From source file:org.unitedid.shibboleth.attribute.resolver.provider.dataConnector.MongoDbDataConnector.java

License:Apache License

/**
 * Retrieve attributes from the database based on the query
 *
 * @param q the query to run//  w  ww.j  a v  a  2  s .c o m
 * @return a list of attributes
 * @throws AttributeResolutionException if an error occurs during query execution
 */
protected Map<String, BaseAttribute> retrieveAttributesFromDatabase(String q)
        throws AttributeResolutionException {
    Map<String, BaseAttribute> resolvedAttributes = new HashMap<String, BaseAttribute>();
    try {
        log.debug("Data connector {} retrieving attributes from: {}", getId(), db.getMongo().getAddress());
        DBCollection collection = db.getCollection(mongoCollection);
        DBObject query = (DBObject) JSON.parse(q);
        resolvedAttributes = processCollectionResult(collection.findOne(query));

    } catch (MongoException e) {
        log.error("Data connector {} exception", getId(), e);
        throw new AttributeResolutionException("MongoDB data connector " + getId() + " unable to execute query",
                e);
    }

    return resolvedAttributes;
}

From source file:org.waveprotocol.box.server.persistence.mongodb.MongoDbStore.java

License:Apache License

@Override
public SignerInfo getSignerInfo(byte[] signerId) {
    DBObject query = getDBObjectForSignerId(signerId);
    DBCollection signerInfoCollection = getSignerInfoCollection();
    DBObject signerInfoDBObject = signerInfoCollection.findOne(query);

    // Sub-class contract specifies return null when not found
    SignerInfo signerInfo = null;/*from  ww  w  .j  a  va  2  s  . co  m*/

    if (signerInfoDBObject != null) {
        byte[] protobuff = (byte[]) signerInfoDBObject.get("protoBuff");
        try {
            signerInfo = new SignerInfo(ProtocolSignerInfo.parseFrom(protobuff));
        } catch (InvalidProtocolBufferException e) {
            LOG.log(Level.SEVERE, "Couldn't parse the protobuff stored in MongoDB: " + protobuff, e);
        } catch (SignatureException e) {
            LOG.log(Level.SEVERE, "Couldn't parse the certificate chain or domain properly", e);
        }
    }
    return signerInfo;
}