Example usage for com.mongodb DBObject containsField

List of usage examples for com.mongodb DBObject containsField

Introduction

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

Prototype

boolean containsField(String s);

Source Link

Document

Checks if this object contains a field with the given name.

Usage

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

License:Apache License

protected void writeInternal(final Object obj, final DBObject dbo, MongoPersistentEntity<?> entity) {

    if (obj == null) {
        return;//  ww w  .j a  va2  s .c  om
    }

    if (null == entity) {
        throw new MappingException("No mapping metadata found for entity of type " + obj.getClass().getName());
    }

    // Write the ID
    final MongoPersistentProperty idProperty = entity.getIdProperty();
    if (!dbo.containsField("_id") && null != idProperty) {
        Object idObj;
        try {
            idObj = getProperty(obj, idProperty, Object.class, useFieldAccessOnly);
        } catch (IllegalAccessException e) {
            throw new MappingException(e.getMessage(), e);
        } catch (InvocationTargetException e) {
            throw new MappingException(e.getMessage(), e);
        }

        if (null != idObj) {
            dbo.put("_id", idObj);
        } else {
            if (!VALID_ID_TYPES.contains(idProperty.getType())) {
                throw new MappingException("Invalid data type " + idProperty.getType().getName()
                        + " for Id property. Should be one of " + VALID_ID_TYPES);
            }
        }
    }

    // Write the properties
    entity.doWithProperties(new PropertyHandler<MongoPersistentProperty>() {
        public void doWithPersistentProperty(MongoPersistentProperty prop) {
            String name = prop.getName();
            Class<?> type = prop.getType();
            Object propertyObj;
            try {
                propertyObj = getProperty(obj, prop, type, useFieldAccessOnly);
            } catch (IllegalAccessException e) {
                throw new MappingException(e.getMessage(), e);
            } catch (InvocationTargetException e) {
                throw new MappingException(e.getMessage(), e);
            }
            if (null != propertyObj) {
                if (!isSimpleType(propertyObj.getClass())) {
                    writePropertyInternal(prop, propertyObj, dbo);
                } else {
                    dbo.put(name, propertyObj);
                }
            }
        }
    });

    entity.doWithAssociations(new AssociationHandler<MongoPersistentProperty>() {
        public void doWithAssociation(Association<MongoPersistentProperty> association) {
            MongoPersistentProperty inverseProp = association.getInverse();
            Class<?> type = inverseProp.getType();
            Object propertyObj;
            try {
                propertyObj = getProperty(obj, inverseProp, type, useFieldAccessOnly);
            } catch (IllegalAccessException e) {
                throw new MappingException(e.getMessage(), e);
            } catch (InvocationTargetException e) {
                throw new MappingException(e.getMessage(), e);
            }
            if (null != propertyObj) {
                writePropertyInternal(inverseProp, propertyObj, dbo);
            }
        }
    });
}

From source file:org.springframework.data.document.mongodb.convert.SimpleMongoConverter.java

License:Apache License

public <S> S read(Class<S> clazz, DBObject source) {

    if (source == null) {
        return null;
    }//  www .  j a va 2s .  c  o m

    Assert.notNull(clazz, "Mapped class was not specified");
    S target = BeanUtils.instantiateClass(clazz);
    MongoBeanWrapper bw = new MongoBeanWrapper(target, conversionService, true);

    for (MongoPropertyDescriptor descriptor : bw.getDescriptors()) {
        String keyToUse = descriptor.getKeyToMap();
        if (source.containsField(keyToUse)) {
            if (descriptor.isMappable()) {
                Object value = source.get(keyToUse);
                if (!isSimpleType(value.getClass())) {
                    if (value instanceof Object[]) {
                        bw.setValue(descriptor,
                                readCollection(descriptor, Arrays.asList((Object[]) value)).toArray());
                    } else if (value instanceof BasicDBList) {
                        bw.setValue(descriptor, readCollection(descriptor, (BasicDBList) value));
                    } else if (value instanceof DBObject) {
                        bw.setValue(descriptor, readCompoundValue(descriptor, (DBObject) value));
                    } else {
                        LOG.warn("Unable to map compound DBObject field " + keyToUse + " to property "
                                + descriptor.getName()
                                + ".  The field value should have been a 'DBObject.class' but was "
                                + value.getClass().getName());
                    }
                } else {
                    bw.setValue(descriptor, value);
                }
            } else {
                LOG.warn("Unable to map DBObject field " + keyToUse + " to property " + descriptor.getName()
                        + ".  Skipping.");
            }
        }
    }

    return target;
}

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

