Search in sources :

Example 51 with DBObject

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

the class Decimal128LegacyAPIQuickTour method main.

/**
     * Run this main method to see the output of this quick example.
     *
     * @param args takes an optional single argument for the connection string
     */
public static void main(final String[] args) {
    MongoClient mongoClient;
    if (args.length == 0) {
        // connect to the local database server
        mongoClient = new MongoClient();
    } else {
        mongoClient = new MongoClient(new MongoClientURI(args[0]));
    }
    // get handle to "mydb" database
    DB database = mongoClient.getDB("mydb");
    // get a handle to the "test" collection
    DBCollection collection = database.getCollection("test");
    // drop all the data in it
    collection.drop();
    // make a document and insert it
    BasicDBObject doc = new BasicDBObject("name", "MongoDB").append("amount1", Decimal128.parse(".10")).append("amount2", new Decimal128(42L)).append("amount3", new Decimal128(new BigDecimal(".200")));
    collection.insert(doc);
    DBObject first = collection.findOne(QueryBuilder.start("amount1").is(new Decimal128(new BigDecimal(".10"))).get());
    Decimal128 amount3 = (Decimal128) first.get("amount3");
    BigDecimal amount2AsBigDecimal = amount3.bigDecimalValue();
    System.out.println(amount3.toString());
    System.out.println(amount2AsBigDecimal.toString());
}
Also used : MongoClient(com.mongodb.MongoClient) DBCollection(com.mongodb.DBCollection) BasicDBObject(com.mongodb.BasicDBObject) MongoClientURI(com.mongodb.MongoClientURI) Decimal128(org.bson.types.Decimal128) DBObject(com.mongodb.DBObject) BasicDBObject(com.mongodb.BasicDBObject) DB(com.mongodb.DB) BigDecimal(java.math.BigDecimal)

Example 52 with DBObject

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

the class CLI method main.

// CHECKSTYLE:OFF
public static void main(final String[] args) throws Exception {
    if (args.length < 1) {
        printUsage();
        return;
    }
    for (int i = 0; i < args.length; i++) {
        String s = args[i];
        if (s.equals("--db")) {
            db = args[i + 1];
            i++;
            continue;
        }
        if (s.equals("--host")) {
            host = args[i + 1];
            i++;
            continue;
        }
        if (s.equals("help")) {
            printUsage();
            return;
        }
        if (s.equals("list")) {
            GridFS fs = getGridFS();
            System.out.printf("%-60s %-10s%n", "Filename", "Length");
            DBCursor fileListCursor = fs.getFileList();
            try {
                while (fileListCursor.hasNext()) {
                    DBObject o = fileListCursor.next();
                    System.out.printf("%-60s %-10d%n", o.get("filename"), ((Number) o.get("length")).longValue());
                }
            } finally {
                fileListCursor.close();
            }
            return;
        }
        if (s.equals("get")) {
            GridFS fs = getGridFS();
            String fn = args[i + 1];
            GridFSDBFile f = fs.findOne(fn);
            if (f == null) {
                System.err.println("can't find file: " + fn);
                return;
            }
            f.writeTo(f.getFilename());
            return;
        }
        if (s.equals("put")) {
            GridFS fs = getGridFS();
            String fn = args[i + 1];
            GridFSInputFile f = fs.createFile(new File(fn));
            f.save();
            f.validate();
            return;
        }
        if (s.equals("md5")) {
            GridFS fs = getGridFS();
            String fn = args[i + 1];
            GridFSDBFile f = fs.findOne(fn);
            if (f == null) {
                System.err.println("can't find file: " + fn);
                return;
            }
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            md5.reset();
            int read = 0;
            DigestInputStream is = new DigestInputStream(f.getInputStream(), md5);
            try {
                while (is.read() >= 0) {
                    read++;
                    int r = is.read(new byte[17]);
                    if (r < 0) {
                        break;
                    }
                    read += r;
                }
            } finally {
                is.close();
            }
            byte[] digest = md5.digest();
            System.out.println("length: " + read + " md5: " + Util.toHex(digest));
            return;
        }
        System.err.println("unknown option: " + s);
        return;
    }
}
Also used : DBCursor(com.mongodb.DBCursor) DigestInputStream(java.security.DigestInputStream) MessageDigest(java.security.MessageDigest) DBObject(com.mongodb.DBObject) File(java.io.File)

