Example usage for com.mongodb BasicDBObject append

List of usage examples for com.mongodb BasicDBObject append

Introduction

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

Prototype

@Override
public BasicDBObject append(final String key, final Object val) 

Source Link

Document

Add a key/value pair to this object

Usage

From source file:com.redhat.lightblue.mongo.crud.DocTranslator.java

License:Open Source License

private void toBson(BasicDBObject dest, SimpleField fieldMd, Path path, JsonNode node, EntityMetadata md) {
    Object value = toValue(fieldMd.getType(), node);
    // Should we add fields with null values to the bson doc? Answer: no
    if (value != null) {
        if (path.equals(ID_PATH)) {
            value = createIdFrom(value);
        }//from   w w w .  jav  a2 s .  co  m
        dest.append(path.tail(0), value);
    }
}

From source file:com.redhat.lightblue.mongo.crud.DocTranslator.java

License:Open Source License

private void convertObjectFieldToBson(JsonNode node, JsonNodeCursor cursor, BasicDBObject ret, Path path,
        EntityMetadata md, ResultMetadata rmd) {
    if (node != null) {
        if (node instanceof ObjectNode) {
            if (cursor.firstChild()) {
                ret.append(path.tail(0), objectToBson(cursor, md, rmd));
                cursor.parent();/*w  w w .j  av a 2  s .  c o m*/
            }
        } else if (node instanceof NullNode) {
            ret.append(path.tail(0), null);
        } else {
            throw Error.get(ERR_INVALID_FIELD, path.toString());
        }
    }
}

From source file:com.redhat.lightblue.mongo.crud.DocTranslator.java

License:Open Source License

private void convertArrayFieldToBson(JsonNode node, JsonNodeCursor cursor, BasicDBObject ret,
        FieldTreeNode fieldMdNode, Path path, EntityMetadata md, ResultMetadata rmd) {
    if (node != null) {
        if (node instanceof ArrayNode) {
            if (cursor.firstChild()) {
                ret.append(path.tail(0), arrayToBson(cursor, ((ArrayField) fieldMdNode).getElement(), md, rmd));
                cursor.parent();//  ww  w. ja v  a 2 s  .co m
            } else {
                // empty array! add an empty list.
                ret.append(path.tail(0), new ArrayList());
            }
        } else if (node instanceof NullNode) {
            ret.append(path.tail(0), null);
        } else {
            throw Error.get(ERR_INVALID_FIELD, path.toString());
        }
    }
}

From source file:com.redhat.lightblue.mongo.crud.ExpressionTranslator.java

License:Open Source License

/**
 * Writes a MongoDB projection containing fields to evaluate the projection,
 * sort, and query//from  ww w  .  j  ava 2  s  .  c  om
 */
public DBObject translateProjection(EntityMetadata md, Projection p, QueryExpression q, Sort s) {
    Set<Path> fields = getRequiredFields(md, p, q, s);
    BasicDBObject ret = new BasicDBObject();
    for (Path f : fields) {
        ret.append(translatePath(f), 1);
    }
    ret.append(translatePath(DocTranslator.HIDDEN_SUB_PATH), 1);
    LOGGER.debug("Resulting projection:{}", ret);
    return ret;
}

From source file:com.redhat.lightblue.mongo.crud.ExpressionTranslator.java

License:Open Source License

