Example usage for com.mongodb BasicDBObjectBuilder add

List of usage examples for com.mongodb BasicDBObjectBuilder add

Introduction

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

Prototype

public BasicDBObjectBuilder add(final String key, final Object val) 

Source Link

Document

Same as append

Usage

From source file:com.mingo.mongo.aggregation.AggregationUtils.java

License:Apache License

/**
 * Add field to builder if exist in  parameters.
 *
 * @param builder    {@link BasicDBObjectBuilder}
 * @param fieldName  field name//w ww.j  a  v  a  2  s .c  o  m
 * @param parameters parameters
 */
public static void appendField(BasicDBObjectBuilder builder, String fieldName, Map<String, String> parameters) {
    if (MapUtils.isNotEmpty(parameters) && parameters.containsKey(fieldName)) {
        builder.add(fieldName, parameters.get(fieldName));
    }
}

From source file:com.mingo.mongo.aggregation.AggregationUtils.java

License:Apache License

/**
 * Add field to builder with $ prefix.//from w w  w.ja va  2  s . com
 *
 * @param builder {@link BasicDBObjectBuilder}
 * @param field   field
 */
public static void appendFieldWithSimplePrefix(BasicDBObjectBuilder builder, String field) {
    if (StringUtils.isNotEmpty(field)) {
        builder.add(field, SIMPLE_PREFIX + field);
    }
}

From source file:com.mingo.mongo.aggregation.AggregationUtils.java

License:Apache License

/**
 * Added condition for created field.// w ww  .j a  v a 2  s  .  co m
 *
 * @param builder    {@link BasicDBObjectBuilder}
 * @param field      field
 * @param parameters parameters
 */
public static void addBetweenCriteria(BasicDBObjectBuilder builder, String field,
        Map<String, String> parameters) {
    BasicDBObjectBuilder createdBuilder = start();
    Date startRange = parameters.containsKey(START_DATE) ? convertToDate(parameters.get(START_DATE)) : null;
    Date endRange = parameters.containsKey(END_DATE) ? addDays(convertToDate(parameters.get(END_DATE)), 1)
            : null;

    if (startRange != null) {
        createdBuilder.add(GT.getMongoName(), startRange);
    }
    if (endRange != null) {
        createdBuilder.add(LT.getMongoName(), endRange);
    }
    if (!createdBuilder.isEmpty()) {
        builder.add(field, createdBuilder.get());
    }
}

From source file:com.mobileman.kuravis.core.services.entity.impl.AbstractEntityServiceImpl.java

License:Apache License

@Override
public List<DBObject> findAll(String entityName, String projection, Pageable page) {
    if (page == null) {
        page = new PageRequest(0, Integer.MAX_VALUE);
    }/*w w w  .j ava2  s  .c o  m*/

    DBCursor cursor = null;
    if (StringUtils.isEmpty(projection)) {
        cursor = getCollection(entityName).find(new BasicDBObject());
    } else {
        String[] properties = projection.split(",");
        BasicDBObjectBuilder projectionBuilder = BasicDBObjectBuilder.start();
        boolean idWanted = false;
        for (String property : properties) {
            property = property.trim();
            if (!StringUtils.isEmpty(property)) {
                if (property.equals(EntityUtils.ID)) {
                    idWanted = true;
                }

                projectionBuilder.add(property.trim(), true);
            }
        }

        if (idWanted == false) {
            projectionBuilder.append("_id", false);
        }

        cursor = getCollection(entityName).find(new BasicDBObject(), projectionBuilder.get())
                .sort(new BasicDBObject(projection, 1));
    }

    if (page.getSort() != null) {
        cursor = cursor.sort(createSort(page));
    } else if (projection != null) {
        cursor = cursor.sort(new BasicDBObject(projection, 1));
    }

    cursor = cursor.skip(page.getOffset()).limit(page.getPageSize());

    List<DBObject> result = cursor.toArray();
    return result;
}

From source file:com.mobileman.kuravis.core.services.entity.impl.AbstractEntityServiceImpl.java

License:Apache License

/**
 * @param page/*w  ww.  ja  va  2  s  . c o m*/
 * @return sort DBObject
 */
protected DBObject createSort(Pageable page) {
    if (page.getSort() == null) {
        return null;
    }

    BasicDBObjectBuilder builder = BasicDBObjectBuilder.start();
    Iterator<Order> orderIter = page.getSort().iterator();
    while (orderIter.hasNext()) {
        Order order = orderIter.next();
        builder.add(order.getProperty(), order.getDirection().equals(Direction.ASC) ? 1 : -1);
    }

    return builder.get();
}

From source file:com.mobileman.kuravis.core.services.user.impl.UserServiceImpl.java

License:Apache License

/** 
 * {@inheritDoc}//w  w  w  .  j a v  a  2s  . c  om
 * @see com.mobileman.kuravis.core.services.user.UserService#findUsersByDiseaseAndTreatment(com.mongodb.DBObject, Pageable)
 */
