Example usage for com.mongodb DBObject keySet

List of usage examples for com.mongodb DBObject keySet

Introduction

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

Prototype

Set<String> keySet();

Source Link

Document

Returns this object's fields' names

Usage

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

License:Open Source License

/**
 * Returns the full names of selected fields in an ordered list.
 *//*ww  w . j a  va2  s. c  om*/
@SuppressWarnings("unchecked")
public List<String> getSelectedFieldNames() {
    Object propValue = getPropertiesMap().get(SELECTED_FIELDS_PROP);
    if (propValue instanceof List<?>)
        return (List<String>) propValue;

    if (propValue instanceof String) {
        DBObject projectionKeys = null;
        try {
            projectionKeys = parseExprToDBObject((String) propValue);
        } catch (OdaException ex) {
            // log and ignore
            getLogger().log(Level.INFO,
                    Messages.bind("Ignoring invalid Selected Fields expression: {0}", propValue), ex); //$NON-NLS-1$
            return Collections.emptyList();
        }

        // extract the included fields to a list of selected fields
        List<String> selectedFieldNames = new ArrayList<String>(projectionKeys.keySet().size());
        for (String key : projectionKeys.keySet()) {
            Object value = projectionKeys.get(key);
            if (value instanceof Integer) {
                if ((Integer) value == 0) // field is being excluded
                    continue;
            } else if (value instanceof Boolean && (Boolean) value == Boolean.FALSE) // field is being excluded
                continue;

            selectedFieldNames.add(key);
        }
        return selectedFieldNames;
    }

    return Collections.emptyList(); // null or non-recognized data type
}

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

License:Open Source License

public void initializeClassifiers() {
    final Classes classes = store.getClasses();

    DBObject query = new BasicDBObject();
    query.put(UNITS, new BasicDBObject("$exists", true));

    new QueryEmbeddedUnits<Object>(query) {
        @Override//  www  . j  a v  a  2s  .  com
        protected Object handleEmbedded(DBObject doc, DBObject embedded) {
            BasicDBList infos = (BasicDBList) embedded.get(PACKAGES);
            for (Object info : infos) {
                DBObject infoObject = (DBObject) info;
                String uri = (String) infoObject.get(PACKAGES_URI);
                handleClassifiers(infoObject, uri);
            }

            return null;
        }

        private void handleClassifiers(DBObject embedded, String packageURI) {
            Set<String> keys = embedded.keySet();
            for (String key : keys) {
                if (key.startsWith(CLASSIFIER_PREFIX)) {
                    int id = Integer.parseInt(key.substring(CLASSIFIER_PREFIX.length()));
                    String classifierName = (String) embedded.get(key);

                    CDOClassifierRef classifierRef = new CDOClassifierRef(packageURI, classifierName);
                    EClassifier classifier = classifierRef.resolve(packageRegistry);

                    classes.mapClassifier(classifier, id);
                }
            }
        }
    }.execute();
}

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

License:Open Source License

protected void showObject(CDOServerBrowser browser, PrintStream pout, DBObject doc, String level) {
    Set<String> keySet = doc.keySet();

    boolean highlight = false;
    try {/*from   w  ww  . j  a va2  s.  com*/
        String paramKey = browser.getParam("key");
        if (paramKey != null) {
            String paramValue = browser.getParam("value");
            Object value = doc.get(paramKey);
            if (String.valueOf(value).equals(paramValue)) {
                highlight = true;
            }
        }
    } catch (Exception ex) {
        // Ignore
    }

    if (highlight) {
        pout.print("<table border=\"0\" bgcolor=\"#FFFFA8\"><tr><td>");
    }

    for (String key : keySet) {
        pout.print(level);
        pout.print("<b>");
        pout.print(key);
        pout.print("</b> = ");

        Object value = doc.get(key);
        if (value instanceof DBObject) {
            DBObject child = (DBObject) value;
            pout.print("<br>");
            showObject(browser, pout, child, level + "&nbsp;&nbsp;");
        } else {
            pout.print("<font color=\"#0000FF\">");
            if (value instanceof String) {
                pout.print("\"");
                pout.print(browser.escape((String) value));
                pout.print("\"");
            } else {
                String string = String.valueOf(value);
                pout.print(browser.href(string, "collections", "key", key, "value", string));
            }

            pout.print("</font><br>");
        }
    }

    if (highlight) {
        pout.print("</td></tr></table>");
    }
}

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

