Example usage for com.mongodb BasicDBObject containsField

List of usage examples for com.mongodb BasicDBObject containsField

Introduction

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

Prototype

public boolean containsField(final String field) 

Source Link

Document

Checks if this object contains a given field

Usage

From source file:com.ebay.cloud.cms.dal.persistence.flatten.impl.root.RootFieldDeleteCommand.java

License:Apache License

private void buildFieldBody(BasicDBObject modifyBody) {
    MetaField field = getField();/*from  w w  w .ja  va2 s  .  co m*/
    BasicDBObject unsetBody = deleteFieldAndFieldProperty(field);
    modifyBody.put("$unset", unsetBody);

    // need to update the expression fields
    MetaClass meta = getEntity().getMetaClass();
    if (meta.hasExpressionFields()) {
        BasicDBObject setBody = null;
        // find the $set object
        if (!modifyBody.containsField("$set")) {
            setBody = new BasicDBObject();
            modifyBody.put("$set", setBody);
        } else {
            setBody = (BasicDBObject) modifyBody.get("$set");
        }

        List<MetaAttribute> expFields = meta.getExpressionFields();
        // update field value and properties accordingly
        for (MetaAttribute expField : expFields) {
            updateExpressFieldAndProperty(setBody, expField);
        }
    }
}

From source file:com.ebay.cloud.cms.dal.persistence.flatten.impl.root.RootFieldModifyCommand.java

License:Apache License

private void buildSetFieldBody(DBObject modifyBody) {
    MetaField field = getField();//from   w ww .j  av  a 2s. com
    BasicDBObject enityObject = (BasicDBObject) getEntity().getNode();
    Object fieldObject = enityObject.get(field.getFlattenValueDbName());

    if (fieldObject != null) {
        BasicDBObject set = (BasicDBObject) modifyBody.get("$set");
        set.put(field.getFlattenValueDbName(), fieldObject);
        // need update the field property
        for (FieldProperty fp : FieldProperty.values()) {
            String propertyValueDbName = field.getFlattenPropertyValueDbName(fp);
            if (enityObject.containsField(propertyValueDbName)) {
                set.put(propertyValueDbName, enityObject.get(propertyValueDbName));
            }
        }
    }
}

From source file:com.ebay.cloud.cms.dal.persistence.impl.root.RootFieldDeleteCommand.java

License:Apache License

private void buildFieldBody(BasicDBObject modifyBody) {
    MetaField field = getField();//from   w  w w  .  j  a v  a 2 s .  c  om
    BasicDBObject unsetBody = new BasicDBObject();
    unsetBody.put(field.getDbName(), "");
    modifyBody.put("$unset", unsetBody);

    MetaClass meta = getEntity().getMetaClass();
    if (meta.hasExpressionFields()) {
        BasicDBObject setBody = null;
        if (!modifyBody.containsField("$set")) {
            setBody = new BasicDBObject();
            modifyBody.put("$set", setBody);
        } else {
            setBody = (BasicDBObject) modifyBody.get("$set");
        }

        List<MetaAttribute> expFields = meta.getExpressionFields();
        for (MetaAttribute expField : expFields) {
            String fieldDbName = expField.getDbName();
            setBody.put(fieldDbName, getEntity().getNode().get(fieldDbName));
        }
    }
}

From source file:com.ebay.cloud.cms.dalapi.entity.impl.BsonEntity.java

License:Apache License