License:Apache License

protected Object insertDBObject(String collectionName, final DBObject dbDoc) {

    // DATADOC-95: This will prevent null objects from being saved.
    //if (dbDoc.keySet().isEmpty()) {
    //return null;
    //}//from   w  w w  . jav a  2  s  .  c o  m

    //TODO: Need to move this to more central place
    if (dbDoc.containsField("_id")) {
        if (dbDoc.get("_id") instanceof String) {
            ObjectId oid = convertIdValue(this.mongoConverter, dbDoc.get("_id"));
            if (oid != null) {
                dbDoc.put("_id", oid);
            }
        }
    }
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug(
                "insert DBObject containing fields: " + dbDoc.keySet() + " in collection: " + collectionName);
    }
    return execute(collectionName, new CollectionCallback<Object>() {
        public Object doInCollection(DBCollection collection) throws MongoException, DataAccessException {
            if (writeConcern == null) {
                collection.insert(dbDoc);
            } else {
                collection.insert(dbDoc, writeConcern);
            }
            return dbDoc.get(ID);
        }
    });
}

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

License:Apache License

protected List<ObjectId> insertDBObjectList(String collectionName, final List<DBObject> dbDocList) {

    if (dbDocList.isEmpty()) {
        return Collections.emptyList();
    }//ww w  .  j a va2 s  . c om

    //TODO: Need to move this to more central place
    for (DBObject dbDoc : dbDocList) {
        if (dbDoc.containsField("_id")) {
            if (dbDoc.get("_id") instanceof String) {
                ObjectId oid = convertIdValue(this.mongoConverter, dbDoc.get("_id"));
                if (oid != null) {
                    dbDoc.put("_id", oid);
                }
            }
        }
    }
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("insert list of DBObjects containing " + dbDocList.size() + " items");
    }
    execute(collectionName, new CollectionCallback<Void>() {
        public Void doInCollection(DBCollection collection) throws MongoException, DataAccessException {
            if (writeConcern == null) {
                collection.insert(dbDocList);
            } else {
                collection.insert(dbDocList.toArray((DBObject[]) new BasicDBObject[dbDocList.size()]),
                        writeConcern);
            }
            return null;
        }
    });

    List<ObjectId> ids = new ArrayList<ObjectId>();
    for (DBObject dbo : dbDocList) {
        Object id = dbo.get(ID);
        if (id instanceof ObjectId) {
            ids.add((ObjectId) id);
        } else {
            // no id was generated
            ids.add(null);
        }
    }
    return ids;
}

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

License:Apache License

protected Object saveDBObject(String collectionName, final DBObject dbDoc) {

    if (dbDoc.keySet().isEmpty()) {
        return null;
    }//  w ww. ja v a 2  s.c o  m

    //TODO: Need to move this to more central place
    if (dbDoc.containsField("_id")) {
        if (dbDoc.get("_id") instanceof String) {
            ObjectId oid = convertIdValue(this.mongoConverter, dbDoc.get("_id"));
            if (oid != null) {
                dbDoc.put("_id", oid);
            }
        }
    }
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("save DBObject containing fields: " + dbDoc.keySet());
    }
    return execute(collectionName, new CollectionCallback<Object>() {
        public Object doInCollection(DBCollection collection) throws MongoException, DataAccessException {
            if (writeConcern == null) {
                collection.save(dbDoc);
            } else {
                collection.save(dbDoc, writeConcern);
            }
            return dbDoc.get(ID);
        }
    });
}

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

License:Apache License

/**
 * Substitutes the id key if it is found in he query. Any 'id' keys will be replaced with '_id' and the value converted
 * to an ObjectId if possible. This conversion should match the way that the id fields are converted during read
 * operations.// w  w w. j a  v a 2  s.  c om
 *
 * @param query
 * @param targetClass
 * @param reader
 */
