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:org.codinjutsu.tools.nosql.mongo.view.model.JsonTreeModel.java

License:Apache License

private static DBObject buildDBList(NoSqlTreeNode parentNode) {
    BasicDBList basicDBList = new BasicDBList();
    Enumeration children = parentNode.children();
    while (children.hasMoreElements()) {
        NoSqlTreeNode node = (NoSqlTreeNode) children.nextElement();
        MongoValueDescriptor descriptor = (MongoValueDescriptor) node.getDescriptor();
        Object value = descriptor.getValue();
        if (value instanceof DBObject) {
            if (value instanceof BasicDBList) {
                basicDBList.add(buildDBList(node));
            } else {
                basicDBList.add(buildDBObject(node));
            }/*from w w w  .  j  a v  a 2  s. c o  m*/
        } else {
            basicDBList.add(value);
        }
    }
    return basicDBList;
}

From source file:org.eclipse.birt.data.oda.mongodb.impl.MDbResultSet.java

License:Open Source License

public String getString(String columnName) throws OdaException {
    Object columnValue = getFieldValue(columnName);
    if (columnValue instanceof String)
        return (String) columnValue;

    if (columnValue instanceof List && !(columnValue instanceof BasicDBList)) {
        // convert generic List to JSON-formattable list
        List<?> fromList = (List<?>) columnValue;
        if (!fromList.isEmpty()) {
            BasicDBList fieldValuesList = new BasicDBList();
            for (int index = 0; index < fromList.size(); index++) {
                fieldValuesList.put(index, fromList.get(index));
            }/*from   w  w  w.j av  a2  s . c  om*/
            fieldValuesList.markAsPartialObject();
            return fieldValuesList.toString(); // return JSON expr format
        }
    }

    if (columnValue instanceof byte[])
        return convertToString((byte[]) columnValue);

    return columnValue != null ? columnValue.toString() : null;
}

From source file:org.eclipse.birt.data.oda.mongodb.internal.impl.MDbOperation.java

License:Open Source License

@SuppressWarnings("unchecked")
static Iterable<DBObject> callDBCommand(DB connectedDB, QueryProperties queryProps) throws OdaException {
    if (!queryProps.hasRunCommand())
        return null;
    DBObject command = queryProps.getOperationExprAsParsedObject(false);
    if (command == null)
        return null;

    try {/*  w w w  .  j  av a 2s . c om*/
        CommandResult cmdResult = connectedDB.command(command);
        cmdResult.throwOnError();

        // wrap the commandResult DBObject in an Iterable
        BasicDBList resultList = new BasicDBList();
        resultList.add(cmdResult);
        Object resultObject = resultList;
        return (Iterable<DBObject>) resultObject;
    } catch (RuntimeException ex) {
        OdaException odaEx = new OdaException(
                Messages.bind(Messages.mDbOp_dbCmdFailed, queryProps.getOperationExpression()));
        odaEx.initCause(ex);
        throw odaEx;
    }
}

From source file:org.eclipse.birt.data.oda.mongodb.internal.impl.ResultDataHandler.java

License:Open Source License

static DBObject fetchFieldDocument(Object fieldValue, byte fieldNativeDataType) {
    if (fieldNativeDataType == BSON.UNDEFINED)
        fieldNativeDataType = Bytes.getType(fieldValue);

    if (fieldNativeDataType == BSON.ARRAY) {
        if (!(fieldValue instanceof List))
            return null;

        // fetch nested document, if exists, for each element in array
        BasicDBList dbObjsList = new BasicDBList();
        for (Object valueInList : (List<?>) fieldValue) {
            DBObject listElementObj = fetchFieldDocument(valueInList);
            if (listElementObj == null) // at least one element in array is not a nested doc
                return null;
            if (listElementObj instanceof List)
                dbObjsList.addAll((List<?>) listElementObj); // collapse into the same list
            else/*  w  w  w. ja  v a2s  .c  o m*/
                dbObjsList.add(listElementObj);
        }
        return dbObjsList; // return nested documents in an array
    }

    DBObject fieldObjValue = null;
    if (fieldNativeDataType == BSON.OBJECT) {
        if (fieldValue instanceof DBObject)
            fieldObjValue = (DBObject) fieldValue;
        else if (fieldValue instanceof DBRefBase) {
            try {
                fieldObjValue = ((DBRefBase) fieldValue).fetch();
            } catch (Exception ex) {
                // log and ignore
                getLogger().log(Level.INFO, "Ignoring error in fetching a DBRefBase object."); //$NON-NLS-1$
            }
        }
    }
    return fieldObjValue;
}

From source file:org.eclipse.birt.data.oda.mongodb.internal.impl.ResultDataHandler.java

License:Open Source License

