Search in sources :

Example 1 with Key

use of org.mongodb.morphia.Key in project morphia by mongodb.

the class Mapper method getKey.

/**
     * Gets the Key for an entity and a specific collection
     *
     * @param entity     the entity to process
     * @param collection the collection to use in the Key rather than the mapped collection as defined on the entity's class
     * @param <T>        the type of the entity
     * @return the Key
     */
public <T> Key<T> getKey(final T entity, final String collection) {
    T unwrapped = entity;
    if (unwrapped instanceof ProxiedEntityReference) {
        final ProxiedEntityReference proxy = (ProxiedEntityReference) unwrapped;
        return (Key<T>) proxy.__getKey();
    }
    unwrapped = ProxyHelper.unwrap(unwrapped);
    if (unwrapped instanceof Key) {
        return (Key<T>) unwrapped;
    }
    final Object id = getId(unwrapped);
    final Class<T> aClass = (Class<T>) unwrapped.getClass();
    return id == null ? null : new Key<T>(aClass, collection, id);
}
Also used : DBObject(com.mongodb.DBObject) BasicDBObject(com.mongodb.BasicDBObject) ReflectionUtils.getParameterizedClass(org.mongodb.morphia.utils.ReflectionUtils.getParameterizedClass) ProxiedEntityReference(org.mongodb.morphia.mapping.lazy.proxy.ProxiedEntityReference) Key(org.mongodb.morphia.Key)

Example 2 with Key

use of org.mongodb.morphia.Key in project morphia by mongodb.

the class Mapper method getKey.

/**
     * Gets the Key for an entity
     *
     * @param entity the entity to process
     * @param <T>    the type of the entity
     * @return the Key
     */
public <T> Key<T> getKey(final T entity) {
    T unwrapped = entity;
    if (unwrapped instanceof ProxiedEntityReference) {
        final ProxiedEntityReference proxy = (ProxiedEntityReference) unwrapped;
        return (Key<T>) proxy.__getKey();
    }
    unwrapped = ProxyHelper.unwrap(unwrapped);
    if (unwrapped instanceof Key) {
        return (Key<T>) unwrapped;
    }
    final Object id = getId(unwrapped);
    final Class<T> aClass = (Class<T>) unwrapped.getClass();
    return id == null ? null : new Key<T>(aClass, getCollectionName(aClass), id);
}
Also used : DBObject(com.mongodb.DBObject) BasicDBObject(com.mongodb.BasicDBObject) ReflectionUtils.getParameterizedClass(org.mongodb.morphia.utils.ReflectionUtils.getParameterizedClass) ProxiedEntityReference(org.mongodb.morphia.mapping.lazy.proxy.ProxiedEntityReference) Key(org.mongodb.morphia.Key)

Example 3 with Key

use of org.mongodb.morphia.Key in project morphia by mongodb.

the class Mapper method toMongoObject.

/**
     * Converts a java object to a mongo-compatible object (possibly a DBObject for complex mappings).  Very similar to {@link
     * Mapper#toDBObject}.  Used (mainly) by query/update operations.
     *
     * @param mf    the MappedField for this value
     * @param mc    the MappedClass for this value
     * @param value the value to convert
     * @return the MongoDB compatible object
     */
