Example usage for com.mongodb BasicDBList BasicDBList

List of usage examples for com.mongodb BasicDBList BasicDBList

Introduction

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

Prototype

BasicDBList

Source Link

Usage

From source file:com.ebay.cloud.cms.dal.persistence.flatten.impl.embed.EmbedFieldModifyCommand.java

License:Apache License

@SuppressWarnings({ "rawtypes", "unchecked" })
void buildArrayBody(BasicDBObject embedObject, MetaField field) {
    BasicDBObject enityObject = (BasicDBObject) getEntity().getNode();
    List<?> fieldObject = (List<?>) enityObject.get(field.getFlattenValueDbName());

    if (fieldObject != null) {
        List givenValue = fieldObject;
        if (givenValue != null) {
            List targetFieldList = new ArrayList();
            BasicDBList list = (BasicDBList) embedObject.get(field.getFlattenValueDbName());
            if (list != null) {
                targetFieldList.addAll(list);
            }//w ww  . j ava2  s  .com
            targetFieldList.addAll(givenValue);

            BasicDBList valueList = new BasicDBList();
            valueList.addAll(targetFieldList);
            // field value
            embedObject.put(field.getFlattenValueDbName(), valueList);
            // field property
            embedObject.put(field.getFlattenPropertyValueDbName(FieldProperty.LENGTH), targetFieldList.size());
            embedObject.put(field.getFlattenPropertyValueDbName(FieldProperty.TIMESTAMP), new Date());
        }
    }
}

From source file:com.ebay.cloud.cms.dal.persistence.impl.embed.EmbedCreateCommand.java

License:Apache License

public DBObject buildCreateBody(MetaRelationship lastField, String parentPath, BsonEntity entity,
        int newVersion, MetaClass rootMetaClass, DBObject rootObject, String parentId) {
    BasicDBObject embedParentObject = (BasicDBObject) EmbedDBObjectFilter.filter(parentId, rootObject,
            rootMetaClass, null, helper);
    if (embedParentObject == null) {
        throw new CmsDalException(DalErrCodeEnum.ENTITY_NOT_FOUND,
                "Create, can not find embed field with Id: " + parentId);
    }/*  ww  w .  j  a v a  2  s.  c  om*/

    embedParentObject.remove("_id");

    if (lastField.getCardinality() == CardinalityEnum.Many) {
        BasicDBObject obj = (BasicDBObject) embedParentObject.get(lastField.getDbName());
        BasicDBList valueList = null;
        if (obj != null) {
            valueList = (BasicDBList) obj.get(MetaField.VALUE_KEY);
        }

        if (valueList == null) {
            if (obj == null) {
                obj = new BasicDBObject();
                embedParentObject.put(lastField.getDbName(), obj);
            }
            valueList = new BasicDBList();
            valueList.add(entity.getNode());
            obj.put(FieldProperty.LENGTH.getDbName(), 1);
            obj.put(FieldProperty.TIMESTAMP.getDbName(), new Date());
            obj.put(MetaField.VALUE_KEY, valueList);
        } else {
            int size = valueList.size();
            valueList.add(entity.getNode());
            obj.put(FieldProperty.LENGTH.getDbName(), size + 1);
            obj.put(FieldProperty.TIMESTAMP.getDbName(), new Date());
            obj.put(MetaField.VALUE_KEY, valueList);
        }
    } else {
        DBObject vObj = new BasicDBObject();
        vObj.put(MetaField.VALUE_KEY, entity.getNode());
        embedParentObject.put(lastField.getDbName(), vObj);
    }

    BasicDBObject setModifyObject = new BasicDBObject();
    BasicDBObject obj = (BasicDBObject) rootObject.get(embedFieldName);
    if (obj == null) {
        throw new CmsDalException(DalErrCodeEnum.ENTITY_NOT_FOUND,
                "Create, can not find embed field with Id: " + this.entity.getId());
    }

    setModifyObject.put(embedFieldName, obj);
    BasicDBObject modifyBody = new BasicDBObject();
    modifyBody.put("$set", setModifyObject);

    // increase version on root document
    BasicDBObject versionObject = new BasicDBObject();
    versionObject.put(InternalFieldEnum.VERSION.getDbName(), 1);
    modifyBody.put("$inc", versionObject);

    buildRootUpdateObject(entity, null, modifyBody, rootMetaClass);

    return modifyBody;
}

From source file:com.ebay.cloud.cms.dal.persistence.impl.embed.EmbedFieldModifyCommand.java

License:Apache License