private DBObject translateRegexMatchExpression(FieldTreeNode context, EntityMetadata md,
        RegexMatchExpression expr, EntityMetadata emd, MutablePath fullPath) {
    FieldInfo finfo = resolveFieldForQuery(context, fullPath.immutableCopy(), expr.getField());

    fullPath.push(finfo.field);//from ww  w  .  j  av  a 2 s. com
    StringBuilder options = new StringBuilder();
    BasicDBObject regex = new BasicDBObject("$regex", expr.getRegex());
    Path field = finfo.field;

    if (expr.isCaseInsensitive()) {
        options.append('i');
        for (Index index : emd.getEntityInfo().getIndexes().getIndexes()) {
            if (index.isCaseInsensitiveKey(fullPath)) {
                field = DocTranslator.getHiddenForField(finfo.field);
                regex.replace("$regex", expr.getRegex().toUpperCase());
                options.deleteCharAt(options.length() - 1);
                break;
            }
        }
    }
    if (expr.isMultiline()) {
        options.append('m');
    }
    if (expr.isExtended()) {
        options.append('x');
    }
    if (expr.isDotAll()) {
        options.append('s');
    }
    String opStr = options.toString();
    if (opStr.length() > 0) {
        regex.append("$options", opStr);
    }
    fullPath.pop();
    return new BasicDBObject(translatePath(field), regex);
}

From source file:com.redhat.lightblue.mongo.crud.MongoCRUDController.java

License:Open Source License

