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.springframework.data.mongodb.core.MongoTemplate.java

License:Apache License

protected Object insertDBObject(final String collectionName, final DBObject dbDoc, final Class<?> entityClass) {

    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("Inserting DBObject containing fields: {} in collection: {}", dbDoc.keySet(),
                collectionName);/*w  ww .j av  a2 s  . c  o m*/
    }

    return execute(collectionName, new CollectionCallback<Object>() {
        public Object doInCollection(DBCollection collection) throws MongoException, DataAccessException {
            MongoAction mongoAction = new MongoAction(writeConcern, MongoActionOperation.INSERT, collectionName,
                    entityClass, dbDoc, null);
            WriteConcern writeConcernToUse = prepareWriteConcern(mongoAction);
            WriteResult writeResult = writeConcernToUse == null ? collection.insert(dbDoc)
                    : collection.insert(dbDoc, writeConcernToUse);
            handleAnyWriteResultErrors(writeResult, dbDoc, MongoActionOperation.INSERT);
            return dbDoc.get(ID_FIELD);
        }
    });
}

From source file:org.springframework.data.mongodb.core.MongoTemplate.java

License:Apache License

protected Object saveDBObject(final String collectionName, final DBObject dbDoc, final Class<?> entityClass) {

    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("Saving DBObject containing fields: {}", dbDoc.keySet());
    }/*from   ww  w .j  a  v a2 s .c  o  m*/

    return execute(collectionName, new CollectionCallback<Object>() {
        public Object doInCollection(DBCollection collection) throws MongoException, DataAccessException {
            MongoAction mongoAction = new MongoAction(writeConcern, MongoActionOperation.SAVE, collectionName,
                    entityClass, dbDoc, null);
            WriteConcern writeConcernToUse = prepareWriteConcern(mongoAction);
            WriteResult writeResult = writeConcernToUse == null ? collection.save(dbDoc)
                    : collection.save(dbDoc, writeConcernToUse);
            handleAnyWriteResultErrors(writeResult, dbDoc, MongoActionOperation.SAVE);
            return dbDoc.get(ID_FIELD);
        }
    });
}

From source file:org.springframework.data.mongodb.core.query.Criteria.java

License:Apache License

public DBObject getCriteriaObject() {

    if (this.criteriaChain.size() == 1) {
        return criteriaChain.get(0).getSingleCriteriaObject();
    } else if (CollectionUtils.isEmpty(this.criteriaChain) && !CollectionUtils.isEmpty(this.criteria)) {
        return getSingleCriteriaObject();
    } else {/*from ww w . ja v a  2  s .c  o  m*/
        DBObject criteriaObject = new BasicDBObject();
        for (Criteria c : this.criteriaChain) {
            DBObject dbo = c.getSingleCriteriaObject();
            for (String k : dbo.keySet()) {
                setValue(criteriaObject, k, dbo.get(k));
            }
        }
        return criteriaObject;
    }
}

From source file:org.springframework.data.mongodb.core.query.Update.java

License:Apache License

/**
 * Creates an {@link Update} instance from the given {@link DBObject}. Allows to explicitly exclude fields from making
 * it into the created {@link Update} object. Note, that this will set attributes directly and <em>not</em> use
 * {@literal $set}. This means fields not given in the {@link DBObject} will be nulled when executing the update. To
 * create an only-updating {@link Update} instance of a {@link DBObject}, call {@link #set(String, Object)} for each
 * value in it./*from   ww  w .  j  av  a 2  s.c o  m*/
 *
 * @param object the source {@link DBObject} to create the update from.
 * @param exclude the fields to exclude.
 * @return
 */
public static Update fromDBObject(DBObject object, String... exclude) {

    Update update = new Update();
    List<String> excludeList = Arrays.asList(exclude);

    for (String key : object.keySet()) {

        if (excludeList.contains(key)) {
            continue;
        }

        Object value = object.get(key);
        update.modifierOps.put(key, value);
        if (isKeyword(key) && value instanceof DBObject) {
            update.keysToUpdate.addAll(((DBObject) value).keySet());
        } else {
            update.keysToUpdate.add(key);
        }
    }

    return update;
}