protected void substituteMappedIdIfNecessary(DBObject query, Class<?> targetClass, MongoReader<?> reader) {
    MongoConverter converter = null;
    if (reader instanceof SimpleMongoConverter) {
        converter = (MongoConverter) reader;
    } else if (reader instanceof MappingMongoConverter) {
        converter = (MappingMongoConverter) reader;
    } else {
        return;
    }
    String idKey = null;
    if (query.containsField("id")) {
        idKey = "id";
    }
    if (query.containsField("_id")) {
        idKey = "_id";
    }
    if (idKey == null) {
        // no ids in this query
        return;
    }
    MongoPropertyDescriptor descriptor;
    try {
        MongoPropertyDescriptor mpd = new MongoPropertyDescriptor(new PropertyDescriptor(idKey, targetClass),
                targetClass);
        descriptor = mpd;
    } catch (IntrospectionException e) {
        // no property descriptor for this key - try the other
        try {
            String theOtherIdKey = "id".equals(idKey) ? "_id" : "id";
            MongoPropertyDescriptor mpd2 = new MongoPropertyDescriptor(
                    new PropertyDescriptor(theOtherIdKey, targetClass), targetClass);
            descriptor = mpd2;
        } catch (IntrospectionException e2) {
            // no property descriptor for this key either - bail
            return;
        }
    }
    if (descriptor.isIdProperty() && descriptor.isOfIdType()) {
        Object value = query.get(idKey);
        if (value instanceof DBObject) {
            DBObject dbo = (DBObject) value;
            if (dbo.containsField("$in")) {
                List<Object> ids = new ArrayList<Object>();
                int count = 0;
                for (Object o : (Object[]) dbo.get("$in")) {
                    count++;
                    ObjectId newValue = convertIdValue(converter, o);
                    if (newValue != null) {
                        ids.add(newValue);
                    }
                }
                if (ids.size() > 0 && ids.size() != count) {
                    throw new InvalidDataAccessApiUsageException("Inconsistent set of id values provided "
                            + Arrays.asList((Object[]) dbo.get("$in")));
                }
                if (ids.size() > 0) {
                    dbo.removeField("$in");
                    dbo.put("$in", ids.toArray());
                }
            }
            query.removeField(idKey);
            query.put(MongoPropertyDescriptor.ID_KEY, value);
        } else {
            ObjectId newValue = convertIdValue(converter, value);
            query.removeField(idKey);
            if (newValue != null) {
                query.put(MongoPropertyDescriptor.ID_KEY, newValue);
            } else {
                query.put(MongoPropertyDescriptor.ID_KEY, value);
            }
        }
    }
}

From source file:org.springframework.data.document.mongodb.query.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.// w  w  w  .  j  a v  a 2 s .  c  om
 * 
 * @param query
 * @param entity
 * @return
 */
public DBObject getMappedObject(DBObject query, MongoPersistentEntity<?> entity) {
    String idKey = null;
    if (null != entity && entity.getIdProperty() != null) {
        idKey = entity.getIdProperty().getName();
    } else if (query.containsField("id")) {
        idKey = "id";
    } else if (query.containsField("_id")) {
        idKey = "_id";
    }

    DBObject newDbo = new BasicDBObject();
    for (String key : query.keySet()) {
        String newKey = key;
        Object value = query.get(key);
        if (key.equals(idKey)) {
            if (value instanceof DBObject) {
                if ("$in".equals(key)) {
                    List<Object> ids = new ArrayList<Object>();
                    for (Object id : (Object[]) ((DBObject) value).get("$in")) {
                        if (null != converter && !(id instanceof ObjectId)) {
                            ObjectId oid = converter.convertObjectId(id);
                            ids.add(oid);
                        } else {
                            ids.add(id);
                        }
                    }
                    newDbo.put("$in", ids.toArray(new ObjectId[ids.size()]));
                }
            } else if (null != converter) {
                try {
                    value = converter.convertObjectId(value);
                } catch (ConversionFailedException ignored) {
                }
            }
            newKey = "_id";
        } else {
            // TODO: Implement other forms of conversion (like @Alias and whatnot)
        }
        newDbo.put(newKey, value);
    }
    return newDbo;
}

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./*w  ww.ja  va 2s.c o m*/
 * 
 * @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.CustomMappingMongoConverter.java