@Override
public List<DBObject> findUsersByDiseaseAndTreatment(DBObject query, Pageable page) {

    BasicDBObjectBuilder builder = BasicDBObjectBuilder.start();

    if (query != null) {
        if (query.containsField("diseaseId")) {
            builder.add("disease." + EntityUtils.ID, query.get("diseaseId"));
        }

        if (query.containsField("treatmentId")) {
            builder.add("treatment." + EntityUtils.ID, query.get("treatmentId"));
        }
    }

    AggregationOutput out = getCollection(TreatmentReview.ENTITY_NAME).aggregate(
            new BasicDBObject("$match", builder.get()),
            new BasicDBObject("$group", new BasicDBObject("_id", new BasicDBObject("_id", "$author._id"))),
            new BasicDBObject("$project", new BasicDBObject(EntityUtils.ID, "$_id._id")),
            new BasicDBObject("$skip", page.getOffset()), new BasicDBObject("$limit", page.getPageSize())

    );

    List<DBObject> result = new ArrayList<>();
    Set<String> userIds = new HashSet<String>();
    for (DBObject dbObject : out.results()) {
        String userId = EntityUtils.getEntityId(dbObject);
        userIds.add(userId);
        result.add(dbObject);
    }

    Map<String, DBObject> usersData = findUsersData(userIds, "name", "gender", "settings.profile");
    for (DBObject user : result) {
        DBObject data = usersData.get(EntityUtils.getEntityId(user));
        if (data != null) {
            user.put("name", data.get("name"));
            user.put("gender", data.get("gender"));
            user.put("settings", data.get("settings"));
        }
    }

    return result;
}

From source file:com.mongodash.appender.MongoDBAppender.java

License:Apache License

@Override
protected void append(LoggingEvent e) {

    BasicDBObjectBuilder objectBuilder = BasicDBObjectBuilder.start().add("ts", new Date(e.getTimeStamp()))
            .add("msg", e.getFormattedMessage()).add("level", e.getLevel().toString())
            .add("logger", e.getLoggerName()).add("thread", e.getThreadName());
    if (e.hasCallerData()) {
        StackTraceElement st = e.getCallerData()[0];
        String callerData = String.format("%s.%s:%d", st.getClassName(), st.getMethodName(),
                st.getLineNumber());/*  w  ww  . jav a2 s  .co  m*/
        objectBuilder.add("caller", callerData);
    }
    Map<String, String> mdc = e.getMdc();
    if (mdc != null && !mdc.isEmpty()) {
        objectBuilder.add("mdc", new BasicDBObject(mdc));
    }
    if (e.getThrowableProxy() != null && _dbEnableStacktrace) {

        String tpAsString = ThrowableProxyUtil.asString(e.getThrowableProxy()); // the
        // stack
        // trace
        // basically
        List<String> stackTrace = Arrays
                .asList(tpAsString.replace("\t", "").split(CoreConstants.LINE_SEPARATOR));
        if (stackTrace.size() > 0) {
            objectBuilder.add("exception", stackTrace.get(0));
        }
        if (stackTrace.size() > 1) {
            objectBuilder.add("stacktrace", stackTrace.subList(1, stackTrace.size()));
        }
    }
    _collection.insert(objectBuilder.get());
}

From source file:de.belaso.mongolyn.ui.TaskDataHandler.java

License:Open Source License

@Override
public RepositoryResponse postTaskData(TaskRepository repository, TaskData taskData,
        Set<TaskAttribute> oldAttributes, IProgressMonitor monitor) throws CoreException {
    DBCollection dbCollection = MongolynUtils.getDBCollection(repository);
    BasicDBObjectBuilder bob = BasicDBObjectBuilder.start();
    for (Map.Entry<String, TaskAttribute> entry : taskData.getRoot().getAttributes().entrySet()) {
        String key = entry.getKey();
        TaskAttribute attribute = entry.getValue();
        String attributeValue = attribute.getValue();
        if (attributeValue != null) {
            bob.add(key.replace('.', '_'), attributeValue);
        }//from  ww  w.ja  v  a2 s.c  o m
    }
    DBObject dbObject = bob.get();
    try {
        if (taskData.isNew()) {
            dbCollection.insert(dbObject, WriteConcern.SAFE);
            return new RepositoryResponse(ResponseKind.TASK_CREATED, dbObject.get("_id").toString());
        } else {
            dbCollection.findAndModify(new BasicDBObject("_id", new ObjectId(taskData.getTaskId())), dbObject);
            return new RepositoryResponse(ResponseKind.TASK_UPDATED, taskData.getTaskId());
        }
    } catch (MongoException mongoException) {
        throw new CoreException(Activator.INSTANCE.getErrorStatus(mongoException));
    }
}

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

License:Apache License

public static void ensureCaps(DB db, String collectionName, ICollectionCap capCollection) {

    if (capCollection != null) {
        long count = capCollection.count();
        long size = capCollection.size();

        if (size == 0)
            throw new ObjectMapperException("Size == 0");
        if ((size < Long.MAX_VALUE) && (count < Long.MAX_VALUE)) {
            try {
                db.requestStart();/*from   w  w  w .j a v  a  2 s  .  c o  m*/
                BasicDBObjectBuilder dbCapOpts = BasicDBObjectBuilder.start("capped", true);
                dbCapOpts.add("size", size);
                if (count > 0)
                    dbCapOpts.add("max", count);
                DBCollection dbColl = db.getCollection(collectionName);

                if (db.getCollectionNames().contains(collectionName)) {
                    DBObject dbResult = db
                            .command(BasicDBObjectBuilder.start("collstats", collectionName).get());
                    if (dbResult.containsField("capped")) {
                        // TODO: check the cap options.
                        _logger.warning(
                                "DBCollection already exists is cap'd already; doing nothing. " + dbResult);
                    } else {
                        _logger.warning("DBCollection already exists with same name(" + collectionName
                                + ") and is not cap'd; not creating cap'd version!");
                    }
                } else {
                    db.createCollection(collectionName, dbCapOpts.get());
                    _logger.info(
                            "Created cap'd DBCollection (" + collectionName + ") with opts " + capCollection);
                }
            } finally {
                Errors.checkError(db, Operation.Insert);
                db.requestDone();
            }
        }
    }
}

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  om
        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();
    }
}