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.semispace.semimeter.dao.mongo.SemiMeterDaoMongo.java

License:Apache License

private void groupedSumsMemory(final int maxResults, final List<GroupedResult> result, final long endMinus15,
        final long endMinus180, final BasicDBObject toFind, final DBObject sortObj) {
    BasicDBObject keys = new BasicDBObject("id", 1);
    DBCollection meterCollection = mongoTemplate.getCollection("meter");
    try (DBCursor dbResult = meterCollection.find(toFind, keys).sort(sortObj).limit(maxResults)) {
        while (dbResult.hasNext()) {
            DBObject row = dbResult.next();
            Object docId = row.get("_id");
            String id = stringOrNull(row.get("id"));

            DBObject doc = meterCollection.findOne(new BasicDBObject("_id", docId));

            DBObject day = (DBObject) doc.get("day");
            DBObject hours = (DBObject) day.get("hours");

            GroupedResult gr = new GroupedResult();
            gr.setCount((Integer) day.get("count"));
            gr.setKey(String.valueOf(id));
            gr.setKeyName("articleId");
            Object pubId = doc.get("publicationId");
            if (pubId != null) {
                gr.setPublicationId(pubId.toString());
            }//from  ww  w.jav  a 2  s .  co  m
            gr.getSplitCounts().put("last180minutes", (Integer) day.get("last180minutes"));
            gr.getSplitCounts().put("last15minutes", (Integer) day.get("last15minutes"));

            Map<String, Integer> trend = gr.getTrend();

            for (String key : hours.keySet()) {
                DBObject hour = (DBObject) hours.get(key);
                trend.put(key, (Integer) hour.get("count"));
            }

            gr.setTrend(trend);
            result.add(gr);

        }
    } catch (Exception e) { // Intentional
        log.error("Got trouble treating the query result", e);
    }
}

From source file:org.semispace.semimeter.dao.mongo.SemiMeterDaoMongo.java

License:Apache License

private void deleteOldMinutes(long before24h, long before180min, long before15min) {
    Calendar cal = new GregorianCalendar();
    cal.setTimeInMillis(before24h);//from   www .  ja v  a  2 s.  c om
    cal.set(Calendar.MILLISECOND, 0);
    cal.set(Calendar.SECOND, 0);
    cal.set(Calendar.MINUTE, 0);
    long targetHour = cal.getTimeInMillis();

    DBCollection meterCollection = mongoTemplate.getCollection("meter");
    DBCursor result = meterCollection.find(new BasicDBObject(), new BasicDBObject("_id", 1));
    while (result.hasNext()) {
        DBObject doc = result.next();

        try {
            //start a new "session" for each document. not sure if this actually helps anything consistency-wise
            meterCollection.getDB().requestStart();

            //and fetch actual object (result only contains _id's)
            doc = meterCollection.findOne(doc); // TODO Double check

            log.trace("cleaning document : {}", doc);
            DBObject day = (DBObject) doc.get("day");
            //log.trace("day: {}", day);
            DBObject hours = (DBObject) day.get("hours");
            //log.trace("hours: {}", hours);
            Set<String> hrSet = new HashSet<String>();
            hrSet.addAll(hours.keySet());
            boolean docChanged = false;

            if (hrSet.isEmpty()) {
                log.trace("no hours in document, remove it: {}", doc);
                meterCollection.remove(new BasicDBObject("_id", doc.get("_id")), WriteConcern.UNACKNOWLEDGED);
            } else {
                for (String h : hrSet) {
                    long hourmillis = Long.valueOf(h);
                    log.trace("checking hour: {}", hourmillis);
                    if (hourmillis < targetHour) {
                        if (log.isTraceEnabled()) {
                            log.trace("removing hour " + h + " because it is older than target" + targetHour);
                        }
                        docChanged = true;
                        DBObject obj = (DBObject) hours.get(h);
                        day.put("count", (Integer) day.get("count") - (Integer) obj.get("count"));
                        hours.removeField(h);
                    } else if (hourmillis == targetHour) {
                        log.trace("current hour is targetHour, check minutes");
                        DBObject currentHour = (DBObject) hours.get(h);
                        DBObject minutes = (DBObject) currentHour.get("minutes");
                        Set<String> keys = new HashSet<String>();
                        keys.addAll(minutes.keySet());
                        for (String m : keys) {
                            long minutemillis = Long.valueOf(m);
                            log.trace("checking minute: {}", minutemillis);
                            if (minutemillis < before24h) {
                                if (log.isTraceEnabled()) {
                                    log.trace("removing minute " + minutemillis + " because it is older than "
                                            + before24h);
                                }

                                docChanged = true;
                                DBObject obj = (DBObject) minutes.get(m);
                                DBObject hourObj = (DBObject) hours.get(h);
                                day.put("count", (Integer) day.get("count") - (Integer) obj.get("count"));
                                hourObj.put("count",
                                        (Integer) hourObj.get("count") - (Integer) obj.get("count"));
                                minutes.removeField(m);
                            }
                        }
                        if (minutes.keySet().isEmpty()) {
                            log.trace("no more minutes, removing hour {}", h);
                            hours.removeField(h);
                            docChanged = true;
                        }
                    }
                }
            }

            docChanged |= updateTrendCounters(doc, before180min, before15min);

            if (docChanged) {
                meterCollection.save(doc);
            }
        } finally {
            meterCollection.getDB().requestDone();
        }
    }
}