@Override
@SuppressWarnings("unchecked")
public List<?> getFieldValues(String fieldName) {
    // validate the field name
    MetaField metaField = getMetaClass().getFieldByName(fieldName);
    CheckConditions.checkArgument(metaField != null, "Can't find meta field %s", fieldName);
    CheckConditions.checkNotNull(metaField.getDbName(), "Meta field doesn't have db name set!");
    // get parent bson & db name
    BasicDBObject fieldBsonObject = null;
    String dbValName = null;/* w  w w.j av  a 2s.  co m*/
    if (metaField.isInternal()) {
        dbValName = metaField.getDbName();
        fieldBsonObject = bsonObject;
    } else {
        dbValName = MetaField.VALUE_KEY;
        fieldBsonObject = getBsonField(metaField.getDbName());
    }
    if (fieldBsonObject == null) {
        return Collections.EMPTY_LIST;
    }
    // get value from parent field
    CardinalityEnum cardinality = metaField.getCardinality();
    DataTypeEnum dataType = metaField.getDataType();
    IDataTypeHandler handler = BsonDataTypeHandlerFactory.getHandler(dataType);
    List<Object> result = Collections.EMPTY_LIST;
    if (cardinality == CardinalityEnum.One) {
        if (fieldBsonObject.containsField(dbValName)) {
            Object bsonValue = fieldBsonObject.get(dbValName);
            // for json type field, if data is Many while metatype changed to One, 
            // it still can return not null bsonValue, but should ignore it
            if (!(bsonValue instanceof BasicDBList)) {
                result = new ArrayList<Object>(1);
                Object value = handler.read(this, bsonValue, metaField);
                addReadValue(dataType, result, value);
            }
        }
    } else if (fieldBsonObject.get(dbValName) instanceof List) {
        Object blist = fieldBsonObject.get(dbValName);
        List<Object> bsonList = (List<Object>) blist;
        if (bsonList != null) {
            result = new ArrayList<Object>();
            for (Object bsonValue : bsonList) {
                Object value = handler.read(this, bsonValue, metaField);
                addReadValue(dataType, result, value);
            }
        }
    }
    return result;
}

From source file:com.ebay.cloud.cms.metadata.mongo.MongoMetadataServiceImpl.java

License:Apache License

private MetaClass innerUpdateMetaClass(MetaClass metaClass, boolean updateGraph, boolean updateExistingField) {

    populateDbName(metaClass);//w w  w  . j  av  a  2s .  c o  m
    metaClass.setLastModified(new Date());

    BasicDBObject object = (BasicDBObject) converter.toBson(metaClass);

    BasicDBObject query = new BasicDBObject();
    query.append(MetaClass.NAME, metaClass.getName());
    BasicDBObject update = new BasicDBObject();
    BasicDBObject ups = new BasicDBObject();

    Collection<MetaField> updateFields = metaClass.getClassFields();
    //update fields
    BasicDBObject objectFields = (BasicDBObject) object.get("fields");
    for (MetaField f : updateFields) {
        if (!f.isInternal()) {
            String fieldKey = "fields." + f.getName();
            if (!updateExistingField) {
                query.append(fieldKey, new BasicDBObject(MongoOperand.exists, false));
            }
            ups.append(fieldKey, objectFields.get(f.getName()));
        }
    }
    // update options
    BasicDBObject objectIndexes = (BasicDBObject) object.get("options");
    Collection<IndexInfo> updateIndex = metaClass.getClassIndexes();
    if (!updateIndex.isEmpty()) {
        BasicDBObject indexOptions = (BasicDBObject) objectIndexes.get("indexes");
        for (IndexInfo index : updateIndex) {
            if (index.isInternal()) {
                continue;
            }
            String fieldKey = "options.indexes." + index.getIndexName();
            query.append(fieldKey, new BasicDBObject(MongoOperand.exists, false));
            ups.append(fieldKey, indexOptions.get(index.getIndexName()));
        }
    }
    // add optional fields if given
    addIfGiven(object, ups, "description");
    if (object.containsField("parent")) {
        addIfGiven(object, ups, "parent");
        addIfGiven(object, ups, "ancestors");
        addIfGiven(object, ups, "parentVersion");
    }
    addIfGiven(object, ups, "allowFullTableScan");
    addIfGiven(object, ups, "embed");
    addIfGiven(object, ups, "lastModified");
    addIfGiven(object, ups, "inner");

    update.append(MongoOperand.set, ups);
    BasicDBObject versionObject = new BasicDBObject();
    versionObject.put("version", 1);
    update.put(MongoOperand.inc, versionObject);

    try {
        boolean updated = MongoUtils.wrapperUpdate(collection, query, update);
        if (!updated) {
            StringBuilder sb = new StringBuilder();
            for (MetaField f : updateFields) {
                sb.append(f.getName()).append(",");
            }
            throw new MetaFieldExistsException(sb.toString());
        }
    } catch (MongoException e) {
        throw new MongoOperationException(e);
    }

    cacheManager.deleteMetaClassFromCache(metaClass);
    MetaClass result = getMetaClass(metaClass.getName());

    if (updateGraph) {
        getMetaClasses(new MetadataContext(true, true));
    }
    return result;
}