private void createUpdateEntityInfoIndexes(EntityInfo ei, Metadata md) {
    LOGGER.debug("createUpdateEntityInfoIndexes: begin");

    Indexes indexes = ei.getIndexes();//from  www .  j a v  a 2  s  .  c  o  m

    MongoDataStore ds = (MongoDataStore) ei.getDataStore();
    DB entityDB = dbResolver.get(ds);
    DBCollection entityCollection = entityDB.getCollection(ds.getCollectionName());
    Error.push("createUpdateIndex");
    try {
        List<DBObject> existingIndexes = entityCollection.getIndexInfo();
        LOGGER.debug("Existing indexes: {}", existingIndexes);

        // This is how index creation/modification works:
        //  - The _id index will remain untouched.
        //  - If there is an index with name X in metadata, find the same named index, and compare
        //    its fields/flags. If different, drop and recreate. Drop all indexes with the same field signature.
        //
        //  - If there is an index with null name in metadata, see if there is an index with same
        //    fields and flags. If so, no change. Otherwise, create index. Drop all indexes with the same field signature.
        List<Index> createIndexes = new ArrayList<>();
        List<DBObject> dropIndexes = new ArrayList<>();
        List<DBObject> foundIndexes = new ArrayList<>();
        for (Index index : indexes.getIndexes()) {
            if (!isIdIndex(index)) {
                if (index.getName() != null && index.getName().trim().length() > 0) {
                    LOGGER.debug("Processing index {}", index.getName());
                    DBObject found = null;
                    for (DBObject existingIndex : existingIndexes) {
                        if (index.getName().equals(existingIndex.get("name"))) {
                            found = existingIndex;
                            break;
                        }
                    }
                    if (found != null) {
                        foundIndexes.add(found);
                        // indexFieldsMatch will handle checking for hidden versions of the index
                        if (indexFieldsMatch(index, found) && indexOptionsMatch(index, found)) {
                            LOGGER.debug("{} already exists", index.getName());
                        } else {
                            LOGGER.debug("{} modified, dropping and recreating index", index.getName());
                            existingIndexes.remove(found);
                            dropIndexes.add(found);
                            createIndexes.add(index);
                        }
                    } else {
                        LOGGER.debug("{} not found, checking if there is an index with same field signature",
                                index.getName());
                        found = findIndexWithSignature(existingIndexes, index);
                        if (found == null) {
                            LOGGER.debug("{} not found, creating", index.getName());
                            createIndexes.add(index);
                        } else {
                            LOGGER.debug("There is an index with same field signature as {}, drop and recreate",
                                    index.getName());
                            foundIndexes.add(found);
                            dropIndexes.add(found);
                            createIndexes.add(index);
                        }
                    }
                } else {
                    LOGGER.debug("Processing index with fields {}", index.getFields());
                    DBObject found = findIndexWithSignature(existingIndexes, index);
                    if (found != null) {
                        foundIndexes.add(found);
                        LOGGER.debug("An index with same keys found: {}", found);
                        if (indexOptionsMatch(index, found)) {
                            LOGGER.debug("Same options as well, not changing");
                        } else {
                            LOGGER.debug("Index with different options, drop/recreate");
                            dropIndexes.add(found);
                            createIndexes.add(index);
                        }
                    } else {
                        LOGGER.debug("Creating index with fields {}", index.getFields());
                        createIndexes.add(index);
                    }
                }
            }
        }
        // Any index in existingIndexes but not in foundIndexes should be deleted as well
        for (DBObject index : existingIndexes) {
            boolean found = false;
            for (DBObject x : foundIndexes) {
                if (x == index) {
                    found = true;
                    break;
                }
            }
            if (!found) {
                for (DBObject x : dropIndexes) {
                    if (x == index) {
                        found = true;
                        break;
                    }
                }
                if (!found && !isIdIndex(index)) {
                    LOGGER.warn("Dropping index {}", index.get("name"));
                    entityCollection.dropIndex(index.get("name").toString());
                }
            }
        }
        for (DBObject index : dropIndexes) {
            LOGGER.warn("Dropping index {}", index.get("name"));
            entityCollection.dropIndex(index.get("name").toString());
        }
        // we want to run in the background if we're only creating indexes (no field generation)
        boolean hidden = false;
        // fieldMap is <canonicalPath, hiddenPath>
        List<Path> fields = new ArrayList<>();
        for (Index index : createIndexes) {
            DBObject newIndex = new BasicDBObject();
            for (IndexSortKey p : index.getFields()) {
                Path field = p.getField();
                if (p.isCaseInsensitive()) {
                    fields.add(p.getField());
                    field = DocTranslator.getHiddenForField(field);
                    // if we have a case insensitive index, we want the index creation operation to be blocking
                    hidden = true;
                }
                newIndex.put(ExpressionTranslator.translatePath(field), p.isDesc() ? -1 : 1);
            }
            BasicDBObject options = new BasicDBObject("unique", index.isUnique());
            // if index is unique and non-partial, also make it a sparse index, so we can have non-required unique fields
            options.append("sparse", index.isUnique()
                    && !index.getProperties().containsKey(PARTIAL_FILTER_EXPRESSION_OPTION_NAME));
            if (index.getName() != null && index.getName().trim().length() > 0) {
                options.append("name", index.getName().trim());
            }
            options.append("background", true);
            // partial index
            if (index.getProperties().containsKey(PARTIAL_FILTER_EXPRESSION_OPTION_NAME)) {
                try {
                    @SuppressWarnings("unchecked")
                    DBObject filter = new BasicDBObject((Map<String, Object>) index.getProperties()
                            .get(PARTIAL_FILTER_EXPRESSION_OPTION_NAME));
                    options.append(PARTIAL_FILTER_EXPRESSION_OPTION_NAME, filter);
                } catch (ClassCastException e) {
                    throw new RuntimeException("Index property " + PARTIAL_FILTER_EXPRESSION_OPTION_NAME
                            + " needs to be a mongo query in json format", e);
                }
            }
            LOGGER.debug("Creating index {} with options {}", newIndex, options);
            LOGGER.warn("Creating index {} with fields={}, options={}", index.getName(), index.getFields(),
                    options);
            entityCollection.createIndex(newIndex, options);
        }
        if (hidden) {
            LOGGER.info("Executing post-index creation updates...");
            // case insensitive indexes have been updated or created. recalculate all hidden fields
            Thread pop = new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        populateHiddenFields(ei, md, fields);
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                }
            });
            pop.start();

            // TODO: remove hidden fields on index deletions? Worth it?
        }
    } catch (MongoException me) {
        throw Error.get(MongoCrudConstants.ERR_ENTITY_INDEX_NOT_CREATED, me.getMessage());
    } catch (Exception e) {
        throw analyzeException(e, MetadataConstants.ERR_ILL_FORMED_METADATA);
    } finally {
        Error.pop();
    }
    LOGGER.debug("createUpdateEntityInfoIndexes: end");
}

From source file:com.redhat.lightblue.mongo.crud.MongoLocking.java

License:Open Source License

