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.axonframework.mongo.serialization.BSONNode.java

License:Apache License

/**
 * Constructrs a BSONNode structure from the given DBObject structure. The node returned is the root node.
 *
 * @param node The root DBObject node containing the BSON Structure
 * @return The BSONNode representing the root of the BSON structure
 *//* w ww  .j a  va 2s.c  o  m*/
public static BSONNode fromDBObject(DBObject node) {
    if (node.keySet().size() != 1) {
        throw new IllegalArgumentException("Given node should have exactly one attribute");
    }
    String rootName = node.keySet().iterator().next();
    BSONNode rootNode = new BSONNode(decode(rootName));
    Object rootContents = node.get(rootName);
    if (rootContents instanceof List) {
        ((List<?>) rootContents).stream().filter(childElement -> childElement instanceof DBObject)
                .forEach(childElement -> {
                    DBObject dbChild = (DBObject) childElement;
                    if (dbChild.containsField(VALUE_KEY)) {
                        rootNode.setValue((String) dbChild.get(VALUE_KEY));
                    } else {
                        rootNode.addChildNode(fromDBObject(dbChild));
                    }
                });
    } else if (rootContents instanceof DBObject) {
        rootNode.addChildNode(fromDBObject((DBObject) rootContents));
    } else if (rootContents instanceof String) {
        rootNode.setValue((String) rootContents);
    } else {
        throw new IllegalArgumentException(
                "Node in " + rootName + " contains child " + rootContents + " which cannot be parsed");
    }
    return rootNode;
}

From source file:org.axonframework.mongo.serialization.DBObjectHierarchicalStreamWriter.java

License:Apache License

/**
 * Initialize the writer to write the object structure to the given {@code root} DBObject.
 * <p/>/*from   w w w . j  a  va2 s . co m*/
 * Note that the given {@code root} DBObject must not contain any data yet.
 *
 * @param root The root DBObject to which the serialized structure will be added. Must not contain any data.
 */
public DBObjectHierarchicalStreamWriter(DBObject root) {
    Assert.isTrue(root.keySet().isEmpty(), () -> "The given root object must be empty.");
    this.root = root;
}

From source file:org.axonframework.serialization.bson.BSONNode.java

License:Apache License

/**
 * Constructrs a BSONNode structure from the given DBObject structure. The node returned is the root node.
 *
 * @param node The root DBObject node containing the BSON Structure
 * @return The BSONNode representing the root of the BSON structure
 *///from  w ww. j a v  a2s .com
public static BSONNode fromDBObject(DBObject node) {
    if (node.keySet().size() != 1) {
        throw new IllegalArgumentException("Given node should have exactly one attribute");
    }
    String rootName = node.keySet().iterator().next();
    BSONNode rootNode = new BSONNode(decode(rootName));
    Object rootContents = node.get(rootName);
    if (rootContents instanceof List) {
        for (Object childElement : (List) rootContents) {
            if (childElement instanceof DBObject) {
                DBObject dbChild = (DBObject) childElement;
                if (dbChild.containsField(VALUE_KEY)) {
                    rootNode.setValue((String) dbChild.get(VALUE_KEY));
                } else {
                    rootNode.addChildNode(fromDBObject(dbChild));
                }
            }
        }
    } else if (rootContents instanceof DBObject) {
        rootNode.addChildNode(fromDBObject((DBObject) rootContents));
    } else if (rootContents instanceof String) {
        rootNode.setValue((String) rootContents);
    } else {
        throw new IllegalArgumentException(
                "Node in " + rootName + " contains child " + rootContents + " which cannot be parsed");
    }
    return rootNode;
}

From source file:org.axonframework.serialization.bson.DBObjectHierarchicalStreamWriter.java

License:Apache License

/**
 * Initialize the writer to write the object structure to the given <code>root</code> DBObject.
 * <p/>/*w  w w .j av a 2  s  .  c  om*/
 * Note that the given <code>root</code> DBObject must not contain any data yet.
 *
 * @param root The root DBObject to which the serialized structure will be added. Must not contain any data.
 */
public DBObjectHierarchicalStreamWriter(DBObject root) {
    Assert.isTrue(root.keySet().isEmpty(), "The given root object must be empty.");
    this.root = root;
}

From source file:org.broad.igv.plugin.mongocollab.MongoFeatureSource.java

License:Open Source License

/**
 * Check to see if we have an index useful for queries
 * @param buildIndex Whether to build locus index if not found
 *///from  w  ww.  j  a v a 2  s. c  o m
private void checkForLocusIndex(boolean buildIndex) {
    if (buildIndex) {
        ensureLocusIndex(collection);
    }
    //Check to see if we have the index we want
    List<DBObject> indexes = collection.getIndexInfo();
    DBObject neededFields = getLocusIndexKeys();
    for (DBObject index : indexes) {

        boolean isMatchingIndex = true;
        DBObject indexKey = (DBObject) index.get("key");
        for (String key : neededFields.keySet()) {
            boolean hasKey = indexKey.containsField(key);
            if (!hasKey) {
                isMatchingIndex = false;
                break;
            }
            Object value = indexKey.get(key);
            boolean equals = neededFields.get(key).equals(value);
            isMatchingIndex &= equals;
        }

        if (isMatchingIndex) {
            this.hasLocusIndex = true;
            break;
        }
    }
}