private static BasicDBList fetchFieldValuesFromList(String fieldFullName, BasicDBList fromDBList) {
    if (fromDBList == null || fromDBList.size() == 0)
        return null;

    // get the named field value from each element in given array list
    BasicDBList fieldValuesList = new BasicDBList();
    if (fromDBList.isPartialObject())
        fieldValuesList.markAsPartialObject();

    for (int index = 0; index < fromDBList.size(); index++) {
        Object listElementObj = fromDBList.get(String.valueOf(index));
        if (listElementObj instanceof DBObject) // nested complex object, e.g. document
            listElementObj = fetchFieldValues(fieldFullName, (DBObject) listElementObj);
        fieldValuesList.put(index, listElementObj);
    }// w ww. j av  a  2  s.co  m

    // check if at least one field value in list is not null, return the list
    for (Object elementValue : fieldValuesList.toMap().values()) {
        if (elementValue != null)
            return fieldValuesList;
    }

    return null; // all values in list is null
}

From source file:org.eclipse.birt.report.engine.emitter.mongodb.MongoDbEmitter.java

License:Open Source License

@Override
public void startTableGroup(ITableGroupContent tableGroup) throws BirtException {
    BasicDBList dbArray = new BasicDBList();
    DBObject groupObj = new BasicDBObject();
    groupObj.put(tableGroup.getName(), dbArray);
    groupObjStack.push(groupObj);//w w w.j  av a 2s .  c  om
}

From source file:org.eclipse.emf.cdo.server.internal.mongodb.Commits.java

License:Open Source License

private DBObject marshallRevision(InternalCommitContext context, InternalCDORevision revision,
        CDOChangeKind changeKind) {/* ww  w . j  av  a  2  s. c om*/
    boolean resource = !(revision instanceof SyntheticCDORevision) && revision.isResource();
    if (resource && resourceNameFeature == null) {
        resourceNameFeature = revision.getEClass()
                .getEStructuralFeature(CDOModelConstants.RESOURCE_NODE_NAME_ATTRIBUTE);
    }

    DBObject doc = new BasicDBObject();
    idHandler.write(doc, REVISIONS_ID, revision.getID());

    EClass eClass = revision.getEClass();
    doc.put(REVISIONS_CLASS, store.getClasses().getClassifierID(eClass));

    if (changeKind == CDOChangeKind.DETACHED) {
        doc.put(REVISIONS_VERSION, -revision.getVersion() - 1);
        return doc;
    }

    doc.put(REVISIONS_VERSION, revision.getVersion());

    CDOID resourceID = revision.getResourceID();
    idHandler.write(doc, REVISIONS_RESOURCE, resourceID);

    CDOID containerID = (CDOID) revision.getContainerID();
    idHandler.write(doc, REVISIONS_CONTAINER, containerID);

    int featureID = revision.getContainingFeatureID();
    doc.put(REVISIONS_FEATURE, featureID);

    if (resource && changeKind != CDOChangeKind.DETACHED) {
        String name = (String) revision.data().get(resourceNameFeature, 0);
        IStoreAccessor accessor = StoreThreadLocal.getAccessor();

        CDOID existingID = accessor.readResourceID(containerID, name, revision);
        if (existingID != null && !existingID.equals(revision.getID())
                && !isBeingDetached(context, existingID)) {
            throw new IllegalStateException("Duplicate resource: name=" + name + ", folderID=" + containerID); //$NON-NLS-1$ //$NON-NLS-2$
        }
    }

    CDOClassInfo classInfo = revision.getClassInfo();
    for (EStructuralFeature feature : classInfo.getAllPersistentFeatures()) {
        Object value = revision.getValue(feature);

        CDOType type = CDOModelUtil.getType(feature);
        ValueHandler valueHandler = store.getValueHandler(type);

        if (feature.isUnsettable()) {
            if (value == null) {
                doc.put(feature.getName() + SET_SUFFIX, false);
                doc.put(feature.getName(), valueHandler.getMongoDefaultValue(feature));
                continue;
            }

            doc.put(feature.getName() + SET_SUFFIX, true);
        }

        if (value == CDORevisionData.NIL) {
            doc.put(feature.getName(), null);
        } else if (value == null) {
            if (feature.isMany() || feature.getDefaultValue() == null) {
                doc.put(feature.getName(), null);
            } else {
                doc.put(feature.getName(), valueHandler.getMongoDefaultValue(feature));
            }
        } else {
            if (feature.isMany()) {
                List<?> cdoList = (List<?>) value;
                BasicDBList mongoList = new BasicDBList();
                for (Object element : cdoList) {
                    element = valueHandler.toMongo(element);
                    mongoList.add(element);
                }

                value = mongoList;
            } else {
                value = valueHandler.toMongo(value);
            }

            doc.put(feature.getName(), value);
        }
    }

    return doc;
}

From source file:org.eclipse.emf.cdo.server.internal.mongodb.Commits.java

License:Open Source License

