Search in sources :

Example 71 with DBObject

use of com.mongodb.DBObject in project mongo-java-driver by mongodb.

the class JSONTest method testIllegalEscape.

// This is not correct behavior, but adding the test here to document it.  It should probably throw a JSONParseException due to the
// illegal escape of \m.
@Test
public void testIllegalEscape() {
    DBObject obj = (DBObject) JSON.parse("{ 'x' : '\\m' }");
    assertEquals("m", obj.get("x"));
}
Also used : BasicDBObject(com.mongodb.BasicDBObject) DBObject(com.mongodb.DBObject) Test(org.junit.Test)

Example 72 with DBObject

use of com.mongodb.DBObject in project mongo-java-driver by mongodb.

the class JSONTest method testRegexNoOptions.

@Test
public void testRegexNoOptions() {
    String x = "^Hello$";
    String serializedPattern = "{ \"$regex\" : \"" + x + "\"}";
    Pattern pattern = Pattern.compile(x);
    assertEquals(JSON.serialize(pattern), serializedPattern);
    BasicDBObject a = new BasicDBObject("x", pattern);
    assertEquals(a.toString(), "{ \"x\" : " + serializedPattern + "}");
    DBObject b = (DBObject) JSON.parse(a.toString());
    assertEquals(Pattern.class, b.get("x").getClass());
    assertEquals(b.toString(), a.toString());
}
Also used : Pattern(java.util.regex.Pattern) BasicDBObject(com.mongodb.BasicDBObject) BasicDBObject(com.mongodb.BasicDBObject) DBObject(com.mongodb.DBObject) Test(org.junit.Test)

Example 73 with DBObject

use of com.mongodb.DBObject in project mongo-java-driver by mongodb.

the class JSONCallbackTest method encodingHooks.

@Test
public void encodingHooks() {
    BSON.addDecodingHook(Date.class, new Transformer() {

        @Override
        public Object transform(final Object o) {
            return ((Date) o).getTime();
        }
    });
    try {
        Date now = new Date();
        Object parsedDate = JSON.parse("{ \"$date\" : " + now.getTime() + "}");
        assertEquals(Long.class, parsedDate.getClass());
        DBObject doc = (DBObject) JSON.parse("{ date : { \"$date\" : " + now.getTime() + "} }");
        assertEquals(Long.class, doc.get("date").getClass());
    } finally {
        BSON.removeDecodingHooks(Date.class);
    }
}
Also used : Transformer(org.bson.Transformer) DBObject(com.mongodb.DBObject) DBObject(com.mongodb.DBObject) Date(java.util.Date) Test(org.junit.Test)

Example 74 with DBObject

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

the class GeometryConverter method decode.

@Override
public Object decode(final Class<?> targetClass, final Object fromDBObject, final MappedField optionalExtraInfo) {
    DBObject dbObject = (DBObject) fromDBObject;
    String type = (String) dbObject.get("type");
    return getMapper().getConverters().decode(GeoJsonType.fromString(type).getTypeClass(), fromDBObject, optionalExtraInfo);
}
Also used : DBObject(com.mongodb.DBObject)

Example 75 with DBObject

use of com.mongodb.DBObject 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)

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