Search in sources :

Example 76 with DBObject

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

the class Mapper method fromDb.

/**
     * Converts a DBObject back to a type-safe java object (POJO)
     *
     * @param <T>       the type of the entity
     * @param datastore the Datastore to use when fetching this reference
     * @param dbObject  the DBObject containing the document from mongodb
     * @param entity    the instance to populate
     * @param cache     the EntityCache to use
     * @return the entity
     */
public <T> T fromDb(final Datastore datastore, final DBObject dbObject, final T entity, final EntityCache cache) {
    //hack to bypass things and just read the value.
    if (entity instanceof MappedField) {
        readMappedField(datastore, (MappedField) entity, entity, cache, dbObject);
        return entity;
    }
    if (dbObject.containsField(ID_KEY) && getMappedClass(entity).getIdField() != null && getMappedClass(entity).getEntityAnnotation() != null) {
        final Key<T> key = new Key(entity.getClass(), getCollectionName(entity.getClass()), dbObject.get(ID_KEY));
        final T cachedInstance = cache.getEntity(key);
        if (cachedInstance != null) {
            return cachedInstance;
        } else {
            // to avoid stackOverflow in recursive refs
            cache.putEntity(key, entity);
        }
    }
    if (entity instanceof Map) {
        Map<String, Object> map = (Map<String, Object>) entity;
        for (String key : dbObject.keySet()) {
            Object o = dbObject.get(key);
            map.put(key, (o instanceof DBObject) ? fromDBObject(datastore, (DBObject) o) : o);
        }
    } else if (entity instanceof Collection) {
        Collection<Object> collection = (Collection<Object>) entity;
        for (Object o : ((List) dbObject)) {
            collection.add((o instanceof DBObject) ? fromDBObject(datastore, (DBObject) o) : o);
        }
    } else {
        final MappedClass mc = getMappedClass(entity);
        final DBObject updated = mc.callLifecycleMethods(PreLoad.class, entity, dbObject, this);
        try {
            for (final MappedField mf : mc.getPersistenceFields()) {
                readMappedField(datastore, mf, entity, cache, updated);
            }
        } catch (final MappingException e) {
            Object id = dbObject.get(ID_KEY);
            String entityName = entity.getClass().getName();
            throw new MappingException(format("Could not map %s with ID: %s in database '%s'", entityName, id, datastore.getDB().getName()), e);
        }
        if (updated.containsField(ID_KEY) && getMappedClass(entity).getIdField() != null) {
            final Key key = new Key(entity.getClass(), getCollectionName(entity.getClass()), updated.get(ID_KEY));
            cache.putEntity(key, entity);
        }
        mc.callLifecycleMethods(PostLoad.class, entity, updated, this);
    }
    return entity;
}
Also used : PreLoad(org.mongodb.morphia.annotations.PreLoad) DBObject(com.mongodb.DBObject) BasicDBObject(com.mongodb.BasicDBObject) PostLoad(org.mongodb.morphia.annotations.PostLoad) Collection(java.util.Collection) DBObject(com.mongodb.DBObject) BasicDBObject(com.mongodb.BasicDBObject) BasicDBList(com.mongodb.BasicDBList) List(java.util.List) ArrayList(java.util.ArrayList) LinkedList(java.util.LinkedList) Map(java.util.Map) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) Key(org.mongodb.morphia.Key)

Example 77 with DBObject

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

the class Mapper method updateKeyAndVersionInfo.

/**
     * Updates the @{@link org.mongodb.morphia.annotations.Id} and @{@link org.mongodb.morphia.annotations.Version} fields.
     *
     * @param datastore the Datastore to use when fetching this reference
     * @param dbObj     Value to update with; null means skip
     * @param cache     the EntityCache
     * @param entity    The object to update
     */
public void updateKeyAndVersionInfo(final Datastore datastore, final DBObject dbObj, final EntityCache cache, final Object entity) {
    final MappedClass mc = getMappedClass(entity);
    // update id field, if there.
    if ((mc.getIdField() != null) && (dbObj != null) && (dbObj.get(ID_KEY) != null)) {
        try {
            final MappedField mf = mc.getMappedIdField();
            final Object oldIdValue = mc.getIdField().get(entity);
            readMappedField(datastore, mf, entity, cache, dbObj);
            if (oldIdValue != null) {
                // The entity already had an id set. Check to make sure it hasn't changed. That would be unexpected, and could
                // indicate a bad state.
                final Object dbIdValue = mf.getFieldValue(entity);
                if (!dbIdValue.equals(oldIdValue)) {
                    //put the value back...
                    mf.setFieldValue(entity, oldIdValue);
                    throw new RuntimeException(format("@Id mismatch: %s != %s for %s", oldIdValue, dbIdValue, entity.getClass().getName()));
                }
            }
        } catch (Exception e) {
            if (e instanceof RuntimeException) {
                throw (RuntimeException) e;
            }
            throw new RuntimeException("Error setting @Id field after save/insert.", e);
        }
    }
    if (mc.getMappedVersionField() != null && (dbObj != null)) {
        readMappedField(datastore, mc.getMappedVersionField(), entity, cache, dbObj);
    }
}
Also used : DBObject(com.mongodb.DBObject) BasicDBObject(com.mongodb.BasicDBObject) ValidationException(org.mongodb.morphia.query.ValidationException) IOException(java.io.IOException)

