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:com.github.dbourdette.otto.web.controller.api.ApiController.java

License:Apache License

@RequestMapping(value = "/jsonapi/sources/{name}/events", method = RequestMethod.GET, headers = "Accept=application/json")
public void eventsJson(@PathVariable String name, @RequestParam(required = false) Integer page,
        @RequestParam(required = false) String from, @RequestParam(required = false) String to,
        HttpServletRequest request, HttpServletResponse response) throws IOException {
    if (!Security.hasSource(name)) {
        throw new UnauthorizedException("You don't have access to this source");
    }//from   w ww . j a v a2  s  . com

    DateTime fromDate = parseDateTime(from), toDate = parseDateTime(to);

    if (fromDate != null && fromDate.isAfter(new DateTime())) {
        throw new BadRequestException("from Date must be in past");
    }

    if (fromDate != null && toDate != null && fromDate.isAfter(toDate)) {
        throw new BadRequestException("from Date must be before to Date");
    }

    IntervalEventsQuery query = new IntervalEventsQuery(fromDate, toDate);
    query.readFilters(request, FILTER_QUERY_PREFIX);
    query.setPage(page);
    query.setPageSize(JSONAPI_PAGE_SIZE);

    Source source = Source.findByName(name);
    Page<DBObject> events = source.findEvents(query);

    ObjectMapper mapper = new ObjectMapper();
    mapper.getSerializationConfig().set(SerializationConfig.Feature.INDENT_OUTPUT, true);

    ObjectNode root = mapper.createObjectNode();

    root.put("count", events.getTotalCount());
    root.put("page", Page.fixPage(page));
    root.put("pageCount", events.getPageCount());

    ArrayNode eventsNode = root.putArray("events");

    for (DBObject event : events.getItems()) {
        ObjectNode eventNode = mapper.createObjectNode();

        for (String key : event.keySet()) {
            if (!"_id".equals(key)) {
                eventNode.put(key, formatValue(event.get(key)));
            }
        }

        eventsNode.add(eventNode);
    }

    response.setCharacterEncoding("UTF-8");
    response.setContentType("application/json");
    mapper.writeValue(response.getOutputStream(), root);
}

From source file:com.github.maasdi.mongo.wrapper.NoAuthMongoClientWrapper.java

License:Apache License

protected List<String> setupAllTags(BasicDBList members) {
    HashSet<String> tempTags = new HashSet<String>();

    if (members != null && members.size() > 0) {
        for (int i = 0; i < members.size(); i++) {
            Object m = members.get(i);

            if (m != null) {
                DBObject tags = (DBObject) ((DBObject) m).get("tags"); //$NON-NLS-1$
                if (tags == null) {
                    continue;
                }//w  w w  .j  av  a  2  s  .  c  o m

                for (String tagName : tags.keySet()) {
                    String tagVal = tags.get(tagName).toString();
                    String combined = quote(tagName) + " : " + quote(tagVal); //$NON-NLS-1$
                    tempTags.add(combined);
                }
            }
        }
    }

    return new ArrayList<String>(tempTags);
}

From source file:com.github.maasdi.mongo.wrapper.NoAuthMongoClientWrapper.java

License:Apache License

protected List<DBObject> checkForReplicaSetMembersThatSatisfyTagSets(List<DBObject> tagSets,
        BasicDBList members) {//from   ww  w.  j a  va  2 s  .c  om
    List<DBObject> satisfy = new ArrayList<DBObject>();
    if (members != null && members.size() > 0) {
        for (int i = 0; i < members.size(); i++) {
            Object m = members.get(i);

            if (m != null) {
                DBObject tags = (DBObject) ((DBObject) m).get("tags"); //$NON-NLS-1$
                if (tags == null) {
                    continue;
                }

                for (int j = 0; j < tagSets.size(); j++) {
                    boolean match = true;
                    DBObject toMatch = tagSets.get(j);

                    for (String tagName : toMatch.keySet()) {
                        String tagValue = toMatch.get(tagName).toString();

                        // does replica set member m's tags contain this tag?
                        Object matchVal = tags.get(tagName);

                        if (matchVal == null) {
                            match = false; // doesn't match this particular tag set
                            // no need to check any other keys in toMatch
                            break;
                        }

                        if (!matchVal.toString().equals(tagValue)) {
                            // rep set member m's tags has this tag, but it's value does not
                            // match
                            match = false;

                            // no need to check any other keys in toMatch
                            break;
                        }
                    }

                    if (match) {
                        // all tag/values present and match - add this member (only if its
                        // not already there)
                        if (!satisfy.contains(m)) {
                            satisfy.add((DBObject) m);
                        }
                    }
                }
            }
        }
    }

    return satisfy;
}

From source file:com.github.nlloyd.hornofmongo.adaptor.Mongo.java

License:Open Source License