@Override
@SuppressWarnings({ "rawtypes", "unchecked" })
protected DBObject buildModifyBody(BitSet arrayBits, DBObject rootObject, MetaClass rootMetaClass) {
    BasicDBObject embedObject = (BasicDBObject) EmbedDBObjectFilter.filter(entity.getId(), rootObject,
            rootMetaClass, null, helper);

    MetaField field = getField();//  w  ww  .j a  v a  2  s  . c o m
    if (field.getCardinality() == CardinalityEnum.Many) {
        BasicDBObject enityObject = (BasicDBObject) getEntity().getNode();
        BasicDBObject fieldObject = (BasicDBObject) enityObject.get(field.getDbName());

        if (fieldObject != null) {
            List givenValue = (List) fieldObject.get(V);
            if (givenValue != null) {
                // merge with exsiting fields FIXME:: keep the same with RootFieldModifyCommand of using delta
                List targetFilterList = new ArrayList();
                BasicDBObject existingFieldObject = (BasicDBObject) embedObject.get(field.getDbName());
                if (existingFieldObject != null) {
                    BasicDBList list = (BasicDBList) existingFieldObject.get(V);
                    if (list != null) {
                        targetFilterList.addAll(list);
                    }
                }
                targetFilterList.addAll(givenValue);

                BasicDBList valueList = new BasicDBList();
                valueList.addAll(targetFilterList);

                DBObject obj = (DBObject) embedObject.get(field.getDbName());
                if (obj == null) {
                    obj = new BasicDBObject();
                    embedObject.put(field.getDbName(), obj);
                }

                obj.put(V, valueList);
                obj.put(FieldProperty.LENGTH.getDbName(), targetFilterList.size());
                obj.put(FieldProperty.TIMESTAMP.getDbName(), new Date());
            }
        }
    } else if (field.getDataType().equals(DataTypeEnum.JSON)) {
        // incremental $set
        // buildJsonBody(parentPath, modifyBody);
        BasicDBObject enityObject = (BasicDBObject) getEntity().getNode();
        BasicDBObject fieldObject = (BasicDBObject) enityObject.get(field.getDbName());
        if (fieldObject != null) {
            DBObject obj = (DBObject) embedObject.get(field.getDbName());
            if (obj == null) {
                obj = new BasicDBObject();
                embedObject.put(field.getDbName(), obj);
            }
            DBObject valueObj = (DBObject) obj.get(V);
            if (valueObj == null) {
                valueObj = new BasicDBObject();
                obj.put(V, valueObj);
            }

            BasicDBObject givenValue = (BasicDBObject) (fieldObject).get(V);
            if (givenValue != null) {
                for (String key : givenValue.keySet()) {
                    valueObj.put(key, givenValue.get(key));
                }
                valueObj.put(FieldProperty.TIMESTAMP.getDbName(),
                        getEntity().getFieldTimestamp(field.getName()));
            }
        }

    } else {
        // non-array: replace the whole field
        BasicDBObject enityObject = (BasicDBObject) getEntity().getNode();
        BasicDBObject fieldObject = (BasicDBObject) enityObject.get(field.getDbName());
        embedObject.put(field.getDbName(), fieldObject);
        // buildSetFieldBody(parentPath, modifyBody);
    }

    embedObject.put(InternalFieldEnum.MODIFIER.getDbName(), entity.getModifier());
    embedObject.put(InternalFieldEnum.LASTMODIFIED.getDbName(), entity.getLastModified());

    return buildSetBody(rootObject);
}

From source file:com.ebay.cloud.cms.lock.mongo.MongoMutex.java

License:Apache License

public synchronized boolean tryAcquire() {
    if (ownerThread == null) {
        BasicDBObject query = new BasicDBObject();
        query.put(LOCK_NAME, lockName);/*from  ww w  . j a v  a2s. c o  m*/

        //owner == null || owner == self || (now - updateTime) > expireTime
        //owner logs the clientName who already acquired this lock
        BasicDBObject q1 = new BasicDBObject();
        q1.put(OWNER, null);
        BasicDBObject q2 = new BasicDBObject();
        q2.put(OWNER, clientName);
        BasicDBObject q3 = new BasicDBObject();
        BasicDBObject qq = new BasicDBObject();
        qq.put(MongoOperand.lt, new Date((new Date().getTime() - expireTime)));
        q3.put(UPDATE_TIME, qq);

        BasicDBList or = new BasicDBList();
        or.add(q1);
        or.add(q2);
        or.add(q3);

        query.put(MongoOperand.or, or);

        BasicDBObject update = new BasicDBObject();
        update.put(OWNER, clientName);
        update.put(UPDATE_TIME, new Date());
        BasicDBObject u = new BasicDBObject();
        u.put(MongoOperand.set, update);

        try {
            boolean success = MongoUtils.wrapperUpdate(coll, query, u);
            if (success) {
                ownerThread = Thread.currentThread();
                lockCount++;
                setLockState(State.LOCKED);
                renewThread = new RenewThread(this);
                renewThread.start();
                logger.debug("{} acquired by {}, thread is {}",
                        new Object[] { lockName, clientName, Thread.currentThread().getName() });
            } else {
                logger.debug("tryacquir failed, {}, {}", query, u);
            }
            return success;
        } catch (MongoException e) {
            logger.error("mongo exception while trying acquire mongo lock: " + lockName + ", " + clientName, e);
            throw e;
        }
    } else if (ownerThread == Thread.currentThread()) {
        if (lockCount <= 0) {
            logger.error("Current thread own this lock but the lockCount <= 0");
            throw new RuntimeException("Current thread own this lock but the lockCount <= 0");
        }
        if (getLockState().equals(State.LOCKED)) {
            lockCount++;
            return true;
        } else {
            return false;
        }
    } else {
        logger.error("lock already acquired by thread: " + Thread.currentThread().getName());
        throw new RuntimeException("lock already acquired by thread: " + Thread.currentThread().getName());
    }
}

