Search in sources :

Example 1 with DBRef

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

the class BasicBSONEncoder method _putObjectField.

/**
     * Encodes any Object type
     *
     * @param name         the field name
     * @param initialValue the value to write
     */
protected void _putObjectField(final String name, final Object initialValue) {
    if ("_transientFields".equals(name)) {
        return;
    }
    if (name.contains("\0")) {
        throw new IllegalArgumentException("Document field names can't have a NULL character. (Bad Key: '" + name + "')");
    }
    if ("$where".equals(name) && initialValue instanceof String) {
        putCode(name, new Code((String) initialValue));
    }
    Object value = BSON.applyEncodingHooks(initialValue);
    if (value == null) {
        putNull(name);
    } else if (value instanceof Date) {
        putDate(name, (Date) value);
    } else if (value instanceof Number) {
        putNumber(name, (Number) value);
    } else if (value instanceof Decimal128) {
        putDecimal128(name, (Decimal128) value);
    } else if (value instanceof Character) {
        putString(name, value.toString());
    } else if (value instanceof String) {
        putString(name, value.toString());
    } else if (value instanceof ObjectId) {
        putObjectId(name, (ObjectId) value);
    } else if (value instanceof Boolean) {
        putBoolean(name, (Boolean) value);
    } else if (value instanceof Pattern) {
        putPattern(name, (Pattern) value);
    } else if (value instanceof Iterable) {
        putIterable(name, (Iterable) value);
    } else if (value instanceof BSONObject) {
        putObject(name, (BSONObject) value);
    } else if (value instanceof Map) {
        putMap(name, (Map) value);
    } else if (value instanceof byte[]) {
        putBinary(name, (byte[]) value);
    } else if (value instanceof Binary) {
        putBinary(name, (Binary) value);
    } else if (value instanceof UUID) {
        putUUID(name, (UUID) value);
    } else if (value.getClass().isArray()) {
        putArray(name, value);
    } else if (value instanceof Symbol) {
        putSymbol(name, (Symbol) value);
    } else if (value instanceof BSONTimestamp) {
        putTimestamp(name, (BSONTimestamp) value);
    } else if (value instanceof CodeWScope) {
        putCodeWScope(name, (CodeWScope) value);
    } else if (value instanceof Code) {
        putCode(name, (Code) value);
    } else if (value instanceof DBRef) {
        BSONObject temp = new BasicBSONObject();
        DBRef dbRef = (DBRef) value;
        temp.put("$ref", dbRef.getCollectionName());
        temp.put("$id", dbRef.getId());
        if (dbRef.getDatabaseName() != null) {
            temp.put("$db", dbRef.getDatabaseName());
        }
        putObject(name, temp);
    } else if (value instanceof MinKey) {
        putMinKey(name);
    } else if (value instanceof MaxKey) {
        putMaxKey(name);
    } else if (putSpecial(name, value)) {
    // no-op
    } else {
        throw new IllegalArgumentException("Can't serialize " + value.getClass());
    }
}
Also used : Pattern(java.util.regex.Pattern) ObjectId(org.bson.types.ObjectId) Symbol(org.bson.types.Symbol) DBRef(com.mongodb.DBRef) MaxKey(org.bson.types.MaxKey) BSONTimestamp(org.bson.types.BSONTimestamp) Decimal128(org.bson.types.Decimal128) Code(org.bson.types.Code) Date(java.util.Date) CodeWScope(org.bson.types.CodeWScope) MinKey(org.bson.types.MinKey) Binary(org.bson.types.Binary) UUID(java.util.UUID) Map(java.util.Map)

Example 2 with DBRef

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

the class JSONCallbackTest method refParsing.

@Test
public void refParsing() {
    DBRef ref = (DBRef) JSON.parse(("{ \"$ref\" : \"friends\", \"$id\" : { \"$oid\" : \"01234567890123456789abcd\" } }"));
    assertEquals("friends", ref.getCollectionName());
    assertEquals(new ObjectId("01234567890123456789abcd"), ref.getId());
}
Also used : ObjectId(org.bson.types.ObjectId) DBRef(com.mongodb.DBRef) Test(org.junit.Test)

Example 3 with DBRef

use of com.mongodb.DBRef 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 4 with DBRef

use of com.mongodb.DBRef in project spring-data-mongodb by spring-projects.

the class MappingMongoConverter method readMap.