Example 78 with DBObject

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

the class ReferenceMapper method resolveObject.

Object resolveObject(final Datastore datastore, final Mapper mapper, final EntityCache cache, final MappedField mf, final boolean idOnly, final Object ref) {
    if (ref == null) {
        return null;
    }
    final DBRef dbRef = idOnly ? null : (DBRef) ref;
    final Key key = mapper.createKey(mf.isSingleValue() ? mf.getType() : mf.getSubClass(), idOnly ? ref : dbRef.getId());
    final Object cached = cache.getEntity(key);
    if (cached != null) {
        return cached;
    }
    final DBObject refDbObject;
    DBCollection collection;
    Object id;
    if (idOnly) {
        collection = datastore.getCollection(key.getType());
        id = ref;
    } else {
        collection = datastore.getDB().getCollection(dbRef.getCollectionName());
        id = dbRef.getId();
    }
    if (id instanceof DBObject) {
        ((DBObject) id).removeField(Mapper.CLASS_NAME_FIELDNAME);
    }
    refDbObject = collection.findOne(id);
    if (refDbObject != null) {
        Object refObj = mapper.getOptions().getObjectFactory().createInstance(mapper, mf, refDbObject);
        refObj = mapper.fromDb(datastore, refDbObject, refObj, cache);
        cache.putEntity(key, refObj);
        return refObj;
    }
    final boolean ignoreMissing = mf.getAnnotation(Reference.class) != null && mf.getAnnotation(Reference.class).ignoreMissing();
    if (!ignoreMissing) {
        throw new MappingException("The reference(" + ref.toString() + ") could not be fetched for " + mf.getFullName());
    } else {
        return null;
    }
}
Also used : DBCollection(com.mongodb.DBCollection) DBRef(com.mongodb.DBRef) DBObject(com.mongodb.DBObject) DBObject(com.mongodb.DBObject) Key(org.mongodb.morphia.Key)

Example 79 with DBObject

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

the class IndexHelperTest method index.

@Test
public void index() {
    checkMinServerVersion(3.4);
    MongoCollection<Document> indexes = getDatabase().getCollection("indexes");
    MappedClass mappedClass = getMorphia().getMapper().getMappedClass(IndexedClass.class);
    indexes.drop();
    Index index = new IndexBuilder().fields(new FieldBuilder().value("indexName"), new FieldBuilder().value("text").type(IndexType.DESC)).options(indexOptions());
    indexHelper.createIndex(indexes, mappedClass, index, false);
    List<DBObject> indexInfo = getDs().getCollection(IndexedClass.class).getIndexInfo();
    for (DBObject dbObject : indexInfo) {
        if (dbObject.get("name").equals("indexName")) {
            checkIndex(dbObject);
            assertEquals("en", dbObject.get("default_language"));
            assertEquals("de", dbObject.get("language_override"));
            assertEquals(new BasicDBObject().append("locale", "en").append("caseLevel", true).append("caseFirst", "upper").append("strength", 5).append("numericOrdering", true).append("alternate", "shifted").append("maxVariable", "space").append("backwards", true).append("normalization", true).append("version", "57.1"), dbObject.get("collation"));
        }
    }
}
Also used : BasicDBObject(com.mongodb.BasicDBObject) Index(org.mongodb.morphia.annotations.Index) MappedClass(org.mongodb.morphia.mapping.MappedClass) Document(org.bson.Document) BsonDocument(org.bson.BsonDocument) DBObject(com.mongodb.DBObject) BasicDBObject(com.mongodb.BasicDBObject) Test(org.junit.Test)

Example 80 with DBObject

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

the class IndexHelperTest method oldIndexForm.

@Test
public void oldIndexForm() {
    MongoCollection<Document> indexes = getDatabase().getCollection("indexes");
    MappedClass mappedClass = getMorphia().getMapper().getMappedClass(IndexedClass.class);
    indexes.drop();
    Index index = new IndexBuilder().name("index_name").background(true).disableValidation(true).dropDups(true).expireAfterSeconds(42).sparse(true).unique(true).value("indexName, -text");
    indexHelper.createIndex(indexes, mappedClass, index, false);
    List<DBObject> indexInfo = getDs().getCollection(IndexedClass.class).getIndexInfo();
    for (DBObject dbObject : indexInfo) {
        if (dbObject.get("name").equals("index_indexName")) {
            checkIndex(dbObject);
        }
    }
}
Also used : Index(org.mongodb.morphia.annotations.Index) MappedClass(org.mongodb.morphia.mapping.MappedClass) Document(org.bson.Document) BsonDocument(org.bson.BsonDocument) DBObject(com.mongodb.DBObject) BasicDBObject(com.mongodb.BasicDBObject) Test(org.junit.Test)

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