Example usage for com.mongodb DBObject toMap

List of usage examples for com.mongodb DBObject toMap

Introduction

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

Prototype

Map toMap();

Source Link

Document

Returns a map representing this BSONObject.

Usage

From source file:org.springframework.data.mongodb.core.aggregation.AggregationOptions.java

License:Apache License

/**
 * Returns a new potentially adjusted copy for the given {@code aggregationCommandObject} with the configuration
 * applied.//from   w ww  .ja v a2  s. c om
 * 
 * @param command the aggregation command.
 * @return
 */
DBObject applyAndReturnPotentiallyChangedCommand(DBObject command) {

    DBObject result = new BasicDBObject(command.toMap());

    if (allowDiskUse && !result.containsField(ALLOW_DISK_USE)) {
        result.put(ALLOW_DISK_USE, allowDiskUse);
    }

    if (explain && !result.containsField(EXPLAIN)) {
        result.put(EXPLAIN, explain);
    }

    if (cursor != null && !result.containsField(CURSOR)) {
        result.put("cursor", cursor);
    }

    return result;
}

From source file:org.springframework.data.mongodb.core.convert.MappingMongoConverter.java

License:Apache License

/**
 * Reads the given {@link DBObject} into a {@link Map}. will recursively resolve nested {@link Map}s as well.
 * /*from w  w  w .  j a  va  2 s. co m*/
 * @param type the {@link Map} {@link TypeInformation} to be used to unmarshall this {@link DBObject}.
 * @param dbObject must not be {@literal null}
 * @param path must not be {@literal null}
 * @return
 */
@SuppressWarnings("unchecked")
protected Map<Object, Object> readMap(TypeInformation<?> type, DBObject dbObject, ObjectPath path) {

    Assert.notNull(dbObject, "DBObject must not be null!");
    Assert.notNull(path, "Object path must not be null!");

    Class<?> mapType = typeMapper.readType(dbObject, type).getType();

    TypeInformation<?> keyType = type.getComponentType();
    Class<?> rawKeyType = keyType == null ? null : keyType.getType();

    TypeInformation<?> valueType = type.getMapValueType();
    Class<?> rawValueType = valueType == null ? null : valueType.getType();

    Map<Object, Object> map = CollectionFactory.createMap(mapType, rawKeyType, dbObject.keySet().size());
    Map<String, Object> sourceMap = dbObject.toMap();

    for (Entry<String, Object> entry : sourceMap.entrySet()) {
        if (typeMapper.isTypeKey(entry.getKey())) {
            continue;
        }

        Object key = potentiallyUnescapeMapKey(entry.getKey());

        if (rawKeyType != null) {
            key = conversionService.convert(key, rawKeyType);
        }

        Object value = entry.getValue();

        if (value instanceof DBObject) {
            map.put(key, read(valueType, (DBObject) value, path));
        } else if (value instanceof DBRef) {
            map.put(key, DBRef.class.equals(rawValueType) ? value
                    : readAndConvertDBRef((DBRef) value, valueType, ObjectPath.ROOT, rawValueType));
        } else {
            Class<?> valueClass = valueType == null ? null : valueType.getType();
            map.put(key, getPotentiallyConvertedSimpleRead(value, valueClass));
        }
    }

    return map;
}

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

License:Apache License

/**
 * Returns the mapped value for the given source object assuming it's a value for the given
 * {@link MongoPersistentProperty}.// w w w  . j  a  va  2  s .com
 * 
 * @param value the source object to be mapped
 * @param property the property the value is a value for
 * @param newKey the key the value will be bound to eventually
 * @return
 */
protected Object getMappedValue(Field documentField, Object value) {

    if (documentField.isIdField()) {

        if (isDBObject(value)) {
            DBObject valueDbo = (DBObject) value;
            DBObject resultDbo = new BasicDBObject(valueDbo.toMap());

            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));
                }
                resultDbo.put(inKey, ids.toArray(new Object[ids.size()]));
            } else if (valueDbo.containsField("$ne")) {
                resultDbo.put("$ne", convertId(valueDbo.get("$ne")));
            } else {
                return getMappedObject(resultDbo, null);
            }

            return resultDbo;

        } else {
            return convertId(value);
        }
    }

    if (isNestedKeyword(value)) {
        return getMappedKeyword(new Keyword((DBObject) value), null);
    }

    if (isAssociationConversionNecessary(documentField, value)) {
        return convertAssociation(value, documentField);
    }

    return convertSimpleOrDBObject(value, documentField.getPropertyEntity());
}

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

License:Apache License

protected WriteResult doUpdate(final String collectionName, final Query query, final Update update,
        final Class<?> entityClass, final boolean upsert, final boolean multi) {

    return execute(collectionName, new CollectionCallback<WriteResult>() {
        public WriteResult doInCollection(DBCollection collection) throws MongoException, DataAccessException {

            MongoPersistentEntity<?> entity = entityClass == null ? null : getPersistentEntity(entityClass);

            increaseVersionForUpdateIfNecessary(entity, update);

            DBObject queryObj = query == null ? new BasicDBObject()
                    : queryMapper.getMappedObject(query.getQueryObject(), entity);
            DBObject updateObj = update == null ? new BasicDBObject()
                    : updateMapper.getMappedObject(update.getUpdateObject(), entity);

            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("Calling update using query: {} and update: {} in collection: {}",
                        serializeToJsonSafely(queryObj), serializeToJsonSafely(updateObj), collectionName);
            }//from w  ww .ja  va 2s .c  o  m

            MongoAction mongoAction = new MongoAction(writeConcern, MongoActionOperation.UPDATE, collectionName,
                    entityClass, updateObj, queryObj);
            WriteConcern writeConcernToUse = prepareWriteConcern(mongoAction);
            WriteResult writeResult = writeConcernToUse == null
                    ? collection.update(queryObj, updateObj, upsert, multi)
                    : collection.update(queryObj, updateObj, upsert, multi, writeConcernToUse);

            if (entity != null && entity.hasVersionProperty() && !multi) {
                if (ReflectiveWriteResultInvoker.wasAcknowledged(writeResult) && writeResult.getN() == 0
                        && dbObjectContainsVersionProperty(queryObj, entity)) {
                    throw new OptimisticLockingFailureException("Optimistic lock exception on saving entity: "
                            + updateObj.toMap().toString() + " to collection " + collectionName);
                }
            }

            handleAnyWriteResultErrors(writeResult, queryObj, MongoActionOperation.UPDATE);
            return writeResult;
        }
    });
}