public void ping(String callerId, String resourceId) {
    Date now = new Date();
    BasicDBObject q = new BasicDBObject().append(CALLERID, callerId).append(RESOURCEID, resourceId)
            .append(EXPIRATION, new BasicDBObject("$gt", now)).append(COUNT, new BasicDBObject("$gt", 0));
    DBObject lock = coll.findOne(q, null, ReadPreference.primary());
    if (lock != null) {
        Date expiration = new Date(now.getTime() + ((Number) lock.get(TTL)).longValue());
        int ver = ((Number) lock.get(VERSION)).intValue();
        BasicDBObject update = new BasicDBObject()
                .append("$set", new BasicDBObject(TIMESTAMP, now).append(EXPIRATION, expiration))
                .append("$inc", new BasicDBObject(VERSION, 1));
        q = q.append(VERSION, ver);
        WriteResult wr = coll.update(q, update, false, false, WriteConcern.ACKNOWLEDGED);
        if (wr.getN() != 1) {
            throw new InvalidLockException(resourceId);
        }//  www . j  a  v  a  2s.  c  o  m
        LOGGER.debug("{}/{} pinged", callerId, resourceId);
    } else {
        throw new InvalidLockException(resourceId);
    }
}

From source file:com.redhat.lightblue.mongo.crud.MongoSafeUpdateProtocol.java

License:Open Source License

/**
 * Writes a replace query, which is://w w  w.ja v  a 2  s  .c o  m
 * <pre>
 *  {_id:<docId>, "@mongoHidden.docver.0":ObjectId(<originalDocver>)}
 * </pre>
 */
private DBObject writeReplaceQuery(DBObject doc) {
    DBObject hidden = DocVerUtil.getHidden(doc, false);
    ObjectId top = null;
    if (hidden != null) {
        List<ObjectId> list = (List<ObjectId>) hidden.get(DocVerUtil.DOCVER);
        if (list != null && !list.isEmpty())
            top = list.get(0);
    }
    BasicDBObject query = new BasicDBObject("_id", doc.get("_id"));
    if (cfg.isDetect())
        query.append(DOCVER_FLD0, top);
    return query;
}

From source file:com.redhat.thermostat.gateway.common.mongodb.filters.MongoSortFilters.java

License:Open Source License

public static Bson createSortObject(String sort) {
    BasicDBObject sortObject = new BasicDBObject();
    if (sort != null) {
        String[] items = sort.split(",");
        for (String item : items) {
            if (item.charAt(0) == '+') {
                sortObject.append(item.substring(1), 1);
            } else if (item.charAt(0) == '-') {
                sortObject.append(item.substring(1), -1);
            }/*from  w ww  .j  av a2 s. com*/
        }
    }
    return sortObject;
}

From source file:com.restfeel.controller.rest.EntityDataController.java

License:Apache License

@RequestMapping(value = "/api/{projectId}/entities/{name}/{id}", method = RequestMethod.GET, headers = "Accept=application/json")
public @ResponseBody String getEntityDataById(@PathVariable("projectId") String projectId,
        @PathVariable("name") String entityName, @PathVariable("id") String entityDataId,
        @RequestHeader(value = "authToken", required = false) String authToken) {

    JSONObject authRes = authService.authorize(projectId, authToken, "USER");
    if (!authRes.getBoolean(SUCCESS)) {
        return authRes.toString(4);
    }//  www  . j av a  2  s  .c  o  m

    DBCollection dbCollection = mongoTemplate.getCollection(projectId + "_" + entityName);

    BasicDBObject queryObject = new BasicDBObject();
    queryObject.append("_id", new ObjectId(entityDataId));

    DBObject resultObject = dbCollection.findOne(queryObject);

    if (resultObject == null) {
        return "Not Found";
    }

    if (entityName.equals("User")) {
        resultObject.removeField(PASSWORD);
    }

    dbRefToRelation(resultObject);
    String json = resultObject.toString();

    // Indentation
    JSONObject jsonObject = new JSONObject(json);
    return jsonObject.toString(4);
}