From source file:com.ebay.cloud.cms.metadata.mongo.MongoMetadataServiceImpl.java

License:Apache License

void addIfGiven(BasicDBObject object, BasicDBObject ups, String name) {
    if (object.containsField(name)) {
        ups.append(name, object.get(name));
    }
}

From source file:com.ebay.cloud.cms.metadata.mongo.MongoMetadataServiceImpl.java

License:Apache License

private void addMetaHistory(MetaClass meta, String operType, MetadataContext context) {
    saveMetaHistory(meta, operType, context);

    if (operType.equals("deleteMetaClass")) {
        return;//from w ww .ja v a 2s  .  c o  m
    }

    // update the parent version in all children meta
    List<MetaClass> descendants = graph.getDescendants(meta);

    if (descendants.size() > 0) {
        Map<String, Integer> metaVersionMap = new HashMap<String, Integer>();
        metaVersionMap.put(meta.getName(), Integer.valueOf(meta.getVersion() + 1));

        String oldParent = null;
        String newParent = null;
        MetaClass newMeta = getMetaClass(meta.getName());
        if (newMeta != null) {
            BasicDBObject newObject = (BasicDBObject) converter.toBson(newMeta);
            BasicDBObject oldObject = (BasicDBObject) converter.toBson(meta);
            if (!oldObject.containsField("parent") && newObject.containsField("parent")) {
                oldParent = null;
                newParent = (String) newObject.get("parent");
            } else if (oldObject.containsField("parent") && !newObject.containsField("parent")) {
                oldParent = (String) oldObject.get("parent");
                newParent = null;
            } else if (oldObject.containsField("parent") && newObject.containsField("parent")
                    && !oldObject.get("parent").equals(newObject.get("parent"))) {
                oldParent = (String) oldObject.get("parent");
                newParent = (String) newObject.get("parent");
            }
        }

        // avoid endless loop by wrong descendants value
        boolean shrinking = true;
        while (descendants.size() > 0 && shrinking) {
            shrinking = false;
            for (int i = 0; i < descendants.size(); i++) {
                MetaClass desc = descendants.get(i);
                String name = desc.getParent();
                Integer newVersion = metaVersionMap.get(name);
                if (newVersion != null) {
                    // update descendant parentVersion
                    MetaClass newDesc = new MetaClass();
                    newDesc.setName(desc.getName());
                    newDesc.setParent(name);
                    newDesc.setParentVersion(newVersion.intValue());

                    List<String> ancestors = desc.getAncestors();
                    if (!org.apache.commons.lang.StringUtils.isEmpty(oldParent)) {
                        ancestors.remove(oldParent);
                    }
                    if (!org.apache.commons.lang.StringUtils.isEmpty(newParent)) {
                        ancestors.add(newParent);
                    }
                    newDesc.setAncestors(ancestors);

                    innerUpdateMetaClass(newDesc, true, false);

                    // save the descendant history
                    saveMetaHistory(desc, "updateMetaClassByParentVersion", context);

                    metaVersionMap.put(desc.getName(), Integer.valueOf(desc.getVersion() + 1));
                    descendants.remove(i);
                    shrinking = true;
                }
            }
        }
    }
}