private <S extends Object> S read(final MongoPersistentEntity<S> entity, final DBObject dbo,
        final ObjectPath path) {

    final DefaultSpELExpressionEvaluator evaluator = new DefaultSpELExpressionEvaluator(dbo, spELContext);

    ParameterValueProvider<MongoPersistentProperty> provider = getParameterProvider(entity, dbo, evaluator,
            path);/*w  w w .j a va 2s.c o m*/
    EntityInstantiator instantiator = instantiators.getInstantiatorFor(entity);
    S instance = instantiator.createInstance(entity, provider);

    final PersistentPropertyAccessor accessor = new ConvertingPropertyAccessor(
            entity.getPropertyAccessor(instance), conversionService);

    final MongoPersistentProperty idProperty = entity.getIdProperty();
    final S result = instance;

    // make sure id property is set before all other properties
    Object idValue = null;

    if (idProperty != null) {
        idValue = getValueInternal(idProperty, dbo, evaluator, path);
        accessor.setProperty(idProperty, idValue);
    }

    final ObjectPath currentPath = path.push(result, entity, idValue);

    // Set properties not already set in the constructor
    entity.doWithProperties(new PropertyHandler<MongoPersistentProperty>() {
        public void doWithPersistentProperty(MongoPersistentProperty prop) {

            // we skip the id property since it was already set
            if (idProperty != null && idProperty.equals(prop)) {
                return;
            }

            if (!dbo.containsField(prop.getFieldName()) || entity.isConstructorArgument(prop)) {
                return;
            }

            accessor.setProperty(prop, getValueInternal(prop, dbo, evaluator, currentPath));
        }
    });

    // Handle associations
    entity.doWithAssociations(new AssociationHandler<MongoPersistentProperty>() {
        public void doWithAssociation(Association<MongoPersistentProperty> association) {

            final MongoPersistentProperty property = association.getInverse();
            Object value = dbo.get(property.getFieldName());

            if (value == null) {
                return;
            }

            DBRef dbref = value instanceof DBRef ? (DBRef) value : null;

            DbRefProxyHandler handler = new DefaultDbRefProxyHandler(spELContext, mappingContext,
                    CustomMappingMongoConverter.this);
            DbRefResolverCallback callback = new DefaultDbRefResolverCallback(dbo, currentPath, evaluator,
                    CustomMappingMongoConverter.this);

            accessor.setProperty(property, dbRefResolver.resolveDbRef(property, dbref, callback, handler));
        }
    });

    return result;
}

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

License:Apache License

private <S extends Object> S read(final MongoPersistentEntity<S> entity, final DBObject dbo,
        final ObjectPath path) {

    final DefaultSpELExpressionEvaluator evaluator = new DefaultSpELExpressionEvaluator(dbo, spELContext);

    ParameterValueProvider<MongoPersistentProperty> provider = getParameterProvider(entity, dbo, evaluator,
            path);//from   ww w.j av a2  s  .  c  om
    EntityInstantiator instantiator = instantiators.getInstantiatorFor(entity);
    S instance = instantiator.createInstance(entity, provider);

    final PersistentPropertyAccessor accessor = new ConvertingPropertyAccessor(
            entity.getPropertyAccessor(instance), conversionService);

    final MongoPersistentProperty idProperty = entity.getIdProperty();
    final S result = instance;

    // make sure id property is set before all other properties
    Object idValue = null;

    if (idProperty != null) {
        idValue = getValueInternal(idProperty, dbo, evaluator, path);
        accessor.setProperty(idProperty, idValue);
    }

    final ObjectPath currentPath = path.push(result, entity,
            idValue != null ? dbo.get(idProperty.getFieldName()) : null);

    // Set properties not already set in the constructor
    entity.doWithProperties(new PropertyHandler<MongoPersistentProperty>() {
        public void doWithPersistentProperty(MongoPersistentProperty prop) {

            // we skip the id property since it was already set
            if (idProperty != null && idProperty.equals(prop)) {
                return;
            }

            if (!dbo.containsField(prop.getFieldName()) || entity.isConstructorArgument(prop)) {
                return;
            }

            accessor.setProperty(prop, getValueInternal(prop, dbo, evaluator, currentPath));
        }
    });

    // Handle associations
    entity.doWithAssociations(new AssociationHandler<MongoPersistentProperty>() {
        public void doWithAssociation(Association<MongoPersistentProperty> association) {

            final MongoPersistentProperty property = association.getInverse();
            Object value = dbo.get(property.getFieldName());

            if (value == null || entity.isConstructorArgument(property)) {
                return;
            }

            DBRef dbref = value instanceof DBRef ? (DBRef) value : null;

            DbRefProxyHandler handler = new DefaultDbRefProxyHandler(spELContext, mappingContext,
                    MappingMongoConverter.this);
            DbRefResolverCallback callback = new DefaultDbRefResolverCallback(dbo, currentPath, evaluator,
                    MappingMongoConverter.this);

            accessor.setProperty(property, dbRefResolver.resolveDbRef(property, dbref, callback, handler));
        }
    });

    return result;
}