From source file:org.springframework.datastore.mapping.mongo.MongoDatastore.java

License:Apache License

/**
 * Indexes any properties that are mapped with index:true
 * @param entity The entity//from www .j  a va 2s .c o m
 * @param template The template
 */
protected void initializeIndices(final PersistentEntity entity, final MongoTemplate template) {
    template.execute(new DbCallback<Object>() {
        public Object doInDB(DB db) throws MongoException, DataAccessException {
            final DBCollection collection = db.getCollection(template.getDefaultCollectionName());

            final ClassMapping<MongoCollection> classMapping = entity.getMapping();
            if (classMapping != null) {
                final MongoCollection mappedForm = classMapping.getMappedForm();
                if (mappedForm != null) {
                    for (Map compoundIndex : mappedForm.getCompoundIndices()) {
                        DBObject indexDef = new BasicDBObject(compoundIndex);
                        collection.ensureIndex(indexDef);
                    }

                }
            }

            for (PersistentProperty<MongoAttribute> property : entity.getPersistentProperties()) {
                final boolean indexed = isIndexed(property);

                if (indexed) {

                    final MongoAttribute mongoAttributeMapping = property.getMapping().getMappedForm();

                    DBObject dbObject = new BasicDBObject();
                    final String fieldName = getMongoFieldNameForProperty(property);
                    dbObject.put(fieldName, 1);
                    DBObject options = new BasicDBObject();
                    if (mongoAttributeMapping != null) {
                        final Map attributes = mongoAttributeMapping.getIndexAttributes();
                        if (attributes != null) {
                            if (attributes.containsKey(MongoAttribute.INDEX_TYPE)) {
                                dbObject.put(fieldName, attributes.remove(MongoAttribute.INDEX_TYPE));
                            }
                            options.putAll(attributes);
                        }
                    }
                    if (options.toMap().isEmpty()) {
                        collection.ensureIndex(dbObject);
                    } else {
                        collection.ensureIndex(dbObject, options);
                    }
                }
            }

            return null;
        }

        String getMongoFieldNameForProperty(PersistentProperty<MongoAttribute> property) {
            PropertyMapping<MongoAttribute> pm = property.getMapping();
            String propKey = null;
            if (pm.getMappedForm() != null) {
                propKey = pm.getMappedForm().getField();
            }
            if (propKey == null) {
                propKey = property.getName();
            }
            return propKey;
        }
    });
}

From source file:org.springframework.xd.test.fixtures.HdfsMongoDbJob.java

License:Apache License

/**
 * Returns a single object from the collection.
 * //from w w  w.j  a va 2  s.com
 * @param collectionName the name of the collection to query
 * @return A Map with the content of the result
 * @throws IllegalStateException if the number of objects in the collection is not one
 */
@SuppressWarnings("unchecked")
public Map<String, String> getSingleObject(String collectionName) {
    DBCursor cursor = mongoTemplate.getCollection(collectionName).find();
    if (cursor.count() != 1) {
        throw new IllegalStateException("Expected only one result but received " + cursor.count() + " entries");
    }
    DBObject dbObject = mongoTemplate.getCollection(collectionName).findOne();
    Map<String, String> result = null;
    if (dbObject != null) {
        result = dbObject.toMap();
    }
    return result;
}

From source file:uk.ac.imperial.presage2.db.mongodb.MongoObject.java

License:Open Source License

public MongoObject(DBObject o) {
    super(o.toMap());
}

From source file:uk.ac.imperial.presage2.db.mongodb.Simulation.java

License:Open Source License

@SuppressWarnings("unchecked")
@Override/*from  w w  w.  j a v a2s .co  m*/
public Map<String, String> getParameters() {
    DBObject params = (DBObject) object.get("parameters");
    return params.toMap();
}

From source file:uk.ac.soton.itinnovation.sad.service.helpers.DataHelper.java

License:Open Source License

/**
 * Utility method that converts Mongo's DBObject to SADJobData
 *///from w w w  .  ja va2  s.  co  m
public SADJobData dBObjectToSADJobData(DBObject object) {
    Map map = object.toMap();
    SADJobData jobData = new SADJobData();

    // reading data
    ObjectId id = (ObjectId) object.get("_id");
    ObjectId sadJobId = (ObjectId) map.get("SADJobID");

    Timestamp whenCollected = new Timestamp(((Date) map.get("whenCollected")).getTime());

    ObjectId ExecutionId = (ObjectId) map.get("SADExecutionDatabaseID");
    String pluginName = (String) map.get("pluginName");
    String dataType = (String) map.get("dataType");
    DBObject jsonData = (DBObject) map.get("jsonData");

    //filling object
    jobData.setId(id);
    jobData.setSADJobID(sadJobId);
    jobData.setSADExecutionDatabaseID(ExecutionId);
    jobData.setWhenCollected(whenCollected);
    jobData.setPluginName(pluginName);
    jobData.setDataType(dataType);
    jobData.setJsonData(jsonData);

    return jobData;
}