License:Open Source License

/** 
 * @see org.eclipse.jetty.server.session.SessionDataStore#load(String)
 *///from   w ww  .  ja v  a2s. c  o  m
@Override
public SessionData load(String id) throws Exception {
    final AtomicReference<SessionData> reference = new AtomicReference<SessionData>();
    final AtomicReference<Exception> exception = new AtomicReference<Exception>();
    Runnable r = new Runnable() {
        public void run() {
            try {
                DBObject sessionDocument = _dbSessions.findOne(new BasicDBObject(__ID, id));

                if (LOG.isDebugEnabled())
                    LOG.debug("id={} loaded={}", id, sessionDocument);

                if (sessionDocument == null)
                    return;

                Boolean valid = (Boolean) sessionDocument.get(__VALID);

                if (LOG.isDebugEnabled())
                    LOG.debug("id={} valid={}", id, valid);
                if (valid == null || !valid)
                    return;

                Object version = getNestedValue(sessionDocument, getContextSubfield(__VERSION));
                Long lastSaved = (Long) getNestedValue(sessionDocument, getContextSubfield(__LASTSAVED));
                String lastNode = (String) getNestedValue(sessionDocument, getContextSubfield(__LASTNODE));

                Long created = (Long) sessionDocument.get(__CREATED);
                Long accessed = (Long) sessionDocument.get(__ACCESSED);
                Long maxInactive = (Long) sessionDocument.get(__MAX_IDLE);
                Long expiry = (Long) sessionDocument.get(__EXPIRY);

                NoSqlSessionData data = null;

                // get the session for the context
                DBObject sessionSubDocumentForContext = (DBObject) getNestedValue(sessionDocument,
                        getContextField());

                if (LOG.isDebugEnabled())
                    LOG.debug("attrs {}", sessionSubDocumentForContext);

                if (sessionSubDocumentForContext != null) {
                    if (LOG.isDebugEnabled())
                        LOG.debug("Session {} present for context {}", id, _context);

                    //only load a session if it exists for this context
                    data = (NoSqlSessionData) newSessionData(id, created, accessed, accessed, maxInactive);
                    data.setVersion(version);
                    data.setExpiry(expiry);
                    data.setContextPath(_context.getCanonicalContextPath());
                    data.setVhost(_context.getVhost());
                    data.setLastSaved(lastSaved);
                    data.setLastNode(lastNode);

                    HashMap<String, Object> attributes = new HashMap<>();
                    for (String name : sessionSubDocumentForContext.keySet()) {
                        //skip special metadata attribute which is not one of the actual session attributes
                        if (__METADATA.equals(name))
                            continue;
                        String attr = decodeName(name);
                        Object value = decodeValue(sessionSubDocumentForContext.get(name));
                        attributes.put(attr, value);
                    }

                    data.putAllAttributes(attributes);
                } else {
                    if (LOG.isDebugEnabled())
                        LOG.debug("Session  {} not present for context {}", id, _context);
                }

                reference.set(data);
            } catch (Exception e) {
                exception.set(e);
            }
        }
    };

    _context.run(r);

    if (exception.get() != null)
        throw exception.get();

    return reference.get();
}

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

License:Open Source License

/** 
 * @see org.eclipse.jetty.server.session.SessionDataStore#delete(String)
 *///from   w ww.j  a v  a2  s.  co m