public void loadCommitInfos(CDOBranch branch, long startTime, long endTime,
        final CDOCommitInfoHandler handler) {
    if (endTime < CDOBranchPoint.UNSPECIFIED_DATE) {
        throw new IllegalArgumentException("Counting not supported");
    }/*ww  w .  j av a 2s  .  c  o m*/

    DBObject query = new BasicDBObject();

    if (branch != null && store.isBranching()) {
        query.put(COMMITS_BRANCH, branch.getID());
    }

    BasicDBList list = new BasicDBList();
    if (startTime != CDOBranchPoint.UNSPECIFIED_DATE) {
        list.add(new BasicDBObject(QueryOperators.GTE, startTime));
    }

    if (endTime != CDOBranchPoint.UNSPECIFIED_DATE) {
        list.add(new BasicDBObject(QueryOperators.LTE, endTime));
    }

    int size = list.size();
    if (size == 2) {
        query.put(COMMITS_ID, list);
    } else if (size == 1) {
        query.put(COMMITS_ID, list.get(0));
    }

    InternalRepository repository = store.getRepository();
    final InternalCDOBranchManager branchManager = repository.getBranchManager();
    final InternalCDOCommitInfoManager commitManager = repository.getCommitInfoManager();

    new Query<Object>(query) {
        @Override
        public Object execute() {
            return execute(collection.find(getRef()).sort(new BasicDBObject(COMMITS_ID, 1)));
        }

        @Override
        protected Object handleDoc(DBObject doc) {
            long time = (Long) doc.get(COMMITS_ID);
            Object value = doc.get(COMMITS_PREVIOUS);
            long previous = value == null ? 0L : (Long) value;

            CDOBranch commitBranch;
            if (store.isBranching()) {
                int branchID = (Integer) doc.get(COMMITS_BRANCH);
                commitBranch = branchManager.getBranch(branchID);
            } else {
                commitBranch = branchManager.getMainBranch();
            }

            String user = (String) doc.get(COMMITS_USER);
            String comment = (String) doc.get(COMMITS_COMMENT);

            CDOCommitInfo commitInfo = commitManager.createCommitInfo(commitBranch, time, previous, user,
                    comment, null);
            handler.handleCommitInfo(commitInfo);
            return null;
        }
    }.execute();
}

From source file:org.eclipse.emf.cdo.server.internal.mongodb.Props.java

License:Open Source License

public void remove(Set<String> names) {
    BasicDBList list = new BasicDBList();
    for (String name : names) {
        list.add(name);//from w ww  . ja v a 2s  .c  o  m
    }

    DBObject ref = new BasicDBObject();
    ref.put(ID, new BasicDBObject("$in", list));

    collection.remove(ref);
}

From source file:org.eclipse.jetty.nosql.mongodb.MongoSessionDataStore.java

License:Open Source License

/** 
 * @see org.eclipse.jetty.server.session.SessionDataStore#getExpired(Set)
 *///from  w w  w. j ava  2s.c  o m
@Override
public Set<String> doGetExpired(Set<String> candidates) {
    long now = System.currentTimeMillis();
    long upperBound = now;
    Set<String> expiredSessions = new HashSet<>();

    //firstly ask mongo to verify if these candidate ids have expired - all of
    //these candidates will be for our node
    BasicDBObject query = new BasicDBObject();
    query.append(__ID, new BasicDBObject("$in", candidates));
    query.append(__EXPIRY, new BasicDBObject("$gt", 0).append("$lt", upperBound));

    DBCursor verifiedExpiredSessions = null;
    try {
        verifiedExpiredSessions = _dbSessions.find(query, new BasicDBObject(__ID, 1));
        for (DBObject session : verifiedExpiredSessions) {
            String id = (String) session.get(__ID);
            if (LOG.isDebugEnabled())
                LOG.debug("{} Mongo confirmed expired session {}", _context, id);
            expiredSessions.add(id);
        }
    } finally {
        if (verifiedExpiredSessions != null)
            verifiedExpiredSessions.close();
    }

    //now ask mongo to find sessions last managed by any nodes that expired a while ago 
    //if this is our first expiry check, make sure that we only grab really old sessions
    if (_lastExpiryCheckTime <= 0)
        upperBound = (now - (3 * (1000L * _gracePeriodSec)));
    else
        upperBound = _lastExpiryCheckTime - (1000L * _gracePeriodSec);

    query = new BasicDBObject();
    BasicDBObject gt = new BasicDBObject(__EXPIRY, new BasicDBObject("$gt", 0));
    BasicDBObject lt = new BasicDBObject(__EXPIRY, new BasicDBObject("$lt", upperBound));
    BasicDBList list = new BasicDBList();
    list.add(gt);
    list.add(lt);
    query.append("and", list);

    DBCursor oldExpiredSessions = null;
    try {
        BasicDBObject bo = new BasicDBObject(__ID, 1);
        bo.append(__EXPIRY, 1);

        oldExpiredSessions = _dbSessions.find(query, bo);
        for (DBObject session : oldExpiredSessions) {
            String id = (String) session.get(__ID);
            if (LOG.isDebugEnabled())
                LOG.debug("{} Mongo found old expired session {}", _context,
                        id + " exp=" + session.get(__EXPIRY));
            expiredSessions.add(id);
        }

    } finally {
        oldExpiredSessions.close();
    }

    return expiredSessions;
}