From source file:org.canedata.provider.mongodb.entity.MongoEntity.java

License:Apache License

/**
 * Finds the first document in the query and updates it.
 * @see com.mongodb.DBCollection#findAndModify(com.mongodb.DBObject, com.mongodb.DBObject, com.mongodb.DBObject, boolean, com.mongodb.DBObject, boolean, boolean)
 * @param expr/*  w  ww. j a  v  a 2  s. c om*/
 * @return
 */
public Fields findAndUpdate(Expression expr) {
    if (logger.isDebug())
        logger.debug("Finding and updating entity, Database is {0}, Collection is {1} ...", getSchema(),
                getName());

    BasicDBObject options = new BasicDBObject();
    try {
        validateState();

        final BasicDBObject fields = new BasicDBObject();

        MongoExpressionFactory expFactory = new MongoExpressionFactory.Impl();
        BasicDBObject projection = new BasicDBObject();
        Limiter limiter = new Limiter.Default();
        BasicDBObject sorter = new BasicDBObject();

        IntentParser.parse(getIntent(), expFactory, fields, projection, limiter, sorter, options);

        BasicDBObject query = expFactory.parse((MongoExpression) expr);

        if (logger.isDebug())
            logger.debug(
                    "Finding and updating entity, Database is {0}, Collection is {1}, expression is {2}, "
                            + "Projections is {3}, Update is {4}, Sorter is {5}, Options is {6} ...",
                    getSchema(), getName(), query.toString(), projection.toString(), fields.toString(),
                    sorter.toString(), JSON.serialize(options));

        DBObject rlt = getCollection().findAndModify(query, projection, sorter,
                options.getBoolean(Options.FIND_AND_REMOVE, false), fields,
                options.getBoolean(Options.RETURN_NEW, false), options.getBoolean(Options.UPSERT, false));

        if (rlt == null || rlt.keySet().isEmpty())
            return null;

        // alive cache
        if (null != getCache()) {
            invalidateCache(query);
        }

        return new MongoFields(this, getIntent(), (BasicDBObject) rlt).project(projection.keySet());
    } catch (AnalyzeBehaviourException abe) {
        if (logger.isDebug())
            logger.debug(abe, "Analyzing behaviour failure, cause by: {0}.", abe.getMessage());

        throw new RuntimeException(abe);
    } finally {
        if (!options.getBoolean(Options.RETAIN, false))
            getIntent().reset();
    }
}

From source file:org.chililog.server.data.MongoJsonSerializer.java

License:Apache License

@SuppressWarnings({ "unchecked", "rawtypes" })
public static void serialize(Object o, StringBuilder buf) {

    o = Bytes.applyEncodingHooks(o);/*from w w w.  j  a  va 2  s  . co m*/

    if (o == null) {
        buf.append(" null ");
        return;
    }

    if (o instanceof Number) {
        buf.append(o);
        return;
    }

    if (o instanceof String) {
        string(buf, o.toString());
        return;
    }

    if (o instanceof Iterable) {

        boolean first = true;
        buf.append("[ ");

        for (Object n : (Iterable) o) {
            if (first)
                first = false;
            else
                buf.append(" , ");

            serialize(n, buf);
        }

        buf.append("]");
        return;
    }

    if (o instanceof ObjectId) {
        // serialize(new BasicDBObject("$oid", o.toString()), buf);
        string(buf, o.toString());
        return;
    }

    if (o instanceof DBObject) {

        boolean first = true;
        buf.append("{ ");

        DBObject dbo = (DBObject) o;

        for (String name : dbo.keySet()) {
            if (first)
                first = false;
            else
                buf.append(" , ");

            string(buf, name);
            buf.append(" : ");
            serialize(dbo.get(name), buf);
        }

        buf.append("}");
        return;
    }

    if (o instanceof Map) {

        boolean first = true;
        buf.append("{ ");

        Map m = (Map) o;

        for (Map.Entry entry : (Set<Map.Entry>) m.entrySet()) {
            if (first)
                first = false;
            else
                buf.append(" , ");

            string(buf, entry.getKey().toString());
            buf.append(" : ");
            serialize(entry.getValue(), buf);
        }

        buf.append("}");
        return;
    }

    if (o instanceof Date) {
        Date d = (Date) o;
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
        format.setCalendar(new GregorianCalendar(new SimpleTimeZone(0, "GMT")));
        // serialize(new BasicDBObject("$date", format.format(d)), buf);
        string(buf, format.format(d));
        return;
    }

    if (o instanceof DBRefBase) {
        buf.append(o);
        return;
    }

    if (o instanceof Boolean) {
        buf.append(o);
        return;
    }

    if (o instanceof byte[] || o instanceof Binary) {
        buf.append("<Binary Data>");
        return;
    }

    if (o instanceof Pattern) {
        DBObject externalForm = new BasicDBObject();
        externalForm.put("$regex", o.toString());
        externalForm.put("$options", Bytes.regexFlags(((Pattern) o).flags()));
        serialize(externalForm, buf);
        return;
    }

    if (o.getClass().isArray()) {
        buf.append("[ ");

        for (int i = 0; i < Array.getLength(o); i++) {
            if (i > 0)
                buf.append(" , ");
            serialize(Array.get(o, i), buf);
        }

        buf.append("]");
        return;
    }

    if (o instanceof BSONTimestamp) {
        BSONTimestamp t = (BSONTimestamp) o;
        buf.append(t.getTime()).append("|").append(t.getInc());
        return;
    }

    if (o instanceof CodeWScope) {
        CodeWScope c = (CodeWScope) o;

        BasicDBObject temp = new BasicDBObject();
        temp.put("$code", c.getCode());
        temp.put("$scope", c.getScope());
        serialize(temp, buf);
        return;
    }

    if (o instanceof Code) {
        string(buf, ((Code) o).getCode());
        return;
    }

    throw new RuntimeException("json can't serialize type : " + o.getClass());
}