@Override
public boolean delete(String id) throws Exception {
    if (LOG.isDebugEnabled())
        LOG.debug("Remove:session {} for context ", id, _context);

    /*
     * Check if the session exists and if it does remove the context
     * associated with this session
     */
    BasicDBObject mongoKey = new BasicDBObject(__ID, id);

    //DBObject sessionDocument = _dbSessions.findOne(mongoKey,_version_1);
    DBObject sessionDocument = _dbSessions.findOne(new BasicDBObject(__ID, id));

    if (sessionDocument != null) {
        DBObject c = (DBObject) getNestedValue(sessionDocument, __CONTEXT);
        if (c == null) {
            //delete whole doc
            _dbSessions.remove(mongoKey, WriteConcern.SAFE);
            return false;
        }

        Set<String> contexts = c.keySet();
        if (contexts.isEmpty()) {
            //delete whole doc
            _dbSessions.remove(mongoKey, WriteConcern.SAFE);
            return false;
        }

        if (contexts.size() == 1 && contexts.iterator().next().equals(getCanonicalContextId())) {
            //delete whole doc
            _dbSessions.remove(new BasicDBObject(__ID, id), WriteConcern.SAFE);
            return true;
        }

        //just remove entry for my context
        BasicDBObject remove = new BasicDBObject();
        BasicDBObject unsets = new BasicDBObject();
        unsets.put(getContextField(), 1);
        remove.put("$unset", unsets);
        WriteResult result = _dbSessions.update(mongoKey, remove, false, false, WriteConcern.SAFE);
        return true;
    } else {
        return false;
    }

}

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

License:Open Source License

@Override
protected Object refresh(NoSqlSession session, Object version) {
    __log.debug("MongoSessionManager:refresh session {}", session.getId());

    // check if our in memory version is the same as what is on the disk
    if (version != null) {
        DBObject o = _dbSessions.findOne(new BasicDBObject(__ID, session.getClusterId()), _version_1);

        if (o != null) {
            Object saved = getNestedValue(o, getContextAttributeKey(__VERSION));

            if (saved != null && saved.equals(version)) {
                __log.debug("MongoSessionManager:refresh not needed session {}", session.getId());
                return version;
            }/*  w w w.  j a  v  a  2  s  . c  o m*/
            version = saved;
        }
    }

    // If we are here, we have to load the object
    DBObject o = _dbSessions.findOne(new BasicDBObject(__ID, session.getClusterId()));

    // If it doesn't exist, invalidate
    if (o == null) {
        __log.debug("MongoSessionManager:refresh:marking session {} invalid, no object",
                session.getClusterId());
        session.invalidate();
        return null;
    }

    // If it has been flagged invalid, invalidate
    Boolean valid = (Boolean) o.get(__VALID);
    if (valid == null || !valid) {
        __log.debug("MongoSessionManager:refresh:marking session {} invalid, valid flag {}",
                session.getClusterId(), valid);
        session.invalidate();
        return null;
    }

    // We need to update the attributes. We will model this as a passivate,
    // followed by bindings and then activation.
    session.willPassivate();
    try {
        DBObject attrs = (DBObject) getNestedValue(o, getContextKey());
        //if disk version now has no attributes, get rid of them
        if (attrs == null || attrs.keySet().size() == 0) {
            session.clearAttributes();
        } else {
            //iterate over the names of the attributes on the disk version, updating the value
            for (String name : attrs.keySet()) {
                //skip special metadata field which is not one of the session attributes
                if (__METADATA.equals(name))
                    continue;

                String attr = decodeName(name);
                Object value = decodeValue(attrs.get(name));

                //session does not already contain this attribute, so bind it
                if (session.getAttribute(attr) == null) {
                    session.doPutOrRemove(attr, value);
                    session.bindValue(attr, value);
                } else //session already contains this attribute, update its value
                {
                    session.doPutOrRemove(attr, value);
                }

            }
            // cleanup, remove values from session, that don't exist in data anymore:
            for (String str : session.getNames()) {
                if (!attrs.keySet().contains(encodeName(str))) {
                    session.doPutOrRemove(str, null);
                    session.unbindValue(str, session.getAttribute(str));
                }
            }
        }

        /*
         * We are refreshing so we should update the last accessed time.
         */
        BasicDBObject key = new BasicDBObject(__ID, session.getClusterId());
        BasicDBObject sets = new BasicDBObject();
        // Form updates
        BasicDBObject update = new BasicDBObject();
        sets.put(__ACCESSED, System.currentTimeMillis());
        // Do the upsert
        if (!sets.isEmpty()) {
            update.put("$set", sets);
        }

        _dbSessions.update(key, update, false, false, WriteConcern.SAFE);

        session.didActivate();

        return version;
    } catch (Exception e) {
        LOG.warn(e);
    }

    return null;
}

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

