Example usage for com.mongodb BasicDBObjectBuilder BasicDBObjectBuilder

List of usage examples for com.mongodb BasicDBObjectBuilder BasicDBObjectBuilder

Introduction

In this page you can find the example usage for com.mongodb BasicDBObjectBuilder BasicDBObjectBuilder.

Prototype

public BasicDBObjectBuilder() 

Source Link

Document

Creates a builder intialized with an empty document.

Usage

From source file:com.impetus.client.mongodb.DocumentObjectMapper.java

License:Apache License

/**
 * Extract entity field.//from   w w  w  . j a  va  2  s. co  m
 * 
 * @param entity
 *            the entity
 * @param dbObj
 *            the db obj
 * @param column
 *            the column
 * @throws PropertyAccessException
 *             the property access exception
 */
static void extractFieldValue(Object entity, DBObject dbObj, Attribute column) throws PropertyAccessException {
    try {
        Object valueObject = PropertyAccessorHelper.getObject(entity, (Field) column.getJavaMember());

        if (valueObject != null) {
            Class javaType = column.getJavaType();
            switch (AttributeType.getType(javaType)) {
            case MAP:
                Map mapObj = (Map) valueObject;
                // BasicDBObjectBuilder builder =
                // BasicDBObjectBuilder.start(mapObj);
                BasicDBObjectBuilder b = new BasicDBObjectBuilder();
                Iterator i = mapObj.entrySet().iterator();
                while (i.hasNext()) {
                    Map.Entry entry = (Map.Entry) i.next();
                    b.add(entry.getKey().toString(),
                            MongoDBUtils.populateValue(entry.getValue(), entry.getValue().getClass()));
                }
                dbObj.put(((AbstractAttribute) column).getJPAColumnName(), b.get());
                break;
            case SET:
            case LIST:
                Collection collection = (Collection) valueObject;
                BasicDBList basicDBList = new BasicDBList();
                for (Object o : collection) {
                    basicDBList.add(o);
                }
                dbObj.put(((AbstractAttribute) column).getJPAColumnName(), basicDBList);
                break;
            case POINT:

                Point p = (Point) valueObject;
                double[] coordinate = new double[] { p.getX(), p.getY() };
                dbObj.put(((AbstractAttribute) column).getJPAColumnName(), coordinate);
                break;
            case ENUM:
            case PRIMITIVE:
                dbObj.put(((AbstractAttribute) column).getJPAColumnName(),
                        MongoDBUtils.populateValue(valueObject, javaType));
                break;
            }
        }
    } catch (PropertyAccessException paex) {
        log.error("Error while getting column {} value, caused by : .",
                ((AbstractAttribute) column).getJPAColumnName(), paex);
        throw new PersistenceException(paex);
    }
}

From source file:com.softwear.plugins.mongodb.MongoDBScriptObject.java

License:BSD License

public BasicDBObjectBuilder js_getBasicDBObjectBuilder() throws UnknownHostException {
    try {//from   ww w .  j av  a  2s  .  co m
        return new BasicDBObjectBuilder();
    } catch (MongoException e) {
        return null;
    }
}

From source file:de.flapdoodle.mongoom.datastore.Indexes.java

License:Apache License

public static void ensureIndex(DB db, IndexDef index, String collectionName) {

    // public <T> void ensureIndex(Class<T> clazz, String name,
    // Set<IndexFieldDef> defs, boolean unique,
    // boolean dropDupsOnCreate) {
    BasicDBObjectBuilder keys = BasicDBObjectBuilder.start();
    BasicDBObjectBuilder keyOpts = null;
    List<FieldIndex> indexSorted = Lists.newArrayList(index.fields());
    Collections.sort(indexSorted, new Comparator<FieldIndex>() {
        @Override/*from  w  ww. j av  a2 s .c o m*/
        public int compare(FieldIndex o1, FieldIndex o2) {
            if (o1.priority() == o2.priority())
                return 0;
            if (o1.priority() < o2.priority())
                return 1;
            return -1;
        }
    });

    for (FieldIndex def : indexSorted) {
        String fieldName = def.name();
        Direction dir = def.direction();
        if (dir == Direction.BOTH)
            keys.add(fieldName, 1).add(fieldName, -1);
        else
            keys.add(fieldName, (dir == Direction.ASC) ? 1 : -1);
    }

    String name = index.name();

    if (name != null && !name.isEmpty()) {
        if (keyOpts == null)
            keyOpts = new BasicDBObjectBuilder();
        keyOpts.add("name", name);
    }
    if (index.unique()) {
        if (keyOpts == null)
            keyOpts = new BasicDBObjectBuilder();
        keyOpts.add("unique", true);
        if (index.dropDups())
            keyOpts.add("dropDups", true);
    }
    if (index.sparse()) {
        if (keyOpts == null)
            keyOpts = new BasicDBObjectBuilder();
        keyOpts.add("sparse", true);
    }

    try {
        db.requestStart();
        DBCollection dbColl = db.getCollection(collectionName);
        DBObject indexKeys = keys.get();
        //         DatastoreImpl._logger.info("Ensuring index for " + dbColl.getName() + "." + index + " with keys " + indexKeys);
        if (keyOpts == null) {
            _logger.info("Ensuring index for " + dbColl.getName() + "." + index + " with keys " + indexKeys);
            dbColl.ensureIndex(indexKeys);
        } else {
            DBObject options = keyOpts.get();
            _logger.info("Ensuring index for " + dbColl.getName() + "." + index + " with keys " + indexKeys
                    + " and opts " + options);
            dbColl.ensureIndex(indexKeys, options);
        }
    } finally {
        Errors.checkError(db, Operation.Insert);
        db.requestDone();
    }
}