/**
 * Reads the given {@link Document} into a {@link Map}. will recursively resolve nested {@link Map}s as well.
 *
 * @param type the {@link Map} {@link TypeInformation} to be used to unmarshall this {@link Document}.
 * @param bson must not be {@literal null}
 * @param path must not be {@literal null}
 * @return
 */
@SuppressWarnings("unchecked")
protected Map<Object, Object> readMap(TypeInformation<?> type, Bson bson, ObjectPath path) {
    Assert.notNull(bson, "Document must not be null!");
    Assert.notNull(path, "Object path must not be null!");
    Class<?> mapType = typeMapper.readType(bson, type).getType();
    TypeInformation<?> keyType = type.getComponentType();
    TypeInformation<?> valueType = type.getMapValueType();
    Class<?> rawKeyType = keyType != null ? keyType.getType() : null;
    Class<?> rawValueType = valueType != null ? valueType.getType() : null;
    Map<String, Object> sourceMap = asMap(bson);
    Map<Object, Object> map = CollectionFactory.createMap(mapType, rawKeyType, sourceMap.keySet().size());
    if (!DBRef.class.equals(rawValueType) && isCollectionOfDbRefWhereBulkFetchIsPossible(sourceMap.values())) {
        bulkReadAndConvertDBRefMapIntoTarget(valueType, rawValueType, sourceMap, map);
        return map;
    }
    for (Entry<String, Object> entry : sourceMap.entrySet()) {
        if (typeMapper.isTypeKey(entry.getKey())) {
            continue;
        }
        Object key = potentiallyUnescapeMapKey(entry.getKey());
        if (rawKeyType != null && !rawKeyType.isAssignableFrom(key.getClass())) {
            key = conversionService.convert(key, rawKeyType);
        }
        Object value = entry.getValue();
        TypeInformation<?> defaultedValueType = valueType != null ? valueType : ClassTypeInformation.OBJECT;
        if (value instanceof Document) {
            map.put(key, read(defaultedValueType, (Document) value, path));
        } else if (value instanceof BasicDBObject) {
            map.put(key, read(defaultedValueType, (BasicDBObject) value, path));
        } else if (value instanceof DBRef) {
            map.put(key, DBRef.class.equals(rawValueType) ? value : readAndConvertDBRef((DBRef) value, defaultedValueType, ObjectPath.ROOT, rawValueType));
        } else if (value instanceof List) {
            map.put(key, readCollectionOrArray(valueType != null ? valueType : ClassTypeInformation.LIST, (List<Object>) value, path));
        } else {
            map.put(key, getPotentiallyConvertedSimpleRead(value, rawValueType));
        }
    }
    return map;
}
Also used : BasicDBObject(com.mongodb.BasicDBObject) DBRef(com.mongodb.DBRef) DBObject(com.mongodb.DBObject) BasicDBObject(com.mongodb.BasicDBObject) BasicDBList(com.mongodb.BasicDBList) List(java.util.List) ArrayList(java.util.ArrayList) Document(org.bson.Document)

Example 5 with DBRef

use of com.mongodb.DBRef in project teiid by teiid.

the class MongoDBExecutionFactory method retrieveValue.

/**
 * @param field
 * @param expectedClass
 * @return
 * @throws TranslatorException
 */