License:Open Source License

@Override
protected synchronized NoSqlSession loadSession(String clusterId) {
    DBObject o = _dbSessions.findOne(new BasicDBObject(__ID, clusterId));

    __log.debug("MongoSessionManager:id={} loaded={}", clusterId, o);
    if (o == null)
        return null;

    Boolean valid = (Boolean) o.get(__VALID);
    __log.debug("MongoSessionManager:id={} valid={}", clusterId, valid);
    if (valid == null || !valid)
        return null;

    try {/*  w  w w. j  av  a 2 s.  c om*/
        Object version = o.get(getContextAttributeKey(__VERSION));
        Long created = (Long) o.get(__CREATED);
        Long accessed = (Long) o.get(__ACCESSED);

        NoSqlSession session = null;

        // get the session for the context
        DBObject attrs = (DBObject) getNestedValue(o, getContextKey());

        __log.debug("MongoSessionManager:attrs {}", attrs);
        if (attrs != null) {
            __log.debug("MongoSessionManager: session {} present for context {}", clusterId, getContextKey());
            //only load a session if it exists for this context
            session = new NoSqlSession(this, created, accessed, clusterId, version);

            for (String name : attrs.keySet()) {
                //skip special metadata attribute which is not one of the actual session attributes
                if (__METADATA.equals(name))
                    continue;

                String attr = decodeName(name);
                Object value = decodeValue(attrs.get(name));

                session.doPutOrRemove(attr, value);
                session.bindValue(attr, value);
            }
            session.didActivate();
        } else
            __log.debug("MongoSessionManager: session  {} not present for context {}", clusterId,
                    getContextKey());

        return session;
    } catch (Exception e) {
        LOG.warn(e);
    }
    return null;
}

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

License:Open Source License

/** 
 * @see org.eclipse.jetty.server.session.SessionStore#load(String)
 *///w ww .j ava 2s  . c om
@Override
public SessionData load(String id) throws Exception {
    final AtomicReference<SessionData> reference = new AtomicReference<SessionData>();
    final AtomicReference<Exception> exception = new AtomicReference<Exception>();
    Runnable r = new Runnable() {
        public void run() {
            try {
                DBObject sessionDocument = _dbSessions.findOne(new BasicDBObject(__ID, id));

                if (LOG.isDebugEnabled())
                    LOG.debug("id={} loaded={}", id, sessionDocument);

                if (sessionDocument == null)
                    return;

                Boolean valid = (Boolean) sessionDocument.get(__VALID);

                if (LOG.isDebugEnabled())
                    LOG.debug("id={} valid={}", id, valid);
                if (valid == null || !valid)
                    return;

                Object version = getNestedValue(sessionDocument, getContextSubfield(__VERSION));

                Long created = (Long) sessionDocument.get(__CREATED);
                Long accessed = (Long) sessionDocument.get(__ACCESSED);
                Long maxInactive = (Long) sessionDocument.get(__MAX_IDLE);
                Long expiry = (Long) sessionDocument.get(__EXPIRY);

                NoSqlSessionData data = null;

                // get the session for the context
                DBObject sessionSubDocumentForContext = (DBObject) getNestedValue(sessionDocument,
                        getContextField());

                if (LOG.isDebugEnabled())
                    LOG.debug("attrs {}", sessionSubDocumentForContext);

                if (sessionSubDocumentForContext != null) {
                    if (LOG.isDebugEnabled())
                        LOG.debug("Session {} present for context {}", id, _context);

                    //only load a session if it exists for this context
                    data = (NoSqlSessionData) newSessionData(id, created, accessed, accessed, maxInactive);
                    data.setVersion(version);
                    data.setExpiry(expiry);
                    data.setContextPath(_context.getCanonicalContextPath());
                    data.setVhost(_context.getVhost());

                    HashMap<String, Object> attributes = new HashMap<>();
                    for (String name : sessionSubDocumentForContext.keySet()) {
                        //skip special metadata attribute which is not one of the actual session attributes
                        if (__METADATA.equals(name))
                            continue;
                        String attr = decodeName(name);
                        Object value = decodeValue(sessionSubDocumentForContext.get(name));
                        attributes.put(attr, value);
                    }

                    data.putAllAttributes(attributes);
                } else {
                    if (LOG.isDebugEnabled())
                        LOG.debug("Session  {} not present for context {}", id, _context);
                }

                reference.set(data);
            } catch (Exception e) {
                exception.set(e);
            }
        }
    };

    _context.run(r);

    if (exception.get() != null)
        throw exception.get();

    return reference.get();
}

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

