Search in sources :

Example 1 with ValidationException

use of org.mongodb.morphia.query.ValidationException in project morphia by mongodb.

the class PathTarget method resolve.

private void resolve() {
    context = this.root;
    position = 0;
    MappedField field = null;
    while (hasNext()) {
        String segment = next();
        if (segment.equals("$") || segment.matches("[0-9]+")) {
            // array operator
            if (!hasNext()) {
                return;
            }
            segment = next();
        }
        field = resolveField(segment);
        if (field != null) {
            translate(field.getNameToStore());
            if (field.isMap() && hasNext()) {
                // consume the map key segment
                next();
            }
        } else {
            if (validateNames) {
                throw new ValidationException(format("Could not resolve path '%s' against '%s'.", join(segments, '.'), root.getClazz().getName()));
            }
        }
    }
    target = field;
    resolved = true;
}
Also used : MappedField(org.mongodb.morphia.mapping.MappedField) ValidationException(org.mongodb.morphia.query.ValidationException)

Example 2 with ValidationException

use of org.mongodb.morphia.query.ValidationException 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 3 with ValidationException

use of org.mongodb.morphia.query.ValidationException in project morphia by mongodb.

the class EmbeddedMappingTest method testNestedInterfaces.

@Test
public void testNestedInterfaces() {
    getMorphia().map(WithNested.class, NestedImpl.class);
    getDs().ensureIndexes();
    final List<DBObject> indexInfo = getDs().getCollection(WithNested.class).getIndexInfo();
    boolean indexFound = false;
    for (DBObject dbObject : indexInfo) {
        indexFound |= "nested.field.fail".equals(((DBObject) dbObject.get("key")).keySet().iterator().next());
    }
    Assert.assertTrue("Should find the nested field index", indexFound);
    WithNested nested = new WithNested();
    nested.nested = new NestedImpl("nested value");
    getDs().save(nested);
    WithNested found;
    try {
        getDs().find(WithNested.class).field("nested.field").equal("nested value").get();
        Assert.fail("Querying against an interface should fail validation");
    } catch (ValidationException ignore) {
    // all good
    }
    found = getDs().find(WithNested.class).disableValidation().field("nested.field").equal("nested value").get();
    Assert.assertNotNull(found);
    Assert.assertEquals(nested, found);
    found = getDs().find(WithNested.class).disableValidation().field("nested.field.fails").equal("nested value").get();
    Assert.assertNull(found);
}
Also used : ValidationException(org.mongodb.morphia.query.ValidationException) DBObject(com.mongodb.DBObject) Test(org.junit.Test)

Aggregations

ValidationException (org.mongodb.morphia.query.ValidationException)3 DBObject (com.mongodb.DBObject)2 BasicDBList (com.mongodb.BasicDBList)1 BasicDBObject (com.mongodb.BasicDBObject)1 IOException (java.io.IOException)1 Test (org.junit.Test)1 Key (org.mongodb.morphia.Key)1 Reference (org.mongodb.morphia.annotations.Reference)1 Serialized (org.mongodb.morphia.annotations.Serialized)1 MappedField (org.mongodb.morphia.mapping.MappedField)1 ProxiedEntityReference (org.mongodb.morphia.mapping.lazy.proxy.ProxiedEntityReference)1 Query (org.mongodb.morphia.query.Query)1 ReflectionUtils.getParameterizedClass (org.mongodb.morphia.utils.ReflectionUtils.getParameterizedClass)1