Search in sources :

Example 61 with DBObject

use of com.mongodb.DBObject in project morphia by mongodb.

the class DatastoreImpl method update.

@SuppressWarnings("unchecked")
private <T> UpdateResults update(final Query<T> query, final DBObject update, final UpdateOptions options) {
    DBCollection dbColl = query.getCollection();
    // TODO remove this after testing.
    if (dbColl == null) {
        dbColl = getCollection(query.getEntityClass());
    }
    if (query.getSortObject() != null && query.getSortObject().keySet() != null && !query.getSortObject().keySet().isEmpty()) {
        throw new QueryException("sorting is not allowed for updates.");
    }
    if (query.getOffset() > 0) {
        throw new QueryException("a query offset is not allowed for updates.");
    }
    if (query.getLimit() > 0) {
        throw new QueryException("a query limit is not allowed for updates.");
    }
    DBObject queryObject = query.getQueryObject();
    final MappedClass mc = getMapper().getMappedClass(query.getEntityClass());
    final List<MappedField> fields = mc.getFieldsAnnotatedWith(Version.class);
    if (!fields.isEmpty()) {
        final MappedField versionMF = fields.get(0);
        if (update.get(versionMF.getNameToStore()) == null) {
            if (!update.containsField("$inc")) {
                update.put("$inc", new BasicDBObject(versionMF.getNameToStore(), 1));
            } else {
                ((Map<String, Object>) (update.get("$inc"))).put(versionMF.getNameToStore(), 1);
            }
        }
    }
    if (LOG.isTraceEnabled()) {
        LOG.trace(format("Executing update(%s) for query: %s, ops: %s, multi: %s, upsert: %s", dbColl.getName(), queryObject, update, options.isMulti(), options.isUpsert()));
    }
    return new UpdateResults(dbColl.update(queryObject, update, enforceWriteConcern(options, query.getEntityClass()).getOptions()));
}
Also used : MappedField(org.mongodb.morphia.mapping.MappedField) DBCollection(com.mongodb.DBCollection) BasicDBObject(com.mongodb.BasicDBObject) QueryException(org.mongodb.morphia.query.QueryException) MappedClass(org.mongodb.morphia.mapping.MappedClass) DBObject(com.mongodb.DBObject) BasicDBObject(com.mongodb.BasicDBObject) Map(java.util.Map) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) UpdateResults(org.mongodb.morphia.query.UpdateResults)

Example 62 with DBObject

use of com.mongodb.DBObject in project morphia by mongodb.

the class EmbeddedMapper method readMap.

@SuppressWarnings("unchecked")
private void readMap(final Datastore datastore, final Mapper mapper, final Object entity, final EntityCache cache, final MappedField mf, final DBObject dbObject) {
    final DBObject dbObj = (DBObject) mf.getDbObjectValue(dbObject);
    if (dbObj != null) {
        final Map map = mapper.getOptions().getObjectFactory().createMap(mf);
        final EphemeralMappedField ephemeralMappedField = isMapOrCollection(mf) ? new EphemeralMappedField((ParameterizedType) mf.getSubType(), mf, mapper) : null;
        new IterHelper<Object, Object>().loopMap(dbObj, new MapIterCallback<Object, Object>() {

            @Override
            public void eval(final Object k, final Object val) {
                Object newEntity = null;
                //run converters
                if (val != null) {
                    if (mapper.getConverters().hasSimpleValueConverter(mf) || mapper.getConverters().hasSimpleValueConverter(mf.getSubClass())) {
                        newEntity = mapper.getConverters().decode(mf.getSubClass(), val, mf);
                    } else {
                        if (val instanceof DBObject) {
                            newEntity = readMapOrCollectionOrEntity(datastore, mapper, cache, mf, ephemeralMappedField, (DBObject) val);
                        } else {
                            newEntity = val;
                        }
                    }
                }
                final Object objKey = mapper.getConverters().decode(mf.getMapKeyClass(), k, mf);
                map.put(objKey, newEntity);
            }
        });
        if (!map.isEmpty() || mapper.getOptions().isStoreEmpties()) {
            mf.setFieldValue(entity, map);
        }
    }
}
Also used : ParameterizedType(java.lang.reflect.ParameterizedType) BasicDBObject(com.mongodb.BasicDBObject) DBObject(com.mongodb.DBObject) BasicDBObject(com.mongodb.BasicDBObject) DBObject(com.mongodb.DBObject) Map(java.util.Map)

Example 63 with DBObject

use of com.mongodb.DBObject in project morphia by mongodb.

the class EmbeddedMapper method toDBObject.

@Override
public void toDBObject(final Object entity, final MappedField mf, final DBObject dbObject, final Map<Object, DBObject> involvedObjects, final Mapper mapper) {
    final String name = mf.getNameToStore();
    final Object fieldValue = mf.getFieldValue(entity);
    if (mf.isMap()) {
        writeMap(mf, dbObject, involvedObjects, name, fieldValue, mapper);
    } else if (mf.isMultipleValues()) {
        writeCollection(mf, dbObject, involvedObjects, name, fieldValue, mapper);
    } else {
        //run converters
        if (mapper.getConverters().hasDbObjectConverter(mf) || mapper.getConverters().hasDbObjectConverter(entity.getClass())) {
            mapper.getConverters().toDBObject(entity, mf, dbObject, mapper.getOptions());
            return;
        }
        final DBObject dbObj = fieldValue == null ? null : mapper.toDBObject(fieldValue, involvedObjects);
        if (dbObj != null) {
            if (!shouldSaveClassName(fieldValue, dbObj, mf)) {
                dbObj.removeField(Mapper.CLASS_NAME_FIELDNAME);
            }
            if (!dbObj.keySet().isEmpty() || mapper.getOptions().isStoreEmpties()) {
                dbObject.put(name, dbObj);
            }
        }
    }
}
Also used : BasicDBObject(com.mongodb.BasicDBObject) DBObject(com.mongodb.DBObject) BasicDBObject(com.mongodb.BasicDBObject) DBObject(com.mongodb.DBObject)