License:Open Source License

/** 
 * @see org.eclipse.jetty.server.session.SessionStore#delete(String)
 *///w  w w .  jav  a2 s . c om
@Override
public boolean delete(String id) throws Exception {
    if (LOG.isDebugEnabled())
        LOG.debug("Remove:session {} for context ", id, _context);

    /*
     * Check if the session exists and if it does remove the context
     * associated with this session
     */
    BasicDBObject mongoKey = new BasicDBObject(__ID, id);

    DBObject sessionDocument = _dbSessions.findOne(mongoKey, _version_1);

    if (sessionDocument != null) {
        DBObject c = (DBObject) getNestedValue(sessionDocument, __CONTEXT);
        if (c == null) {
            //delete whole doc
            _dbSessions.remove(mongoKey);
            return false;
        }

        Set<String> contexts = c.keySet();
        if (contexts.isEmpty()) {
            //delete whole doc
            _dbSessions.remove(mongoKey);
            return false;
        }

        if (contexts.size() == 1 && contexts.iterator().next().equals(getCanonicalContextId())) {
            //delete whole doc
            _dbSessions.remove(mongoKey);
            return true;
        }

        //just remove entry for my context
        BasicDBObject remove = new BasicDBObject();
        BasicDBObject unsets = new BasicDBObject();
        unsets.put(getContextField(), 1);
        remove.put("$unset", unsets);
        _dbSessions.update(mongoKey, remove, false, false, WriteConcern.SAFE);

        return true;
    } else {
        return false;
    }

}

From source file:org.eclipselabs.mongoemf.query.simple.SimpleQueryEngine.java

License:Open Source License

