Example usage for com.mongodb DBObject keySet

List of usage examples for com.mongodb DBObject keySet

Introduction

In this page you can find the example usage for com.mongodb DBObject keySet.

Prototype

Set<String> keySet();

Source Link

Document

Returns this object's fields' names

Usage

From source file:org.restheart.handlers.schema.JsonSchemaTransformer.java

License:Open Source License

public static void unescapeSchema(DBObject schema) {
    DBObject unescaped = (DBObject) JsonUtils.unescapeKeys(schema);

    List<String> keys = Lists.newArrayList(schema.keySet().iterator());

    keys.stream().forEach(f -> schema.removeField(f));

    schema.putAll(unescaped);/*from  www  .  ja  v  a2 s  . co  m*/
}

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());
            }//ww w  . ja v  a 2 s  . com
            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 hourlySumsMemory(final Map<String, GroupedResult> result, final DBObject query) {
    DBCursor dbResult = mongoTemplate.getCollection("meter").find(query);
    try {/*from  w  ww .ja v a2s .  c o  m*/
        while (dbResult.hasNext()) {
            DBObject row = dbResult.next();
            DBObject day = (DBObject) row.get("day");
            DBObject hours = (DBObject) day.get("hours");
            String type = (String) row.get("type");
            for (String hourString : hours.keySet()) {
                DBObject hourObject = (DBObject) hours.get(hourString);
                DBObject minutes = (DBObject) hourObject.get("minutes");
                for (String minuteString : minutes.keySet()) {
                    DBObject minuteObject = (DBObject) minutes.get(minuteString);
                    Integer count = (Integer) minuteObject.get("count");
                    GroupedResult gr;
                    if (result.containsKey(minuteString)) {
                        gr = result.get(minuteString);
                    } else {
                        gr = new GroupedResult();
                        Long ts = Long.valueOf(minuteString);
                        String time = df.format(new Date(ts));
                        gr.setKey(time);
                        gr.setKeyName("minute");
                        gr.setCount(0);
                        result.put(minuteString, gr);
                    }
                    gr.setCount(gr.getCount() + count);
                    if (gr.getSplitCounts().containsKey(type)) {
                        gr.getSplitCounts().put(type, gr.getSplitCounts().get(type) + count);
                    } else {
                        gr.getSplitCounts().put(type, count);
                    }
                }
            }
        }
    } finally {
        dbResult.close();
    }

}

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   w  w w.j  a  va  2 s.  c o m
    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.semispace.semimeter.dao.mongo.SemiMeterDaoMongo.java

License:Apache License

private boolean updateTrendCounters(final DBObject doc, final long before180min, final long before15min) {
    long oneHour = 60 * 60 * 1000;
    BasicDBObject day = (BasicDBObject) doc.get("day");
    DBObject hours = (DBObject) day.get("hours");

    int last15Counter = 0;
    int last180Counter = 0;
    for (String h : hours.keySet()) {
        long hourmillis = Long.valueOf(h);
        if (hourmillis >= (before180min - oneHour)) {
            DBObject currentHour = (DBObject) hours.get(h);
            DBObject minutes = (DBObject) currentHour.get("minutes");

            for (String m : minutes.keySet()) {
                long minutemillis = Long.valueOf(m);
                DBObject obj = null;/*from   ww  w  . j  av a2  s .com*/
                if (minutemillis >= before180min) {
                    obj = (DBObject) minutes.get(m);
                    last180Counter += (Integer) obj.get("count");
                }
                if (minutemillis >= before15min) {
                    last15Counter += (Integer) obj.get("count");
                }

            }
        }
    }

    int oldVal = day.get("last15minutes") == null ? 0 : (Integer) day.get("last15minutes");
    boolean objChanged = false;
    if (oldVal != last15Counter) {
        objChanged = true;
        day.put("last15minutes", last15Counter);
    }

    oldVal = day.get("last180minutes") == null ? 0 : (Integer) day.get("last180minutes");
    if (oldVal != last180Counter) {
        objChanged = true;
        day.put("last180minutes", last180Counter);
    }

    return objChanged;
}