From source file:com.ebay.cloud.cms.query.metadata.AggregateMetaAttribute.java

License:Apache License

@JsonIgnore
private boolean hasFieldValue(IEntity currentEntity) {
    BasicDBObject dbo = (BasicDBObject) currentEntity.getNode();
    if (groupField != null) {
        return ((DBObject) dbo.get("_id")).containsField(groupField.getFieldName());
    } else {// w ww.j  a  v a 2  s .  com
        return dbo.containsField(aggregationField.getFieldName());
    }
}

From source file:com.edgytech.umongo.AggregateDialog.java

License:Apache License

@Override
protected void updateComponentCustom(JDialog old) {
    BasicDBObject cmd = (BasicDBObject) JSON.parse(pipeline);
    if (cmd != null && cmd.containsField("pipeline")) {
        BasicDBList list = (BasicDBList) cmd.get("pipeline");
        operationList.clear();//from   w  ww  . j  a v a  2  s. co  m
        for (Object op : list) {
            operationList.add((BasicDBObject) op);
        }
        refreshAggList();
    }
}

From source file:com.edgytech.umongo.CollectionPanel.java

License:Apache License

public void shardingDistribution(ButtonBase button) {
    final DB config = getCollectionNode().getCollection().getDB().getSisterDB("config");

    new DbJob() {
        @Override/*  w  w w.ja v a2s  .co  m*/
        public Object doRun() throws Exception {
            BasicDBObject result = new BasicDBObject();
            BasicDBList shardList = new BasicDBList();
            BasicDBObject stats = getStats();
            BasicDBObject shards = (BasicDBObject) stats.get("shards");
            if (shards == null || shards.isEmpty())
                return null;

            long totalChunks = 0;
            long totalSize = stats.getLong("size");
            long totalCount = stats.getLong("count");

            for (Entry shard : shards.entrySet()) {
                String shardName = (String) shard.getKey();
                BasicDBObject shardStats = (BasicDBObject) shard.getValue();

                BasicDBObject query = new BasicDBObject("ns",
                        getCollectionNode().getCollection().getFullName());
                query.put("shard", shardName);
                long numChunks = config.getCollection("chunks").count(query);
                totalChunks += numChunks;

                double estChunkData = numChunks <= 0 ? 0 : shardStats.getLong("size") / numChunks;
                long estChunkCount = numChunks <= 0 ? 0
                        : (long) Math.floor(shardStats.getLong("count") / numChunks);

                BasicDBObject shardDetails = new BasicDBObject("shard", shardName);
                shardDetails.put("data", shardStats.getLong("size"));
                shardDetails.put("pctData",
                        totalSize <= 0 ? 0 : (shardStats.getLong("size") * 100.0) / totalSize);
                shardDetails.put("docs", shardStats.getLong("count"));
                shardDetails.put("pctDocs",
                        totalCount <= 0 ? 0 : (shardStats.getLong("count") * 100.0) / totalCount);
                shardDetails.put("chunks", numChunks);
                if (shardStats.containsField("avgObjSize"))
                    shardDetails.put("avgDocSize", shardStats.getDouble("avgObjSize"));
                shardDetails.put("estimatedDataPerChunk", estChunkData);
                shardDetails.put("estimatedDocsPerChunk", estChunkCount);
                shardList.add(shardDetails);
            }
            result.put("shards", shardList);

            BasicDBObject total = new BasicDBObject();
            total.put("data", totalSize);
            total.put("docs", totalCount);
            total.put("chunks", totalChunks);
            total.put("avgDocSize", stats.getDouble("avgObjSize"));
            result.put("total", total);
            return result;
        }

        @Override
        public String getNS() {
            return getCollectionNode().getCollection().getFullName();
        }

        @Override
        public String getShortName() {
            return "Sharding Distribution";
        }
    }.addJob();
}