From source file:example.AggregationExample.java

License:Apache License

/**
 * Run this main method to see the output of this quick example.
 *
 * @param args takes no args//from  ww  w .  j  a va  2s  .com
 * @throws UnknownHostException if it cannot connect to a MongoDB instance at localhost:27017
 */
public static void main(final String[] args) throws UnknownHostException {
    // connect to the local database server
    MongoClient mongoClient = new MongoClient();

    // get handle to "mydb"
    DB db = mongoClient.getDB("mydb");

    // Authenticate - optional
    // boolean auth = db.authenticate("foo", "bar");

    // Add some sample data
    DBCollection coll = db.getCollection("aggregationExample");
    coll.insert(new BasicDBObjectBuilder().add("employee", 1).add("department", "Sales").add("amount", 71)
            .add("type", "airfare").get());
    coll.insert(new BasicDBObjectBuilder().add("employee", 2).add("department", "Engineering").add("amount", 15)
            .add("type", "airfare").get());
    coll.insert(new BasicDBObjectBuilder().add("employee", 4).add("department", "Human Resources")
            .add("amount", 5).add("type", "airfare").get());
    coll.insert(new BasicDBObjectBuilder().add("employee", 42).add("department", "Sales").add("amount", 77)
            .add("type", "airfare").get());

    // create our pipeline operations, first with the $match
    DBObject match = new BasicDBObject("$match", new BasicDBObject("type", "airfare"));

    // build the $projection operation
    DBObject fields = new BasicDBObject("department", 1);
    fields.put("amount", 1);
    fields.put("_id", 0);
    DBObject project = new BasicDBObject("$project", fields);

    // Now the $group operation
    DBObject groupFields = new BasicDBObject("_id", "$department");
    groupFields.put("average", new BasicDBObject("$avg", "$amount"));
    DBObject group = new BasicDBObject("$group", groupFields);

    // Finally the $sort operation
    DBObject sort = new BasicDBObject("$sort", new BasicDBObject("average", -1));

    // run aggregation
    List<DBObject> pipeline = Arrays.asList(match, project, group, sort);
    AggregationOutput output = coll.aggregate(pipeline);

    // Output the results
    for (DBObject result : output.results()) {
        System.out.println(result);
    }

    // Aggregation Cursor
    AggregationOptions aggregationOptions = AggregationOptions.builder().batchSize(100)
            .outputMode(AggregationOptions.OutputMode.CURSOR).allowDiskUse(true).build();

    Cursor cursor = coll.aggregate(pipeline, aggregationOptions);
    while (cursor.hasNext()) {
        System.out.println(cursor.next());
    }

    // clean up
    db.dropDatabase();
    mongoClient.close();
}

From source file:example.springdata.mongodb.util.RequiresMongoDB.java

License:Apache License

private void initCurrentVersion() {

    if (currentVersion == null) {
        try {/*from  w w w.ja v  a  2  s  .c  o m*/
            MongoClient client;
            client = new MongoClient(host, port);
            DB db = client.getDB("test");
            CommandResult result = db.command(new BasicDBObjectBuilder().add("buildInfo", 1).get());
            this.currentVersion = Version.parse(result.get("version").toString());
        } catch (com.mongodb.MongoTimeoutException | UnknownHostException e) {
            throw new AssumptionViolatedException("Seems as mongodb server is not running.", e);
        }
    }

}

From source file:ezbake.locksmith.db.RsaLocksmithManager.java

License:Apache License