Example 64 with DBObject

use of com.mongodb.DBObject in project morphia by mongodb.

the class MappedClass method callLifecycleMethods.

/**
     * Call the lifecycle methods
     *
     * @param event  the lifecycle annotation
     * @param entity the entity to process
     * @param dbObj  the dbObject to use
     * @param mapper  the Mapper to use
     * @return dbObj
     */
@SuppressWarnings({ "WMI", "unchecked" })
public DBObject callLifecycleMethods(final Class<? extends Annotation> event, final Object entity, final DBObject dbObj, final Mapper mapper) {
    final List<ClassMethodPair> methodPairs = getLifecycleMethods((Class<Annotation>) event);
    DBObject retDbObj = dbObj;
    try {
        Object tempObj;
        if (methodPairs != null) {
            final HashMap<Class<?>, Object> toCall = new HashMap<Class<?>, Object>((int) (methodPairs.size() * 1.3));
            for (final ClassMethodPair cm : methodPairs) {
                toCall.put(cm.clazz, null);
            }
            for (final Class<?> c : toCall.keySet()) {
                if (c != null) {
                    toCall.put(c, getOrCreateInstance(c, mapper));
                }
            }
            for (final ClassMethodPair cm : methodPairs) {
                final Method method = cm.method;
                final Object inst = toCall.get(cm.clazz);
                method.setAccessible(true);
                if (LOG.isDebugEnabled()) {
                    LOG.debug(format("Calling lifecycle method(@%s %s) on %s", event.getSimpleName(), method, inst));
                }
                if (inst == null) {
                    if (method.getParameterTypes().length == 0) {
                        tempObj = method.invoke(entity);
                    } else {
                        tempObj = method.invoke(entity, retDbObj);
                    }
                } else if (method.getParameterTypes().length == 0) {
                    tempObj = method.invoke(inst);
                } else if (method.getParameterTypes().length == 1) {
                    tempObj = method.invoke(inst, entity);
                } else {
                    tempObj = method.invoke(inst, entity, retDbObj);
                }
                if (tempObj != null) {
                    retDbObj = (DBObject) tempObj;
                }
            }
        }
        callGlobalInterceptors(event, entity, dbObj, mapper);
    } catch (IllegalAccessException e) {
        throw new RuntimeException(e);
    } catch (InvocationTargetException e) {
        throw new RuntimeException(e);
    }
    return retDbObj;
}
Also used : HashMap(java.util.HashMap) Method(java.lang.reflect.Method) DBObject(com.mongodb.DBObject) Annotation(java.lang.annotation.Annotation) InvocationTargetException(java.lang.reflect.InvocationTargetException) DBObject(com.mongodb.DBObject)

Example 65 with DBObject

use of com.mongodb.DBObject in project morphia by mongodb.

the class Converters method fromDBObject.

/**
     * Creates an entity and populates its state based on the dbObject given.  This method is primarily an internal method.  Reliance on
     * this method may break your application in future releases.
     *
     * @param dbObj        the object state to use
     * @param mf           the MappedField containing the metadata to use when decoding in to a field
     * @param targetEntity then entity to hold the state from the database
     */
public void fromDBObject(final DBObject dbObj, final MappedField mf, final Object targetEntity) {
    final Object object = mf.getDbObjectValue(dbObj);
    if (object != null) {
        final TypeConverter enc = getEncoder(mf);
        final Object decodedValue = enc.decode(mf.getType(), object, mf);
        try {
            mf.setFieldValue(targetEntity, decodedValue);
        } catch (IllegalArgumentException e) {
            throw new MappingException(format("Error setting value from converter (%s) for %s to %s", enc.getClass().getSimpleName(), mf.getFullName(), decodedValue), e);
        }
    }
}
Also used : DBObject(com.mongodb.DBObject) MappingException(org.mongodb.morphia.mapping.MappingException)

Aggregations

DBObject (com.mongodb.DBObject)646 BasicDBObject (com.mongodb.BasicDBObject)445 Test (org.junit.Test)267 YearFilterPagingRequest (org.devgateway.ocds.web.rest.controller.request.YearFilterPagingRequest)95 DBCollection (com.mongodb.DBCollection)84 Aggregation (org.springframework.data.mongodb.core.aggregation.Aggregation)79 ApiOperation (io.swagger.annotations.ApiOperation)71 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)70 Aggregation.newAggregation (org.springframework.data.mongodb.core.aggregation.Aggregation.newAggregation)63 CustomProjectionOperation (org.devgateway.toolkit.persistence.mongo.aggregate.CustomProjectionOperation)53 ArrayList (java.util.ArrayList)44 DBCursor (com.mongodb.DBCursor)42 HashMap (java.util.HashMap)40 List (java.util.List)35 ObjectId (org.bson.types.ObjectId)30 BasicDBList (com.mongodb.BasicDBList)29 Map (java.util.Map)28 BasicDBObjectBuilder (com.mongodb.BasicDBObjectBuilder)20 CustomGroupingOperation (org.devgateway.toolkit.persistence.mongo.aggregate.CustomGroupingOperation)20 BSONObject (org.bson.BSONObject)19