Search in sources :

Example 11 with MappedClass

use of org.mongodb.morphia.mapping.MappedClass in project morphia by mongodb.

the class IndexHelperTest method findField.

@Test
public void findField() {
    MappedClass mappedClass = getMorphia().getMapper().getMappedClass(IndexedClass.class);
    assertEquals("indexName", indexHelper.findField(mappedClass, new IndexOptionsBuilder(), singletonList("indexName")));
    assertEquals("nest.name", indexHelper.findField(mappedClass, new IndexOptionsBuilder(), asList("nested", "name")));
    assertEquals("nest.name", indexHelper.findField(mappedClass, new IndexOptionsBuilder(), asList("nest", "name")));
    try {
        assertEquals("nest.whatsit", indexHelper.findField(mappedClass, new IndexOptionsBuilder(), asList("nest", "whatsit")));
        fail("Should have failed on the bad index path");
    } catch (MappingException e) {
    // alles ist gut
    }
    assertEquals("nest.whatsit.nested.more.deeply.than.the.object.model", indexHelper.findField(mappedClass, new IndexOptionsBuilder().disableValidation(true), asList("nest", "whatsit", "nested", "more", "deeply", "than", "the", "object", "model")));
}
Also used : MappedClass(org.mongodb.morphia.mapping.MappedClass) MappingException(org.mongodb.morphia.mapping.MappingException) Test(org.junit.Test)

Example 12 with MappedClass

use of org.mongodb.morphia.mapping.MappedClass 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)

Example 13 with MappedClass

use of org.mongodb.morphia.mapping.MappedClass in project morphia by mongodb.

the class MorphiaTest method testSubPackagesMapping.

@Test
public void testSubPackagesMapping() {
    // when
    final Morphia morphia = new Morphia();
    morphia.getMapper().getOptions().setMapSubPackages(true);
    morphia.mapPackage("org.mongodb.morphia.testmappackage");
    // then
    Collection<MappedClass> mappedClasses = morphia.getMapper().getMappedClasses();
    assertThat(mappedClasses.size(), is(3));
    Collection<Class<?>> classes = new ArrayList<Class<?>>();
    for (MappedClass mappedClass : mappedClasses) {
        classes.add(mappedClass.getClazz());
    }
    assertTrue(classes.contains(SimpleEntity.class));
    assertTrue(classes.contains(SimpleEntityInSubPackage.class));
    assertTrue(classes.contains(SimpleEntityInSubSubPackage.class));
}
Also used : SimpleEntity(org.mongodb.morphia.testmappackage.SimpleEntity) ArrayList(java.util.ArrayList) MappedClass(org.mongodb.morphia.mapping.MappedClass) MappedClass(org.mongodb.morphia.mapping.MappedClass) SimpleEntityInSubPackage(org.mongodb.morphia.testmappackage.testmapsubpackage.SimpleEntityInSubPackage) SimpleEntityInSubSubPackage(org.mongodb.morphia.testmappackage.testmapsubpackage.testmapsubsubpackage.SimpleEntityInSubSubPackage) Test(org.junit.Test)

Example 14 with MappedClass

use of org.mongodb.morphia.mapping.MappedClass in project morphia by mongodb.

the class QueryImpl method getFieldsObject.

@Override
@Deprecated
public DBObject getFieldsObject() {
    DBObject projection = getOptions().getProjection();
    if (projection == null || projection.keySet().size() == 0) {
        return null;
    }
    final MappedClass mc = ds.getMapper().getMappedClass(clazz);
    Entity entityAnnotation = mc.getEntityAnnotation();
    final BasicDBObject fieldsFilter = copy(projection);
    if (includeFields && entityAnnotation != null && !entityAnnotation.noClassnameStored()) {
        fieldsFilter.put(Mapper.CLASS_NAME_FIELDNAME, 1);
    }
    return fieldsFilter;
}
Also used : Entity(org.mongodb.morphia.annotations.Entity) BasicDBObject(com.mongodb.BasicDBObject) MappedClass(org.mongodb.morphia.mapping.MappedClass) DBObject(com.mongodb.DBObject) BasicDBObject(com.mongodb.BasicDBObject)

Example 15 with MappedClass

use of org.mongodb.morphia.mapping.MappedClass in project morphia by mongodb.

the class QueryValidator method validateQuery.

/**
     * Validate the path, and value type, returning the mapped field for the field at the path
     */