From source file:org.chililog.server.data.RepositoryEntryController.java

License:Apache License

/**
 * Count of number of entries that matches the condition
 * /*from  www  .ja v  a 2 s  . c  o m*/
 * @param db
 *            Database connection
 * @param criteria
 *            Criteria to filter resultset. Fields and Conditions is used.
 * @return List of distinct values for the nominated field.
 */
@SuppressWarnings("rawtypes")
public List executeDistinctQuery(DB db, RepositoryEntryListCriteria criteria) throws ChiliLogException {
    try {
        if (db == null) {
            throw new NullArgumentException("db");
        }
        if (criteria == null) {
            throw new NullArgumentException("criteria");
        }

        DBCollection coll = db.getCollection(this.getDBCollectionName());

        DBObject fields = criteria.getFieldsDbObject();
        if (fields == null || fields.keySet().isEmpty()) {
            throw new IllegalArgumentException("Field is required for a 'distinct' query.");
        }

        String fieldName = null;
        for (String n : fields.keySet()) {
            fieldName = n;
            break;
        }

        DBObject conditions = criteria.getConditionsDbObject();

        return coll.distinct(fieldName, conditions);
    } catch (Exception ex) {
        throw new ChiliLogException(ex, Strings.MONGODB_QUERY_ERROR, ex.getMessage());
    }
}

From source file:org.culturegraph.mf.mongodb.source.MongoDBReader.java

License:Apache License

private void processBasicDBList(final BasicDBList basicDBList) {
    for (final Object object : basicDBList) {
        final DBObject dbObject = (DBObject) object;
        for (final String key : dbObject.keySet()) {
            final Object value = dbObject.get(key);
            if (value instanceof BasicDBList) {
                streamReceiver.startEntity(key.substring(MongoDBKeys.KEY_PREFIX.length()));
                processBasicDBList((BasicDBList) value);
                streamReceiver.endEntity();
            } else {
                streamReceiver.literal(key.substring(MongoDBKeys.KEY_PREFIX.length()), (String) value);
            }/*from ww  w  .jav a2 s.  com*/
        }
    }
}

From source file:org.datanucleus.store.mongodb.MongoDBSchemaHandler.java

License:Open Source License

private DBObject getIndexObjectForIndex(List<DBObject> indices, String idxName, DBObject idxObj,
        boolean unique) {
    if (indices == null || indices.isEmpty()) {
        return null;
    }/* www  .j av a2 s  . c  om*/

    Iterator<DBObject> idxIter = indices.iterator();
    while (idxIter.hasNext()) {
        DBObject index = idxIter.next();
        DBObject obj = null;
        String name = (String) index.get("name");
        if (name.equals(idxName)) {
            obj = index;
            if (unique) {
                boolean flag = (Boolean) index.get("unique");
                if (!flag) {
                    continue;
                }
            }

            boolean equal = true;
            DBObject key = (DBObject) index.get("key");
            if (key.toMap().size() != idxObj.toMap().size()) {
                equal = false;
            } else {
                Iterator<String> indicKeyIter = key.keySet().iterator();
                while (indicKeyIter.hasNext()) {
                    String fieldKey = indicKeyIter.next();
                    Object fieldValue = key.get(fieldKey);
                    if (!idxObj.containsField(fieldKey)) {
                        equal = false;
                    } else {
                        Object idxObjValue = idxObj.get(fieldKey);
                        if (!idxObjValue.equals(fieldValue)) {
                            equal = false;
                        }
                    }
                }
            }
            if (equal) {
                return obj;
            }
        }
    }
    return null;
}