From source file:org.shenjitang.mongodbutils.MongoDbOperater.java

public <T> T findOneObj(String dbName, String collName, Map queryMap, Class<T> clazz)
        throws InstantiationException, IllegalAccessException, InvocationTargetException {
    DB db = mongoClient.getDB(dbName);//from  w ww.j  a v a  2s  .  c o  m
    DBCollection coll = db.getCollection(collName);
    BasicDBObject query = new BasicDBObject(queryMap);
    DBObject map = coll.findOne(query);
    if (map == null) {
        return null;
    }
    T obj = clazz.newInstance();
    ConvertUtils.register(new DateConverter(null), Date.class);
    ConvertUtils.register(new IntegerConverter(null), Integer.class);
    BeanUtils.populate(obj, map.toMap());
    return obj;
}

From source file:org.sipfoundry.authcode.AuthCodeManager.java

License:Open Source License

public static AuthCodeConfig getAuthCode(String code) {
    DBCollection entityCol = UnfortunateLackOfSpringSupportFactory.getImdb().getCollection("entity");
    Pattern codePattern = Pattern.compile("AuthCode.*");
    DBObject query = QueryBuilder.start(ID).is(codePattern).and(MongoConstants.AUTH_CODE).is(code).get();
    DBObject result = entityCol.findOne(query);
    if (result != null) {
        AuthCodeConfig conf = new AuthCodeConfig();
        conf.setAuthCode(getStringValue(result, MongoConstants.AUTH_CODE));
        conf.setAuthName(getStringValue(result, MongoConstants.UID));
        conf.setAuthPassword(getStringValue(result, MongoConstants.PASSTOKEN));
        return conf;
    }/* w w  w  .  ja  v  a2  s .  c o m*/
    return null;
}

From source file:org.sipfoundry.sipxconfig.admin.commserver.imdb.DataSetGenerator.java

License:Contributor Agreement License

public DBObject findOrCreate(Replicable entity) {
    DBCollection collection = getDbCollection();
    String id = getEntityId(entity);

    DBObject search = new BasicDBObject();
    search.put(ID, id);//from   ww  w .  j  av a 2 s  .com
    DBObject top = collection.findOne(search);
    if (top == null) {
        top = new BasicDBObject();
        top.put(ID, id);
    }
    if (entity.getIdentity(getSipDomain()) != null) {
        top.put(IDENTITY, entity.getIdentity(getSipDomain()));
    }
    for (String key : entity.getMongoProperties(getSipDomain()).keySet()) {
        top.put(key, entity.getMongoProperties(getSipDomain()).get(key));
    }
    if (entity.isValidUser()) {
        top.put(VALID_USER, true);
    }
    return top;
}

From source file:org.sipfoundry.sipxconfig.admin.commserver.imdb.ReplicationManagerImpl.java

License:Contributor Agreement License