Example 53 with DBObject

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

the class DatastoreImpl method ensureCaps.

@Override
public void ensureCaps() {
    for (final MappedClass mc : mapper.getMappedClasses()) {
        if (mc.getEntityAnnotation() != null && mc.getEntityAnnotation().cap().value() > 0) {
            final CappedAt cap = mc.getEntityAnnotation().cap();
            final String collName = mapper.getCollectionName(mc.getClazz());
            final BasicDBObjectBuilder dbCapOpts = start("capped", true);
            if (cap.value() > 0) {
                dbCapOpts.add("size", cap.value());
            }
            if (cap.count() > 0) {
                dbCapOpts.add("max", cap.count());
            }
            final DB database = getDB();
            if (database.getCollectionNames().contains(collName)) {
                final DBObject dbResult = database.command(start("collstats", collName).get());
                if (dbResult.containsField("capped")) {
                    LOG.debug("DBCollection already exists and is capped already; doing nothing. " + dbResult);
                } else {
                    LOG.warning("DBCollection already exists with same name(" + collName + ") and is not capped; not creating capped version!");
                }
            } else {
                getDB().createCollection(collName, dbCapOpts.get());
                LOG.debug("Created capped DBCollection (" + collName + ") with opts " + dbCapOpts);
            }
        }
    }
}
Also used : CappedAt(org.mongodb.morphia.annotations.CappedAt) BasicDBObjectBuilder(com.mongodb.BasicDBObjectBuilder) MappedClass(org.mongodb.morphia.mapping.MappedClass) DBObject(com.mongodb.DBObject) BasicDBObject(com.mongodb.BasicDBObject) DB(com.mongodb.DB)

Example 54 with DBObject

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

the class DatastoreImpl method getByKey.

@Override
public <T> T getByKey(final Class<T> clazz, final Key<T> key) {
    final String collectionName = mapper.getCollectionName(clazz);
    final String keyCollection = mapper.updateCollection(key);
    if (!collectionName.equals(keyCollection)) {
        throw new RuntimeException("collection names don't match for key and class: " + collectionName + " != " + keyCollection);
    }
    Object id = key.getId();
    if (id instanceof DBObject) {
        ((DBObject) id).removeField(Mapper.CLASS_NAME_FIELDNAME);
    }
    return get(clazz, id);
}
Also used : DBObject(com.mongodb.DBObject) BasicDBObject(com.mongodb.BasicDBObject) DBObject(com.mongodb.DBObject) BasicDBObject(com.mongodb.BasicDBObject)

Example 55 with DBObject

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

the class DatastoreImpl method save.

protected <T> Key<T> save(final DBCollection dbColl, final T entity, final InsertOptions options) {
    if (entity == null) {
        throw new UpdateException("Can not persist a null entity");
    }
    final MappedClass mc = mapper.getMappedClass(entity);
    if (mc.getAnnotation(NotSaved.class) != null) {
        throw new MappingException(format("Entity type: %s is marked as NotSaved which means you should not try to save it!", mc.getClazz().getName()));
    }
    // involvedObjects is used not only as a cache but also as a list of what needs to be called for life-cycle methods at the end.
    final LinkedHashMap<Object, DBObject> involvedObjects = new LinkedHashMap<Object, DBObject>();
    final DBObject document = entityToDBObj(entity, involvedObjects);
    // try to do an update if there is a @Version field
    final Object idValue = document.get(Mapper.ID_KEY);
    WriteResult wr = tryVersionedUpdate(dbColl, entity, document, idValue, enforceWriteConcern(options, entity.getClass()), mc);
    if (wr == null) {
        saveDocument(dbColl, document, options);
    }
    return postSaveOperations(singletonList(entity), involvedObjects, dbColl).get(0);
}
Also used : WriteResult(com.mongodb.WriteResult) NotSaved(org.mongodb.morphia.annotations.NotSaved) DBObject(com.mongodb.DBObject) BasicDBObject(com.mongodb.BasicDBObject) UpdateException(org.mongodb.morphia.query.UpdateException) MappedClass(org.mongodb.morphia.mapping.MappedClass) DBObject(com.mongodb.DBObject) BasicDBObject(com.mongodb.BasicDBObject) MappingException(org.mongodb.morphia.mapping.MappingException) LinkedHashMap(java.util.LinkedHashMap)

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