From source file:com.ebay.cloud.cms.metadata.dataloader.MetadataDataLoader.java

License:Apache License

private void loadMetaClassesFromPath(String pathName) {
    try {/*  w  w w  .  j av a 2  s.  c o m*/

        URL url = MetadataDataLoader.class.getResource(pathName);
        URI uri = url.toURI();
        BasicDBList metas = new BasicDBList();

        if (uri.isOpaque()) {
            JarURLConnection connection = (JarURLConnection) url.openConnection();
            JarFile jar = connection.getJarFile();
            Enumeration<JarEntry> entries = jar.entries();

            while (entries.hasMoreElements()) {
                JarEntry entry = entries.nextElement();
                if (entry.getName().startsWith(pathName.substring(1)) && entry.getName().endsWith(".json")) {
                    InputStream is = jar.getInputStream(entry);
                    readMetaClass(is, metas);
                }
            }

        } else {
            File dir = new File(url.toURI());
            Collection<File> files = FileUtils.listFiles(dir, new String[] { "json" }, true);
            for (File f : files) {
                InputStream is = new FileInputStream(f);
                readMetaClass(is, metas);
            }
        }

        loadMetaClasses(metas);

    } catch (Exception e) {
        logger.error("error in loading metadata: ", e);
    }
}

From source file:com.ebay.cloud.cms.metadata.dataloader.MetadataDataLoader.java

License:Apache License

public void loadMetaClassesFromResource(String fileName) {
    InputStream is = null;/*from  w w w.  j  a  v a  2  s.c  o  m*/
    try {
        is = MetadataDataLoader.class.getResourceAsStream(fileName);
        BasicDBList metas = new BasicDBList();
        readMetaClasses(is, metas);
        loadMetaClasses(metas);
    } finally {
        try {
            is.close();
        } catch (IOException e) {
            logger.error("error in closing stream: ", e);
        }
    }
}

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

License:Apache License

BasicDBObject getAggregateCommand(String collection) {
    BasicDBObject cmd = new BasicDBObject("aggregate", collection);
    BasicDBList list = new BasicDBList();
    cmd.put("pipeline", list);
    for (BasicDBObject op : operationList) {
        list.add(op);/*from ww w.  ja  v  a  2 s  .com*/
    }
    return cmd;
}

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/*from w  w w .jav a  2s  .  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();
}

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

License:Apache License

@Override
protected DBObject createDBObject() {
    return new BasicDBList();
}

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

License:Apache License

public void addNewField(String key, String type) {
    Object val = "";
    if (type.equals("Integer")) {
        val = new Integer(0);
    } else if (type.startsWith("Long")) {
        val = new Long(0);
    } else if (type.equals("Binary")) {
        val = new Binary((byte) 0, new byte[1]);
    } else if (type.startsWith("ObjectId")) {
        val = new ObjectId();
    } else if (type.equals("Boolean")) {
        val = new Boolean(true);
    } else if (type.equals("Code")) {
        val = new Code("");
    } else if (type.equals("Date")) {
        val = new Date();
    } else if (type.startsWith("Double")) {
        val = new Double(0.0);
    } else if (type.equals("Pattern")) {
        val = Pattern.compile("");
    } else if (type.equals("Timestamp")) {
        val = new BSONTimestamp((int) (System.currentTimeMillis() / 1000), 0);
    } else if (type.equals("Document")) {
        val = new BasicDBObject();
    } else if (type.equals("List")) {
        val = new BasicDBList();
    } else if (type.equals("Null")) {
        val = null;
    } else if (type.equals("UUID")) {
        val = UUID.randomUUID();
    } else if (type.equals("MinKey")) {
        val = new MinKey();
    } else if (type.equals("MaxKey")) {
        val = new MaxKey();
    }/*from   www .  j  ava2s  .  c om*/

    if (value == null) {
        value = createDBObject();
    }
    addField(key, val);
    structureComponent();
}