private DBObject buildDBObjectQuery(Expression expression) {
    final DBObject dbObject = new BasicDBObject();

    if (expression != null) {
        new QuerySwitch<Object>() {
            Object getValue(Literal literal) {
                return literal.getValue() == null ? literal.getLiteralValue() : literal.getValue();
            }/*w  w w  .  j av  a  2s  . c  o m*/

            @Override
            public Object caseBinaryOperation(BinaryOperation binaryOperation) {
                Expression leftOperand = binaryOperation.getLeftOperand();
                String operator = binaryOperation.getOperator();

                if ("==".equals(operator)) {
                    Expression rightOperand = binaryOperation.getRightOperand();
                    String property = ExpressionBuilder.toString(leftOperand);

                    if (Keywords.ID_KEY.equals(property)) {
                        dbObject.put(property, new ObjectId(((Literal) rightOperand).getLiteralValue()));
                    } else if (rightOperand instanceof Literal) {
                        dbObject.put(property, getValue((Literal) rightOperand));
                    } else if ("null".equals(ExpressionBuilder.toString(rightOperand))) {
                        DBObject notExists = new BasicDBObject();
                        notExists.put("$exists", Boolean.FALSE);
                        dbObject.put(property, notExists);
                    } else {
                        // TODO: What to do?
                    }
                } else if ("!=".equals(operator)) {
                    Expression rightOperand = binaryOperation.getRightOperand();
                    String property = ExpressionBuilder.toString(leftOperand);
                    if (rightOperand instanceof Literal) {
                        DBObject notEqual = new BasicDBObject();
                        notEqual.put("$ne", getValue((Literal) rightOperand));
                        dbObject.put(property, notEqual);
                    } else if ("null".equals(ExpressionBuilder.toString(rightOperand))) {
                        DBObject exists = new BasicDBObject();
                        exists.put("$exists", Boolean.TRUE);
                        dbObject.put(property, exists);
                    } else {
                        // TODO: What to do?
                    }
                } else if ("<".equals(operator) || "<=".equals(operator) || ">".equals(operator)
                        || ">=".equals(operator)) {
                    Expression rightOperand = binaryOperation.getRightOperand();
                    String property = ExpressionBuilder.toString(leftOperand);
                    if (rightOperand instanceof Literal) {
                        DBObject compare = new BasicDBObject();
                        compare.put(
                                "<".equals(operator) ? QueryOperators.LT
                                        : "<=".equals(operator) ? QueryOperators.LTE
                                                : ">".equals(operator) ? QueryOperators.GT : QueryOperators.GTE,
                                getValue((Literal) rightOperand));
                        dbObject.put(property, compare);
                    } else {
                        // TODO: What to do?
                    }
                } else if ("||".equals(operator)) {
                    DBObject leftObject = buildDBObjectQuery(leftOperand);
                    DBObject rightObject = buildDBObjectQuery(binaryOperation.getRightOperand());
                    @SuppressWarnings("unchecked")
                    List<Object> or = (List<Object>) leftObject.get("$or");
                    if (or != null) {
                        or.add(rightObject);
                        dbObject.putAll(leftObject);
                    } else {
                        or = new ArrayList<Object>();
                        or.add(leftObject);
                        or.add(rightObject);
                        dbObject.put("$or", or);
                    }
                } else if ("&&".equals(operator)) {
                    dbObject.putAll(buildDBObjectQuery(leftOperand));
                    DBObject rightObject = buildDBObjectQuery(binaryOperation.getRightOperand());
                    for (String field : rightObject.keySet()) {
                        Object rightValue = rightObject.get(field);
                        Object leftValue = dbObject.get(field);
                        if (leftValue instanceof DBObject) {
                            DBObject leftDBObject = (DBObject) leftValue;
                            if (rightValue instanceof DBObject) {
                                DBObject rightDBObject = (DBObject) rightValue;
                                if (leftDBObject.containsField("$nin") && rightDBObject.containsField("$ne")) {
                                    @SuppressWarnings("unchecked")
                                    List<Object> values = (List<Object>) leftDBObject.get("$nin");
                                    values.add(rightDBObject.get("$ne"));
                                } else if (leftDBObject.containsField("$ne")
                                        && rightDBObject.containsField("$ne")) {
                                    DBObject nin = new BasicDBObject();
                                    List<Object> values = new ArrayList<Object>();
                                    values.add(leftDBObject.get("$ne"));
                                    values.add(rightDBObject.get("$ne"));
                                    nin.put("$nin", values);
                                    dbObject.put(field, nin);
                                } else {
                                    leftDBObject.putAll(rightDBObject);
                                }
                            } else {
                                Object all = leftDBObject.get("$all");
                                if (all instanceof List<?>) {
                                    @SuppressWarnings("unchecked")
                                    List<Object> allList = (List<Object>) all;
                                    allList.add(rightValue);
                                } else {
                                    // What to do?
                                }
                            }
                        } else if (leftValue instanceof List<?>) {
                            @SuppressWarnings("unchecked")
                            List<Object> leftListValue = (List<Object>) leftValue;
                            if (rightValue instanceof List<?>) {
                                leftListValue.addAll((List<?>) rightValue);
                            } else {
                                leftListValue.add(rightValue);
                            }
                        } else if (leftValue != null) {
                            if (rightValue instanceof List<?>) {
                                @SuppressWarnings("unchecked")
                                List<Object> rightListValue = (List<Object>) rightValue;
                                rightListValue.add(0, leftValue);
                                dbObject.put(field, rightListValue);
                            } else {
                                List<Object> listValue = new ArrayList<Object>();
                                listValue.add(leftValue);
                                listValue.add(rightValue);
                                DBObject in = new BasicDBObject("$all", listValue);
                                dbObject.put(field, in);
                            }
                        } else {
                            dbObject.put(field, rightValue);
                        }
                    }
                }

                return null;
            }
        }.doSwitch(expression);
    }

    return dbObject;
}