From source file:org.sglover.checksum.dao.mongo.MongoChecksumDAO.java

License:Open Source License

@SuppressWarnings("unchecked")
private NodeChecksums toChecksums(DBObject dbObject) {
    NodeChecksums documentChecksums = null;
    if (dbObject != null) {
        String nodeId = (String) dbObject.get("n");
        Long nodeInternalId = (Long) dbObject.get("ni");
        Long nodeVersion = (Long) dbObject.get("v");
        String versionLabel = (String) dbObject.get("l");
        int blockSize = (Integer) dbObject.get("b");
        long numBlocks = (Long) dbObject.get("nb");

        documentChecksums = new NodeChecksums(nodeId, nodeInternalId, nodeVersion, versionLabel, blockSize,
                numBlocks);// w w  w .j  av  a 2 s. c  o  m

        DBObject documentChecksumDBObject = (DBObject) dbObject.get("c");
        for (String hashStr : documentChecksumDBObject.keySet()) {
            List<DBObject> checksumDBObjects = (List<DBObject>) documentChecksumDBObject.get(hashStr);
            for (DBObject checksumDBObject : checksumDBObjects) {
                Checksum checksum = toChecksum(checksumDBObject);
                documentChecksums.addChecksum(checksum);
            }
        }
    }

    return documentChecksums;
}

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

License:Open Source License

private static String getStringValue(DBObject obj, String key) {
    if (obj.keySet().contains(key)) {
        if (obj.get(key) != null) {
            return obj.get(key).toString();
        }/*w w w . ja  v  a 2  s .  c o  m*/
    }
    return null;
}

From source file:org.sipfoundry.commons.userdb.ValidUsers.java

License:Open Source License