@Override
public void registerTunnels(Location location) {
    DBCollection registrarNode = m_imdb.getDb().getCollection(MongoConstants.STUNNEL_COLLECTION);
    registrarNode.drop();/*  w  w  w.j  a v a 2  s  .com*/

    Location[] locations = m_locationsManager.getLocations();
    if (locations.length > 1) {
        for (int i = 0; i < locations.length; i++) {
            List<Location> otherLocations = new ArrayList<Location>(Arrays.asList(locations));
            otherLocations.remove(locations[i]);

            for (TunnelProvider tunnelProvider : m_tunnelManager.getTunnelProviders()) {
                List<RemoteOutgoingTunnel> tunnels = (List<RemoteOutgoingTunnel>) tunnelProvider
                        .getClientSideTunnels(otherLocations, location);
                for (RemoteOutgoingTunnel tunnel : tunnels) {
                    DBObject search = new BasicDBObject();
                    search.put(ID, tunnel.getName());
                    DBObject server = registrarNode.findOne(search);
                    if (server == null) {
                        server = new BasicDBObject();
                        server.put(ID, tunnel.getName());
                    }
                    server.put(SERVER, "localhost:" + tunnel.getLocalhostPort());
                    server.put(INTERNAL_ADDRESS, tunnel.getRemoteMachineAddress());
                    Location loc = m_locationsManager.getLocationByAddress(tunnel.getRemoteMachineAddress());
                    server.put(ENABLED, loc.isRegistered());
                    registrarNode.save(server);
                }
            }
        }
        DBObject timestamp = new BasicDBObject();
        timestamp.put(ID, "timestamp");
        timestamp.put(TIMESTAMP, new Long(System.currentTimeMillis() / 1000).toString());
        registrarNode.save(timestamp);
    }
}

From source file:org.sipfoundry.sipxconfig.admin.commserver.imdb.ReplicationManagerImpl.java

License:Contributor Agreement License

/**
 * shortcut to remove objects from mongo's imdb database
 *//*from www  .  j a va2s . com*/
private void remove(String collectionName, Object id) {
    DBCollection collection = m_imdb.getDb().getCollection(collectionName);
    DBObject search = new BasicDBObject();
    search.put(ID, id);
    DBObject node = collection.findOne(search);
    //necessary only in case of CallSequences
    //(user delete will trigger CS delete but CS for user may not exist)
    if (node != null) {
        collection.remove(node);
    }
}

From source file:org.sipfoundry.sipxconfig.commserver.imdb.ReplicationManagerImpl.java

License:Contributor Agreement License

protected DBObject findOrCreate(Replicable entity) {
    DBCollection collection = getDbCollection();
    String id = getEntityId(entity);

    DBObject search = new BasicDBObject();
    search.put(ID, id);//from ww w. ja va  2  s  . c  o m
    DBObject top = collection.findOne(search);
    if (top == null) {
        top = new BasicDBObject();
        top.put(ID, id);
    }
    String sipDomain = m_coreContext.getDomainName();
    if (entity.getIdentity(sipDomain) != null) {
        top.put(IDENTITY, entity.getIdentity(sipDomain));
    }
    for (String key : entity.getMongoProperties(sipDomain).keySet()) {
        top.put(key, entity.getMongoProperties(sipDomain).get(key));
    }
    if (entity.isValidUser()) {
        top.put(VALID_USER, true);
    }
    top.put(ENTITY_NAME, entity.getClass().getSimpleName().toLowerCase());
    return top;
}

From source file:org.slc.sli.aggregation.util.IdByNameLookup.java

License:Apache License

/**
 * getAssessmentId - Look up an assessment ID given the assessments identification code ID.
 *
 * @param assmtIDCode - ID code to look up
 * @return assessment identifier/*from www  . j  av a2s.  c  o  m*/
 * @throws UnknownHostException
 */
public static String getAssessmentId(String assmtIDCode) throws UnknownHostException {

    // TODO - parameterize these values.
    Mongo m = new Mongo("localhost");
    DB db = m.getDB("sli");
    DBCollection assessments = db.getCollection("assessment");
    DBObject assmt = assessments
            .findOne(new BasicDBObject("body.assessmentIdentificationCode.ID", assmtIDCode));
    String assmtId = (String) assmt.get("_id");
    return assmtId;
}

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

License:Open Source License

/**
 * selectKeys//from   www  . j a v  a  2  s  .c  o  m
 * <p/>
 * returns all keys that belong to a principal
 *
 * @param username The identifier of the principal
 * @return The OAuth2AccessToken associated with this principal
 */
public OAuth2AccessToken selectKeys(String username) {
    final BasicDBObject query = new BasicDBObject("name", username);
    final DBCollection collection = getCollection(OAUTH_ACCESS_TOKEN);
    DBObject document = collection.findOne(query);
    return (document == null) ? null : (OAuth2AccessToken) deserialize((byte[]) document.get("token"));
}