From source file:org.springframework.data.mongodb.core.QueryMapper.java

License:Apache License

/**
 * Replaces the property keys used in the given {@link DBObject} with the appropriate keys by using the
 * {@link PersistentEntity} metadata.//from   ww  w.jav  a  2s. c  om
 * 
 * @param query must not be {@literal null}.
 * @param entity can be {@literal null}.
 * @return
 */
public DBObject getMappedObject(DBObject query, MongoPersistentEntity<?> entity) {

    DBObject newDbo = new BasicDBObject();

    for (String key : query.keySet()) {

        String newKey = key;
        Object value = query.get(key);

        if (isIdKey(key, entity)) {
            if (value instanceof DBObject) {
                DBObject valueDbo = (DBObject) value;
                if (valueDbo.containsField("$in") || valueDbo.containsField("$nin")) {
                    String inKey = valueDbo.containsField("$in") ? "$in" : "$nin";
                    List<Object> ids = new ArrayList<Object>();
                    for (Object id : (Iterable<?>) valueDbo.get(inKey)) {
                        ids.add(convertId(id));
                    }
                    valueDbo.put(inKey, ids.toArray(new Object[ids.size()]));
                } else if (valueDbo.containsField("$ne")) {
                    valueDbo.put("$ne", convertId(valueDbo.get("$ne")));
                } else {
                    value = getMappedObject((DBObject) value, null);
                }
            } else {
                value = convertId(value);
            }
            newKey = "_id";
        } else if (key.matches(N_OR_PATTERN)) {
            // $or/$nor
            Iterable<?> conditions = (Iterable<?>) value;
            BasicBSONList newConditions = new BasicBSONList();
            Iterator<?> iter = conditions.iterator();
            while (iter.hasNext()) {
                newConditions.add(getMappedObject((DBObject) iter.next(), entity));
            }
            value = newConditions;
        }

        newDbo.put(newKey, convertSimpleOrDBObject(value, null));
    }

    return newDbo;
}

From source file:org.springframework.data.mongodb.core.ReflectiveDBCollectionInvoker.java

License:Apache License

/**
 * Borrowed from MongoDB Java driver version 2. See <a
 * href="http://github.com/mongodb/mongo-java-driver/blob/r2.13.0/src/main/com/mongodb/DBCollection.java#L754"
 * >http://github.com/mongodb/mongo-java-driver/blob/r2.13.0/src/main/com/mongodb/DBCollection.java#L754</a>
 * //from  ww  w.  ja  v  a2 s.co m
 * @param keys
 * @return
 */
private static String genIndexName(DBObject keys) {

    StringBuilder name = new StringBuilder();

    for (String s : keys.keySet()) {

        if (name.length() > 0) {
            name.append('_');
        }

        name.append(s).append('_');
        Object val = keys.get(s);

        if (val instanceof Number || val instanceof String) {
            name.append(val.toString().replace(' ', '_'));
        }
    }

    return name.toString();
}

From source file:org.springframework.data.mongodb.core.spel.ExpressionTransformationContextSupport.java

License:Apache License

private BasicDBList extractArgumentListFrom(DBObject context) {
    return (BasicDBList) context.get(context.keySet().iterator().next());
}

From source file:org.tinygroup.mongodb.engine.operation.MongoOperationContext.java

License:GNU General Public License

/**
 * //from  w  ww .  j  a  v a  2s  .  co m
 * ???
 */
public BSONObject addObjectArrayModel() {
    if (operation != null) {
        DBObject objectArray = new BasicDBObject();
        DBObject common = new BasicDBObject();
        addObjectArrayOperationObject(operation.getOperationGroup(), objectArray, common);
        DBObject condition = generateConditionObject();
        if (common.keySet().size() > 0) {
            persistence.update(condition, common);//
        }
        return persistence.insertObjectArrayModel(condition, objectArray);//?
    }
    return null;
}

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