public Object retrieveValue(Object value, Class<?> expectedClass, DB mongoDB, String fqn, String colName) throws TranslatorException {
    if (value == null) {
        return null;
    }
    if (value.getClass().equals(expectedClass)) {
        return value;
    }
    if (value instanceof DBRef) {
        Object obj = ((DBRef) value).getId();
        if (obj instanceof BasicDBObject) {
            BasicDBObject bdb = (BasicDBObject) obj;
            return bdb.get(colName);
        }
        return obj;
    } else if (value instanceof java.util.Date && expectedClass.equals(java.sql.Date.class)) {
        return new java.sql.Date(((java.util.Date) value).getTime());
    } else if (value instanceof java.util.Date && expectedClass.equals(java.sql.Timestamp.class)) {
        return new java.sql.Timestamp(((java.util.Date) value).getTime());
    } else if (value instanceof java.util.Date && expectedClass.equals(java.sql.Time.class)) {
        return new java.sql.Time(((java.util.Date) value).getTime());
    } else if (value instanceof String && expectedClass.equals(BigDecimal.class)) {
        return new BigDecimal((String) value);
    } else if (value instanceof String && expectedClass.equals(BigInteger.class)) {
        return new BigInteger((String) value);
    } else if (value instanceof String && expectedClass.equals(Character.class)) {
        return new Character(((String) value).charAt(0));
    } else if (value instanceof String && expectedClass.equals(BinaryType.class)) {
        return new BinaryType(((String) value).getBytes());
    } else if (value instanceof String && expectedClass.equals(Blob.class)) {
        GridFS gfs = new GridFS(mongoDB, fqn);
        final GridFSDBFile resource = gfs.findOne((String) value);
        if (resource == null) {
            return null;
        }
        return new BlobImpl(new InputStreamFactory() {

            @Override
            public InputStream getInputStream() throws IOException {
                return resource.getInputStream();
            }
        });
    } else if (value instanceof String && expectedClass.equals(Clob.class)) {
        GridFS gfs = new GridFS(mongoDB, fqn);
        final GridFSDBFile resource = gfs.findOne((String) value);
        if (resource == null) {
            return null;
        }
        return new ClobImpl(new InputStreamFactory() {

            @Override
            public InputStream getInputStream() throws IOException {
                return resource.getInputStream();
            }
        }, -1);
    } else if (value instanceof String && expectedClass.equals(SQLXML.class)) {
        GridFS gfs = new GridFS(mongoDB, fqn);
        final GridFSDBFile resource = gfs.findOne((String) value);
        if (resource == null) {
            return null;
        }
        return new SQLXMLImpl(new InputStreamFactory() {

            @Override
            public InputStream getInputStream() throws IOException {
                return resource.getInputStream();
            }
        });
    } else if (value instanceof BasicDBList) {
        BasicDBList arrayValues = (BasicDBList) value;
        // array
        if (expectedClass.isArray() && !(arrayValues.get(0) instanceof BasicDBObject)) {
            Class arrayType = expectedClass.getComponentType();
            Object array = Array.newInstance(arrayType, arrayValues.size());
            for (int i = 0; i < arrayValues.size(); i++) {
                Object arrayItem = retrieveValue(arrayValues.get(i), arrayType, mongoDB, fqn, colName);
                Array.set(array, i, arrayItem);
            }
            value = array;
        }
    } else if (value instanceof org.bson.types.ObjectId) {
        org.bson.types.ObjectId id = (org.bson.types.ObjectId) value;
        value = id.toHexString();
    } else {
        Transform transform = DataTypeManager.getTransform(value.getClass(), expectedClass);
        if (transform != null) {
            try {
                value = transform.transform(value, expectedClass);
            } catch (TransformationException e) {
                throw new TranslatorException(e);
            }
        }
    }
    return value;
}
Also used : InputStreamFactory(org.teiid.core.types.InputStreamFactory) BasicDBObject(com.mongodb.BasicDBObject) BlobImpl(org.teiid.core.types.BlobImpl) ClobImpl(org.teiid.core.types.ClobImpl) Blob(java.sql.Blob) SQLXMLImpl(org.teiid.core.types.SQLXMLImpl) TransformationException(org.teiid.core.types.TransformationException) BinaryType(org.teiid.core.types.BinaryType) InputStream(java.io.InputStream) DBRef(com.mongodb.DBRef) IOException(java.io.IOException) GridFS(com.mongodb.gridfs.GridFS) BigDecimal(java.math.BigDecimal) BasicDBList(com.mongodb.BasicDBList) SQLXML(java.sql.SQLXML) GridFSDBFile(com.mongodb.gridfs.GridFSDBFile) BigInteger(java.math.BigInteger) BasicDBObject(com.mongodb.BasicDBObject) Transform(org.teiid.core.types.Transform)

Aggregations

DBRef (com.mongodb.DBRef)68 Document (org.bson.Document)26 Test (org.junit.jupiter.api.Test)24 BasicDBObject (com.mongodb.BasicDBObject)22 ObjectId (org.bson.types.ObjectId)20 DBObject (com.mongodb.DBObject)17 MongoPersistentProperty (org.springframework.data.mongodb.core.mapping.MongoPersistentProperty)13 BasicDBList (com.mongodb.BasicDBList)11 ArrayList (java.util.ArrayList)7 Binary (org.bson.types.Binary)7 Test (org.junit.Test)6 Document (org.springframework.data.mongodb.core.mapping.Document)6 DBCollection (com.mongodb.DBCollection)5 Map (java.util.Map)5 BasicBSONObject (org.bson.BasicBSONObject)5 Date (java.util.Date)4 List (java.util.List)4 UUID (java.util.UUID)4 Bson (org.bson.conversions.Bson)4 MaxKey (org.bson.types.MaxKey)4