private static User extractUser(DBObject obj) {
    if (obj == null) {
        return null;
    }//w  ww  .  j a  v a2s.  com

    User user = new User();
    user.setSysId(getStringValue(obj, ID));
    user.setIdentity(getStringValue(obj, IDENTITY));
    user.setUserName(getStringValue(obj, UID));
    user.setDisplayName(getStringValue(obj, DISPLAY_NAME));
    user.setUri(getStringValue(obj, CONTACT));
    user.setPasstoken(getStringValue(obj, HASHED_PASSTOKEN));
    user.setPintoken(getStringValue(obj, PINTOKEN));
    user.setVoicemailPintoken(getStringValue(obj, VOICEMAIL_PINTOKEN));

    BasicDBList permissions = (BasicDBList) obj.get(PERMISSIONS);
    if (permissions != null) {
        user.setInDirectory(permissions.contains(IMDB_PERM_AA));
        user.setHasVoicemail(permissions.contains(IMDB_PERM_VOICEMAIL));
        user.setCanRecordPrompts(permissions.contains(IMDB_PERM_RECPROMPTS));
        user.setCanTuiChangePin(permissions.contains(IMDB_PERM_TUICHANGEPIN));
    }

    user.setUserBusyPrompt(Boolean.valueOf(getStringValue(obj, USERBUSYPROMPT)));
    user.setMoh(getStringValue(obj, MOH));
    user.setVoicemailTui(getStringValue(obj, VOICEMAILTUI));
    user.setEmailAddress(getStringValue(obj, EMAIL));
    if (obj.keySet().contains(NOTIFICATION)) {
        user.setEmailFormat(getStringValue(obj, NOTIFICATION));
    }
    user.setAttachAudioToEmail(Boolean.valueOf(getStringValue(obj, ATTACH_AUDIO)));

    user.setAltEmailAddress(getStringValue(obj, ALT_EMAIL));
    if (obj.keySet().contains(ALT_NOTIFICATION)) {
        user.setAltEmailFormat(getStringValue(obj, ALT_NOTIFICATION));
    }
    user.setAltAttachAudioToEmail(Boolean.valueOf(getStringValue(obj, ALT_ATTACH_AUDIO)));

    BasicDBList aliasesObj = (BasicDBList) obj.get(ALIASES);
    if (aliasesObj != null) {
        Vector<String> aliases = new Vector<String>();
        for (int i = 0; i < aliasesObj.size(); i++) {
            DBObject aliasObj = (DBObject) aliasesObj.get(i);
            if (aliasObj.get(RELATION).toString().equals(ALIAS)) {
                aliases.add(aliasObj.get(ALIAS_ID).toString());
            }
        }
        user.setAliases(aliases);
    }

    if (obj.keySet().contains(SYNC)) {
        ImapInfo imapInfo = new ImapInfo();
        imapInfo.setSynchronize(Boolean.valueOf(getStringValue(obj, SYNC)));
        imapInfo.setHost(getStringValue(obj, HOST));
        imapInfo.setPort(getStringValue(obj, PORT));
        imapInfo.setUseTLS(Boolean.valueOf(getStringValue(obj, TLS)));
        imapInfo.setAccount(getStringValue(obj, ACCOUNT));
        imapInfo.setPassword(getStringValue(obj, PASSWD));
        user.setImapInfo(imapInfo);
        if (imapInfo.isSynchronize()) {
            user.setEmailFormat(EmailFormats.FORMAT_IMAP);
            user.setAttachAudioToEmail(true);
        }
        // // If account isn't set, use the e-mail username
        if (imapInfo.getAccount() == null || imapInfo.getAccount().length() == 0) {
            if (user.getEmailAddress() != null) {
                imapInfo.setAccount(user.getEmailAddress().split("@")[0]);
            }
        }
    }

    // contact info related data
    user.setCellNum(getStringValue(obj, CELL_PHONE_NUMBER));
    user.setHomeNum(getStringValue(obj, HOME_PHONE_NUMBER));
    user.setConfEntryIM(getStringValue(obj, CONF_ENTRY_IM));
    user.setConfExitIM(getStringValue(obj, CONF_EXIT_IM));
    user.setVMEntryIM(getStringValue(obj, LEAVE_MESSAGE_BEGIN_IM));
    user.setVMExitIM(getStringValue(obj, LEAVE_MESSAGE_END_IM));
    user.setCallIM(getStringValue(obj, CALL_IM));
    user.setCallFromAnyIM(getStringValue(obj, CALL_FROM_ANY_IM));
    user.setImEnabled(Boolean.valueOf(getStringValue(obj, IM_ENABLED)));
    user.setJid(getStringValue(obj, IM_ID));
    user.setAltJid(getStringValue(obj, ALT_IM_ID));
    user.setImDisplayName(getStringValue(obj, IM_DISPLAY_NAME));
    user.setOnthePhoneMessage(getStringValue(obj, IM_ON_THE_PHONE_MESSAGE));
    user.setAdvertiseOnCallStatus(Boolean.valueOf(getStringValue(obj, IM_ADVERTISE_ON_CALL_STATUS)));
    user.setShowOnCallDetails(Boolean.valueOf(getStringValue(obj, IM_SHOW_ON_CALL_DETAILS)));
    user.setCompanyName(getStringValue(obj, COMPANY_NAME));
    user.setJobDepartment(getStringValue(obj, JOB_DEPT));
    user.setJobTitle(getStringValue(obj, JOB_TITLE));
    user.setFaxNumber(getStringValue(obj, FAX_NUMBER));

    // office details
    user.setOfficeStreet(getStringValue(obj, OFFICE_STREET));
    user.setOfficeCity(getStringValue(obj, OFFICE_CITY));
    user.setOfficeState(getStringValue(obj, OFFICE_STATE));
    user.setOfficeZip(getStringValue(obj, OFFICE_ZIP));
    user.setOfficeCountry(getStringValue(obj, OFFICE_COUNTRY));

    // home details
    user.setHomeCity(getStringValue(obj, HOME_CITY));
    user.setHomeState(getStringValue(obj, HOME_STATE));
    user.setHomeZip(getStringValue(obj, HOME_ZIP));
    user.setHomeCountry(getStringValue(obj, HOME_COUNTRY));
    user.setHomeStreet(getStringValue(obj, HOME_STREET));

    user.setAvatar(getStringValue(obj, AVATAR));

    // active greeting related data
    if (obj.keySet().contains(ACTIVEGREETING)) {
        user.setActiveGreeting(getStringValue(obj, ACTIVEGREETING));
    }

    user.setPlayDefaultVmOption(Boolean.valueOf(getStringValue(obj, PLAY_DEFAULT_VM)));

    // personal attendant related data
    if (obj.keySet().contains(PERSONAL_ATT)) {
        BasicDBObject pao = (BasicDBObject) obj.get(PERSONAL_ATT);
        String operator = getStringValue(pao, OPERATOR);
        String language = getStringValue(pao, LANGUAGE);
        Map<String, String> menu = new HashMap<String, String>();
        StringBuilder validDigits = new StringBuilder(10);
        BasicDBList buttonsList = (BasicDBList) pao.get(BUTTONS);
        if (buttonsList != null) {
            for (int i = 0; i < buttonsList.size(); i++) {
                DBObject button = (DBObject) buttonsList.get(i);
                if (button != null) {
                    menu.put(getStringValue(button, DIALPAD), getStringValue(button, ITEM));
                    validDigits.append(getStringValue(button, DIALPAD));
                }
            }
        }
        user.setPersonalAttendant(new PersonalAttendant(language, operator, menu, validDigits.toString()));
    }

    // distribution lists
    if (obj.keySet().contains(DISTRIB_LISTS)) {
        Distributions distribs = new Distributions();
        BasicDBList distribList = (BasicDBList) obj.get(DISTRIB_LISTS);
        if (distribList != null) {
            for (int i = 0; i < distribList.size(); i++) {
                DBObject distrib = (DBObject) distribList.get(i);
                if (distrib != null) {
                    distribs.addList(getStringValue(distrib, DIALPAD),
                            StringUtils.split(getStringValue(distrib, ITEM), " "));
                }
            }
        }
        user.setDistributions(distribs);
    }

    if (user.isInDirectory()) {
        buildDialPatterns(user);
    }

    return user;
}