@JSFunction
public Object find(final String ns, final Object query, final Object fields, Integer limit, Integer skip,
        Integer batchSize, Integer options) {
    Object result = null;/*from ww  w. j ava2 s .co  m*/

    Object rawQuery = BSONizer.convertJStoBSON(query, false);
    Object rawFields = BSONizer.convertJStoBSON(fields, false);
    DBObject bsonQuery = null;
    DBObject bsonFields = null;
    if (rawQuery instanceof DBObject)
        bsonQuery = (DBObject) rawQuery;
    if (rawFields instanceof DBObject)
        bsonFields = (DBObject) rawFields;
    com.mongodb.DB db = innerMongo.getDB(ns.substring(0, ns.indexOf('.')));
    String collectionName = ns.substring(ns.indexOf('.') + 1);
    if ("$cmd".equals(collectionName)) {
        try {
            if (options == 0)
                options = innerMongo.getOptions();
            //GC: 16/11/15 fixed for v3
            //                CommandResult cmdResult = db.command(bsonQuery, options,
            CommandResult cmdResult = db.command(bsonQuery, innerMongo.getReadPreference(),
                    HornOfMongoBSONEncoder.FACTORY.create());
            //GC: 16/11/15 removed for v3
            //                handlePostCommandActions(db, bsonQuery);
            Object jsCmdResult = BSONizer.convertBSONtoJS(mongoScope, cmdResult);
            result = MongoRuntime
                    .call(new NewInstanceAction(mongoScope, "InternalCursor", new Object[] { jsCmdResult }));
        } catch (NoSuchElementException nse) {
            // thrown when db.runCommand() called (no arguments)
            CommandResult failedCmdResult = db.command(this.hosts.iterator().next().toString());
            failedCmdResult.put("ok", Boolean.FALSE);
            failedCmdResult.put("errmsg", "no such cmd: ");
            Object jsFailedCmdResult = BSONizer.convertBSONtoJS(mongoScope, failedCmdResult);
            result = MongoRuntime.call(
                    new NewInstanceAction(mongoScope, "InternalCursor", new Object[] { jsFailedCmdResult }));
        } catch (MongoException me) {
            handleMongoException(me);
        }
    } else {
        DBCollection collection = db.getCollection(collectionName);
        collection.setDBEncoderFactory(HornOfMongoBSONEncoder.FACTORY);
        collection.setDBDecoderFactory(HornOfMongoBSONDecoder.FACTORY);
        DBObject specialFields = null;
        if (bsonQuery.get("query") instanceof DBObject) {
            specialFields = bsonQuery;
            bsonQuery = (DBObject) bsonQuery.get("query");
        }
        DBCursor cursor = collection.find(bsonQuery, bsonFields).skip(skip).batchSize(batchSize).limit(limit)
                .addOption(options);
        if (specialFields != null) {
            for (String key : specialFields.keySet()) {
                if (!"query".equals(key))
                    cursor.addSpecial(key, specialFields.get(key));
            }
        }

        InternalCursor jsCursor = (InternalCursor) MongoRuntime
                .call(new NewInstanceAction(mongoScope, "InternalCursor", new Object[] { cursor }));
        result = jsCursor;
    }

    return result;
}

From source file:com.github.rutledgepaulv.testsupport.CriteriaSerializer.java

License:Open Source License

private DBObject applyInternal(DBObject object) {
    object.keySet().stream()
            .forEach(key -> object.put(key,
                    object.get(key) instanceof Enum<?> ? object.get(key).toString()
                            : object.get(key) instanceof DBObject ? applyInternal((DBObject) object.get(key))
                                    : object.get(key) instanceof Collection<?>
                                            ? applyList((Collection<?>) object.get(key))
                                            : object.get(key)));

    return object;
}

From source file:com.grallandco.impl.MongoCAPIBehavior.java

License:Apache License

/**
 * Load the documents into MongoDB/*from   www  . j  a  va  2  s  .  com*/
 * @param database
 * @param docs
 * @return
 */