License:Apache License

/**
 * Process the result from the query and return a list of resolved attributes
 *
 * @param result the result from the query
 * @return a list of resolved attributes
 * @throws AttributeResolutionException if an error occurs when reading the mongo db result
 *//*from  w w w .  jav a 2s . c  o  m*/
protected Map<String, BaseAttribute> processCollectionResult(DBObject result)
        throws AttributeResolutionException {
    Map<String, BaseAttribute> attributes = new HashMap<String, BaseAttribute>();
    try {
        MongoDbKeyAttributeMapper keyAttributeMapper;
        BaseAttribute attribute;

        if (result != null) {
            for (String keyName : result.keySet()) {
                log.debug("Processing mongodb key: {} class: {}", keyName, result.get(keyName).getClass());

                List<MongoDbKeyAttributeMapper> keyChildMap = null;
                keyAttributeMapper = keyAttributeMap.get(keyName);
                attribute = getAttribute(attributes, keyAttributeMapper, keyName);
                if (keyAttributeMapper != null) {
                    keyChildMap = keyAttributeMapper.getChildKeyAttributeMaps();
                }

                if (keyChildMap != null && keyChildMap.size() > 0) {
                    BasicDBObject dataMap = (BasicDBObject) result.get(keyName);
                    for (MongoDbKeyAttributeMapper map : keyChildMap) {
                        attribute = getAttribute(attributes, map, map.getAttributeName());
                        attribute.getValues().add(dataMap.get(map.getMongoKey()));
                        attributes.put(attribute.getId(), attribute);
                    }
                } else if (result.get(keyName) instanceof com.mongodb.BasicDBList) {
                    log.debug("Processing BasicDBList for {}.", keyName);
                    BasicDBList res = (BasicDBList) result.get(keyName);
                    List<String> resultList = new ArrayList<String>();
                    for (Object s : res) {
                        if (s instanceof BasicDBObject) {
                            log.error("BasicDBObjects in embedded lists not supported");
                            continue;
                        }
                        resultList.add((String) s);
                    }
                    attribute.getValues().addAll(resultList);
                    attributes.put(attribute.getId(), attribute);
                } else {
                    attribute.getValues().add(result.get(keyName));
                    attributes.put(attribute.getId(), attribute);
                }
            }
        }
    } catch (MongoException e) {
        log.error("Problem processing result {}:", getId(), e);
        throw new AttributeResolutionException("Problem processing result " + getId() + ":", e);
    }
    log.debug("MongoDb data connector {} attribute result: {}", getId(), attributes.keySet());
    return attributes;
}

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

License:Apache License

@SuppressWarnings("unchecked")
private RobotCapabilities objectToCapabilities(DBObject object) {
    if (object == null) {
        return null;
    }//w ww . j a  v  a  2 s. c om

    Map<String, Object> capabilitiesObj = (Map<String, Object>) object.get(CAPABILITIES_CAPABILITIES_FIELD);
    Map<EventType, Capability> capabilities = CollectionUtils.newHashMap();

    for (Entry<String, Object> capability : capabilitiesObj.entrySet()) {
        EventType eventType = EventType.valueOf(capability.getKey());
        List<Context> contexts = CollectionUtils.newArrayList();
        DBObject capabilityObj = (DBObject) capability.getValue();
        DBObject contextsObj = (DBObject) capabilityObj.get(CAPABILITY_CONTEXTS_FIELD);
        for (String contextId : contextsObj.keySet()) {
            contexts.add(Context.valueOf((String) contextsObj.get(contextId)));
        }
        String filter = (String) capabilityObj.get(CAPABILITY_FILTER_FIELD);

        capabilities.put(eventType, new Capability(eventType, contexts, filter));
    }

    String capabilitiesHash = (String) object.get(CAPABILITIES_HASH_FIELD);
    ProtocolVersion version = ProtocolVersion.valueOf((String) object.get(CAPABILITIES_VERSION_FIELD));

    return new RobotCapabilities(capabilities, capabilitiesHash, version);
}