From source file:org.slc.sli.domain.MongoEntity.java

License:Apache License

@SuppressWarnings("unchecked")
private static Map<String, List<Entity>> extractEmbeddedData(DBObject dbObj) {
    Map<String, List<Entity>> embeddedData = new HashMap<String, List<Entity>>();

    for (String key : dbObj.keySet()) {
        if (EmbeddedDocumentRelations.getSubDocuments().contains(key)) {
            List<DBObject> values = (List<DBObject>) dbObj.get(key);
            List<Entity> subEntityList = new ArrayList<Entity>();
            for (DBObject subEntity : values) {
                subEntityList.add(fromDBObject(subEntity));
            }/*from www.  ja  va2  s .  com*/
            embeddedData.put(key, subEntityList);
        }
    }

    return embeddedData;
}

From source file:org.slc.sli.domain.MongoEntity.java

License:Apache License

@SuppressWarnings("unchecked")
private static Map<String, List<Map<String, Object>>> extractDenormalizedData(DBObject dbObj) {
    String type = (String) dbObj.get("type");
    Map<String, List<Map<String, Object>>> denormalized = new HashMap<String, List<Map<String, Object>>>();

    for (String key : dbObj.keySet()) {
        if (EmbeddedDocumentRelations.isDenormalization(type, key)) {
            List<Map<String, Object>> values = (List<Map<String, Object>>) dbObj.get(key);
            denormalized.put(key, values);
        }/*from ww w. jav  a2  s.  c o m*/
    }

    return denormalized;
}