@SuppressWarnings("deprecation")
public Object toMongoObject(final MappedField mf, final MappedClass mc, final Object value) {
    if (value == null) {
        return null;
    }
    Object mappedValue = value;
    if (value instanceof Query) {
        mappedValue = ((QueryImpl) value).getQueryObject();
    } else if (isAssignable(mf, value) || isEntity(mc)) {
        //convert the value to Key (DBRef) if the field is @Reference or type is Key/DBRef, or if the destination class is an @Entity
        try {
            if (value instanceof Iterable) {
                MappedClass mapped = getMappedClass(mf.getSubClass());
                if (mapped != null && (Key.class.isAssignableFrom(mapped.getClazz()) || mapped.getEntityAnnotation() != null)) {
                    mappedValue = getDBRefs(mf, (Iterable) value);
                } else {
                    if (mf.hasAnnotation(Reference.class)) {
                        mappedValue = getDBRefs(mf, (Iterable) value);
                    } else {
                        mappedValue = toMongoObject(value, false);
                    }
                }
            } else {
                if (mf != null) {
                    Reference refAnn = mf.getAnnotation(Reference.class);
                    Class<?> idType = null;
                    if (!mf.getType().equals(Key.class) && isMapped(mf.getType())) {
                        idType = getMappedClass(mf.getType()).getMappedIdField().getType();
                    }
                    boolean valueIsIdType = mappedValue.getClass().equals(idType);
                    if (refAnn != null) {
                        if (!valueIsIdType) {
                            Key<?> key = value instanceof Key ? (Key<?>) value : getKey(value);
                            if (key != null) {
                                mappedValue = refAnn.idOnly() ? keyToId(key) : keyToDBRef(key);
                            }
                        }
                    } else if (mf.getType().equals(Key.class)) {
                        mappedValue = keyToDBRef(valueIsIdType ? createKey(mf.getSubClass(), value) : value instanceof Key ? (Key<?>) value : getKey(value));
                        if (mappedValue == value) {
                            throw new ValidationException("cannot map to Key<T> field: " + value);
                        }
                    }
                }
                if (mappedValue == value) {
                    mappedValue = toMongoObject(value, false);
                }
            }
        } catch (Exception e) {
            LOG.error("Error converting value(" + value + ") to reference.", e);
            mappedValue = toMongoObject(value, false);
        }
    } else if (mf != null && mf.hasAnnotation(Serialized.class)) {
        //serialized
        try {
            mappedValue = Serializer.serialize(value, !mf.getAnnotation(Serialized.class).disableCompression());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    } else if (value instanceof DBObject) {
        //pass-through
        mappedValue = value;
    } else {
        mappedValue = toMongoObject(value, EmbeddedMapper.shouldSaveClassName(value, mappedValue, mf));
        if (mappedValue instanceof BasicDBList) {
            final BasicDBList list = (BasicDBList) mappedValue;
            if (list.size() != 0) {
                if (!EmbeddedMapper.shouldSaveClassName(extractFirstElement(value), list.get(0), mf)) {
                    for (Object o : list) {
                        if (o instanceof DBObject) {
                            ((DBObject) o).removeField(CLASS_NAME_FIELDNAME);
                        }
                    }
                }
            }
        } else if (mappedValue instanceof DBObject && !EmbeddedMapper.shouldSaveClassName(value, mappedValue, mf)) {
            ((DBObject) mappedValue).removeField(CLASS_NAME_FIELDNAME);
        }
    }
    return mappedValue;
}
Also used : ValidationException(org.mongodb.morphia.query.ValidationException) Query(org.mongodb.morphia.query.Query) ProxiedEntityReference(org.mongodb.morphia.mapping.lazy.proxy.ProxiedEntityReference) Reference(org.mongodb.morphia.annotations.Reference) Serialized(org.mongodb.morphia.annotations.Serialized) IOException(java.io.IOException) DBObject(com.mongodb.DBObject) BasicDBObject(com.mongodb.BasicDBObject) ValidationException(org.mongodb.morphia.query.ValidationException) IOException(java.io.IOException) BasicDBList(com.mongodb.BasicDBList) DBObject(com.mongodb.DBObject) BasicDBObject(com.mongodb.BasicDBObject) ReflectionUtils.getParameterizedClass(org.mongodb.morphia.utils.ReflectionUtils.getParameterizedClass) Key(org.mongodb.morphia.Key)

Example 4 with Key

use of org.mongodb.morphia.Key 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 5 with Key

use of org.mongodb.morphia.Key in project morphia by mongodb.

the class Mapper method getDBRefs.

private Object getDBRefs(final MappedField field, final Iterable value) {
    final List<Object> refs = new ArrayList<Object>();
    Reference annotation = field.getAnnotation(Reference.class);
    boolean idOnly = annotation != null && annotation.idOnly();
    for (final Object o : value) {
        Key<?> key = (o instanceof Key) ? (Key<?>) o : getKey(o);
        refs.add(idOnly ? key.getId() : keyToDBRef(key));
    }
    return refs;
}
Also used : ProxiedEntityReference(org.mongodb.morphia.mapping.lazy.proxy.ProxiedEntityReference) Reference(org.mongodb.morphia.annotations.Reference) ArrayList(java.util.ArrayList) DBObject(com.mongodb.DBObject) BasicDBObject(com.mongodb.BasicDBObject) Key(org.mongodb.morphia.Key)

Aggregations

Key (org.mongodb.morphia.Key)25 DBObject (com.mongodb.DBObject)13 ArrayList (java.util.ArrayList)11 Test (org.junit.Test)8 BasicDBObject (com.mongodb.BasicDBObject)7 MappedField (org.mongodb.morphia.mapping.MappedField)5 ProxiedEntityReference (org.mongodb.morphia.mapping.lazy.proxy.ProxiedEntityReference)5 DBRef (com.mongodb.DBRef)4 Map (java.util.Map)3 ObjectId (org.bson.types.ObjectId)3 FacebookUser (org.mongodb.morphia.TestDatastore.FacebookUser)3 MappedClass (org.mongodb.morphia.mapping.MappedClass)3 Mapper (org.mongodb.morphia.mapping.Mapper)3 ReflectionUtils.getParameterizedClass (org.mongodb.morphia.utils.ReflectionUtils.getParameterizedClass)3 BasicDBList (com.mongodb.BasicDBList)2 HashMap (java.util.HashMap)2 List (java.util.List)2 Datastore (org.mongodb.morphia.Datastore)2 KeysKeysKeys (org.mongodb.morphia.TestDatastore.KeysKeysKeys)2 Reference (org.mongodb.morphia.annotations.Reference)2