@Override
public byte[] insertKey(String keyId, byte[] keyData, String owner, String... sharedWith)
        throws KeyExistsException {
    byte[] insertedKey = keyData;

    if (!keyExists(keyId)) {
        BasicDBObject doc = new BasicDBObject(KEY_ID, keyId).append(KEY_DATA, keyData).append(KEY_OWNER, owner)
                .append(ACCESS_LIST, sharedWith);

        mongoService.insertDocumentIntoCollection(getTableName(), doc);
    } else {//from  ww  w . j  a v  a  2s .c om
        // Try to claim ownership
        DBObject keyQuery = keyQuery(keyId);
        DBObject projection = new BasicDBObject(KEY_OWNER, 1).append(KEY_DATA, 1);

        Iterator<DBObject> it = mongoService.findInCollection(getTableName(), keyQuery, projection).iterator();
        if (it.hasNext()) {
            DBObject obj = it.next();
            String keyOwner = (String) obj.get(KEY_OWNER);
            insertedKey = (byte[]) obj.get(KEY_DATA);
            if (keyOwner == null) {
                // Take ownership
                DBObject upd = new BasicDBObjectBuilder().push("$set").add(KEY_OWNER, owner).pop().get();
                DBCollection coll = mongoService.getMongoDB().getCollection(getTableName());
                coll.update(keyQuery, upd);
            } else {
                throw new KeyExistsException("The keyId [" + keyId + "] Already Exists.");
            }
        }
    }
    return insertedKey;
}

From source file:ezbake.locksmith.db.RsaLocksmithManager.java

License:Apache License

public String getPublicKey(String keyId) throws KeyExistsException {
    // Get the key
    DBObject keyQuery = new BasicDBObjectBuilder().add(KEY_ID, keyId).get();
    DBObject projection = new BasicDBObjectBuilder().add(KEY_DATA, 1).get();

    Iterator<DBObject> keyIt = mongoService.findInCollection(getTableName(), keyQuery, projection).iterator();
    byte[] key;//from   w w w.  j  a  v a  2 s .c  o m
    if (keyIt.hasNext()) {
        key = (byte[]) keyIt.next().get(KEY_DATA);
    } else {
        key = generateKey(keyId, null);
    }

    return RSAKeyCrypto.getPublicFromPrivatePEM(new String(key));
}

From source file:mongofx.js.api.Collection.java

License:Open Source License

public ObjectListPresentation distinct(String key, Bindings query) {
    BasicDBObjectBuilder command = new BasicDBObjectBuilder() //
            .add("distinct", name) //
            .add("key", key); //
    if (query != null) {
        command.add("query", query);
    }/*  ww w .  j  av a 2s.c o  m*/

    return singletonIter(mongoDatabase.getMongoDb().runCommand((Bson) command.get()));
}

From source file:mongofx.js.api.Collection.java

License:Open Source License

public ObjectListPresentation mapReduce(String map, String reduce, Bindings options) {
    BasicDBObjectBuilder command = new BasicDBObjectBuilder();
    command.add("mapReduce", name);
    command.add("map", map);
    command.add("reduce", reduce);

    putObject("query", options, command);
    putObject("out", options, command);
    putObject("scope", options, command);
    putSimpleField("field", options, command);
    putSimpleField("jsMode", options, command);
    putSimpleField("finilize", options, command);
    putSimpleField("verbose", options, command);

    return singletonIter(mongoDatabase.getMongoDb().runCommand((Bson) command.get()));
}

From source file:net.cogz.friends.GearzFriends.java

License:Open Source License

public void addFriend(String toUpdate, String toAdd, boolean primary) throws FriendRequestException {
    if (isFriend(toUpdate, toAdd))
        throw new IllegalStateException("Already added");
    DBObject playerDocument = getPlayerDocument(toUpdate);
    Object friendsObj = playerDocument.get("friends");
    if (friendsObj == null || !(friendsObj instanceof BasicDBList)) {
        friendsObj = new BasicDBList();
    }/*from   w  w  w.j a  va 2s  .  c om*/
    BasicDBList friendsList = (BasicDBList) friendsObj;
    if (!hasRequest(toUpdate, toAdd)) {
        throw new FriendRequestException("No request found");
    } else {
        DBObject newFriend = new BasicDBObjectBuilder().add("name", getObjectId(getPlayerDocument(toAdd)))
                .add("added", new Date()).get();
        friendsList.add(newFriend);
        if (primary) {
            addFriendRequest(toAdd, toUpdate);
            addFriend(toAdd, toUpdate, false);
        }
        denyFriendRequest(toUpdate, toAdd);
    }
    playerDocument.put("friends", friendsList);
    getCollection().save(playerDocument);
}