static MappedField validateQuery(final Class clazz, final Mapper mapper, final StringBuilder origProp, final FilterOperator op, final Object val, final boolean validateNames, final boolean validateTypes) {
    MappedField mf = null;
    final String prop = origProp.toString();
    boolean hasTranslations = false;
    if (!origProp.substring(0, 1).equals("$")) {
        final String[] parts = prop.split("\\.");
        if (clazz == null) {
            return null;
        }
        MappedClass mc = mapper.getMappedClass(clazz);
        //CHECKSTYLE:OFF
        for (int i = 0; ; ) {
            //CHECKSTYLE:ON
            final String part = parts[i];
            boolean fieldIsArrayOperator = part.equals("$") || part.matches("[0-9]+");
            mf = mc.getMappedField(part);
            //translate from java field name to stored field name
            if (mf == null && !fieldIsArrayOperator) {
                mf = mc.getMappedFieldByJavaField(part);
                if (validateNames && mf == null) {
                    throw new ValidationException(format("The field '%s' could not be found in '%s' while validating - %s; if " + "you wish to continue please disable validation.", part, mc.getClazz().getName(), prop));
                }
                hasTranslations = true;
                if (mf != null) {
                    parts[i] = mf.getNameToStore();
                }
            }
            i++;
            if (mf != null && mf.isMap()) {
                //skip the map key validation, and move to the next part
                i++;
            }
            if (i >= parts.length) {
                break;
            }
            if (!fieldIsArrayOperator) {
                //catch people trying to search/update into @Reference/@Serialized fields
                if (validateNames && !canQueryPast(mf)) {
                    throw new ValidationException(format("Cannot use dot-notation past '%s' in '%s'; found while" + " validating - %s", part, mc.getClazz().getName(), prop));
                }
                if (mf == null && (mc.isInterface() || !validateNames)) {
                    break;
                } else if (mf == null) {
                    throw new ValidationException(format("The field '%s' could not be found in '%s'", prop, mc.getClazz().getName()));
                }
                //get the next MappedClass for the next field validation
                mc = mapper.getMappedClass((mf.isSingleValue()) ? mf.getType() : mf.getSubClass());
            }
        }
        //record new property string if there has been a translation to any part
        if (hasTranslations) {
            // clear existing content
            origProp.setLength(0);
            origProp.append(parts[0]);
            for (int i = 1; i < parts.length; i++) {
                origProp.append('.');
                origProp.append(parts[i]);
            }
        }
        if (validateTypes && mf != null) {
            List<ValidationFailure> typeValidationFailures = new ArrayList<ValidationFailure>();
            boolean compatibleForType = isCompatibleForOperator(mc, mf, mf.getType(), op, val, typeValidationFailures);
            List<ValidationFailure> subclassValidationFailures = new ArrayList<ValidationFailure>();
            boolean compatibleForSubclass = isCompatibleForOperator(mc, mf, mf.getSubClass(), op, val, subclassValidationFailures);
            if ((mf.isSingleValue() && !compatibleForType) || mf.isMultipleValues() && !(compatibleForSubclass || compatibleForType)) {
                if (LOG.isWarningEnabled()) {
                    LOG.warning(format("The type(s) for the query/update may be inconsistent; using an instance of type '%s' " + "for the field '%s.%s' which is declared as '%s'", val.getClass().getName(), mf.getDeclaringClass().getName(), mf.getJavaFieldName(), mf.getType().getName()));
                    typeValidationFailures.addAll(subclassValidationFailures);
                    LOG.warning("Validation warnings: \n" + typeValidationFailures);
                }
            }
        }
    }
    return mf;
}
Also used : MappedField(org.mongodb.morphia.mapping.MappedField) ArrayList(java.util.ArrayList) MappedClass(org.mongodb.morphia.mapping.MappedClass) ValidationFailure(org.mongodb.morphia.query.validation.ValidationFailure)

Aggregations

MappedClass (org.mongodb.morphia.mapping.MappedClass)92 Test (org.junit.Test)73 MappedField (org.mongodb.morphia.mapping.MappedField)56 Mapper (org.mongodb.morphia.mapping.Mapper)53 ArrayList (java.util.ArrayList)48 BasicDBObject (com.mongodb.BasicDBObject)18 DBObject (com.mongodb.DBObject)12 BsonDocument (org.bson.BsonDocument)8 Document (org.bson.Document)8 MappingException (org.mongodb.morphia.mapping.MappingException)6 DBCollection (com.mongodb.DBCollection)5 List (java.util.List)5 SimpleEntity (org.mongodb.morphia.entities.SimpleEntity)5 ObjectId (org.bson.types.ObjectId)4 Key (org.mongodb.morphia.Key)4 Index (org.mongodb.morphia.annotations.Index)4 LinkedHashMap (java.util.LinkedHashMap)3 NotSaved (org.mongodb.morphia.annotations.NotSaved)3 UpdateResults (org.mongodb.morphia.query.UpdateResults)3 WriteResult (com.mongodb.WriteResult)2