@Override
public List<Object> bulkDocs(String database, List<Map<String, Object>> docs) {

    DB db = MongoConnectionManager.getMongoClient().getDB(getDatabaseName(database));
    List<Object> result = new ArrayList<Object>();

    logger.log(Level.INFO, String.format("Replicating %d document(s)", docs.size()));

    for (Map<String, Object> doc : docs) {
        Map<String, Object> meta = (Map<String, Object>) doc.get("meta");
        Map<String, Object> json = (Map<String, Object>) doc.get("json");
        String base64 = (String) doc.get("base64");

        if (meta == null) {
            // if there is no meta-data section, there is nothing we can do
            logger.log(Level.WARNING, "Document without meta in bulk_docs, ignoring....");
            continue;
        } else if ("non-JSON mode".equals(meta.get("att_reason"))
                || "invalid_json".equals(meta.get("att_reason"))) {
            // optimization, this tells us the body isn't json
            json = new HashMap<String, Object>();
        } else if (json == null && base64 != null) {

            // use Java 6/7 XML Base64 library
            // TODO : see if it makes sense to use Java8 Library java.util.Base64
            String jsonValue = new String(DatatypeConverter.parseBase64Binary(base64));
            DBObject o = (DBObject) JSON.parse(jsonValue);
            DBObject mongoJson = BasicDBObjectBuilder.start("_id", meta.get("id")).get();

            // need to check if json keys do not contains . or $ and replace them with other char
            // TODO : Copy the doc, put _id at the top and clean key names
            Set<String> keys = o.keySet();
            for (String key : keys) {
                String newKey = key;
                newKey = newKey.replace(".", MongoDBCouchbaseReplicator.dotReplacement);
                newKey = newKey.replace("$", MongoDBCouchbaseReplicator.dollarReplacement);
                mongoJson.put(newKey, o.get(key));
            }

            // add meta data if configured
            if (MongoDBCouchbaseReplicator.keepMeta) {
                mongoJson.put("meta", new BasicDBObject(meta));
            }

            String collectionName = MongoDBCouchbaseReplicator.defaultCollection;
            if (o.get(MongoDBCouchbaseReplicator.collectionField) != null) {
                collectionName = (String) o.get(MongoDBCouchbaseReplicator.collectionField);
            }

            try {

                if (MongoDBCouchbaseReplicator.replicationType.equalsIgnoreCase("insert_only")) {
                    // this will raise an exception
                    db.getCollection(collectionName).insert(mongoJson);
                } else { // insert & update
                    db.getCollection(collectionName).save(mongoJson);
                }

            } catch (MongoException e) {

                if (e.getCode() == 11000) {
                    logger.log(Level.INFO, "Not replicating updated document " + meta.get("id"));
                } else {
                    logger.log(Level.SEVERE, e.getMessage());
                }

            }

        }

        String id = (String) meta.get("id");
        String rev = (String) meta.get("rev");
        Map<String, Object> itemResponse = new HashMap<String, Object>();
        itemResponse.put("id", id);
        itemResponse.put("rev", rev);
        result.add(itemResponse);
    }

    return result;
}

From source file:com.groupon.jenkins.mongo.JenkinsEmbeddedMapper.java

License:Open Source License

private boolean isFullySerializedObject(DBObject cachedStub, Mapper mapper) {
    return cachedStub.keySet().size() > 2 && cachedStub.containsField(mapper.ID_KEY)
            && cachedStub.containsField(mapper.CLASS_NAME_FIELDNAME);
}

From source file:com.hangum.tadpole.mongodb.core.utils.MongoDBTableColumn.java

License:Open Source License

/**
 * TableView?   ? ?. /* ww w .  jav a  2s.c  o  m*/
 *
 * @param dbObject
 * @param mapColumns
 * @return
 */
public static Map<Integer, String> getTabelColumnView(DBObject dbObject, Map<Integer, String> mapColumns) {
    if (dbObject == null)
        return mapColumns;

    int i = mapColumns.size();
    for (String name : dbObject.keySet()) {
        if (!mapColumns.containsValue(name)) {
            mapColumns.put(i, name);
            i++;
        }
    }

    return mapColumns;
}

From source file:com.hangum.tadpole.mongodb.core.utils.MongoDBTableColumn.java

License:Open Source License

/**
 * TableViewer?   ?? ./*from w  ww.ja  v a 2 s.  c o m*/
 * 
 * @return
 */
public static Map<Integer, String> getTabelColumnView(DBObject dbObject) {
    Map<Integer, String> map = new HashMap<Integer, String>();

    if (dbObject == null)
        return map;

    int i = 0;
    Set<String> names = dbObject.keySet();
    for (String name : names) {
        map.put(i, name);
        i++;
    }

    return map;
}

From source file:com.hangum.tadpole.mongodb.core.utils.MongoDBTableColumn.java

License:Open Source License

/**
 * mongodb table column /*from  ww  w .j  a v a  2 s .c  om*/
 * 
 * @param indexInfo
 * @param dbObject
 * @return
 */
public static List<CollectionFieldDAO> tableColumnInfo(List<DBObject> indexInfo, DBObject dbObject) {
    Map<String, Boolean> mapIndex = new HashMap<String, Boolean>();

    // key list parsing
    for (DBObject indexObject : indexInfo) {
        String realKey = StringUtils.substringBetween(indexObject.get("key").toString(), "\"", "\""); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
        mapIndex.put(realKey, true);
    }

    // column info
    List<CollectionFieldDAO> retColumns = new ArrayList<CollectionFieldDAO>();
    try {
        // ? ? ? ..
        if (dbObject == null)
            return retColumns;

        Set<String> names = dbObject.keySet();
        for (String name : names) {
            CollectionFieldDAO column = new CollectionFieldDAO(name,
                    dbObject.get(name) != null ? dbObject.get(name).getClass().getSimpleName() : "Unknow", //$NON-NLS-1$
                    mapIndex.get(name) != null ? "YES" : "NO"); //$NON-NLS-1$ //$NON-NLS-2$
            // ???  ? ?
            if (dbObject.get(name) instanceof BasicDBObject) {
                makeTableColumn(column, (BasicDBObject) dbObject.get(name));
            }

            retColumns.add(column);
        }
    } catch (Exception e) {
        logger.error("get MongoDB table column info", e); //$NON-NLS-1$
    }

    return retColumns;
}