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:com.jaspersoft.mongodb.query.MongoDbQueryWrapper.java

License:Open Source License

private Object fixQueryObject(DBObject queryObjectToFix, Map<String, Object> reportParameters) {
    Set<String> keySet = queryObjectToFix.keySet();
    if (keySet.size() == 1) {
        String key = keySet.iterator().next();
        if (reportParameters.containsKey(key) && queryObjectToFix.get(key) == null) {
            return reportParameters.get(key);
        }/* w  w  w .j  a  v a  2s . c o m*/
    }
    for (String key : queryObjectToFix.keySet()) {
        Object value = queryObjectToFix.get(key);
        if (value instanceof DBObject) {
            queryObjectToFix.put(key, fixQueryObject((DBObject) value, reportParameters));
        }
    }
    return queryObjectToFix;
}

From source file:com.jaspersoft.mongodb.query.MongoDbQueryWrapper.java

License:Open Source License

private void createIterator() throws JRException {
    if (!queryObject.containsField(COLLECTION_NAME_KEY)) {
        throw new JRException("\"" + COLLECTION_NAME_KEY + "\" must be part of the query object");
    }/*from   w  ww  . j  a v  a  2  s.com*/
    DBObject findQueryObject = (DBObject) queryObject.get(FIND_QUERY_KEY);
    if (findQueryObject == null) {
        findQueryObject = new BasicDBObject();
    }
    if (queryObject.containsField(FIND_QUERY_REGEXP_KEY)) {
        DBObject regExpObject = (DBObject) queryObject.get(FIND_QUERY_REGEXP_KEY);
        String value, flags;
        int index;
        for (String key : regExpObject.keySet()) {
            value = (String) regExpObject.get(key);
            if (value.startsWith("/")) {
                value = value.substring(1, value.length());
            } else {
                throw new JRException("Regular expressions must start with: /");
            }
            if (!value.contains("/")) {
                throw new JRException("No ending symbol found: /");
            }
            index = value.lastIndexOf("/");
            flags = null;
            if (index == value.length() - 1) {
                value = value.substring(0, index);
            } else {
                flags = value.substring(index + 1, value.length());
                value = value.substring(0, index);
            }
            findQueryObject.put(key, Pattern.compile((flags != null ? "(?" + flags + ")" : "") + value));
        }
    }

    DBCollection collection = connection.getMongoDatabase()
            .getCollectionFromString((String) queryObject.removeField(COLLECTION_NAME_KEY));
    if (queryObject.containsField(MAP_REDUCE_KEY)) {
        Object value = queryObject.removeField(MAP_REDUCE_KEY);
        if (!(value instanceof DBObject)) {
            logger.error("MapReduce value must be a valid JSON object");
        } else {
            DBObject mapReduceObject = (DBObject) value;
            String map = validateProperty(mapReduceObject, MAP_KEY);
            String reduce = validateProperty(mapReduceObject, REDUCE_KEY);
            Object outObject = mapReduceObject.get(OUT_KEY);
            if (outObject == null) {
                throw new JRException("\"out\" cannot be null");
            }
            String collectionName = null;
            Object outDb = null;
            OutputType outputType = null;
            boolean hasOutputType = false;
            if (logger.isDebugEnabled()) {
                logger.debug("Out object: " + outObject + ". Type: " + outObject.getClass().getName());
            }
            if (outObject instanceof String) {
                collectionName = String.valueOf(outObject);
            } else if (outObject instanceof DBObject) {
                DBObject outDbObject = (DBObject) outObject;
                outDb = outDbObject.removeField(OUT_DB_KEY);
                Iterator<String> keysIterator = outDbObject.keySet().iterator();
                String type = null;
                if (keysIterator.hasNext()) {
                    type = keysIterator.next();
                    collectionName = String.valueOf(outDbObject.get(type));
                } else {
                    throw new JRException("\"out\" object cannot be empty");
                }
                type = type.toUpperCase();
                outputType = OutputType.valueOf(type);
                if (outputType == null) {
                    throw new JRException("Unknow output type: " + type);
                }
                hasOutputType = true;
                if (logger.isDebugEnabled()) {
                    logger.debug("outobject: " + outDbObject);
                    logger.debug("collectionName: " + collectionName);
                    logger.debug("outputType: " + outputType);
                }
            } else {
                throw new JRException("Unsupported type for \"out\": " + outObject.getClass().getName());
            }
            MapReduceCommand mapReduceCommand = new MapReduceCommand(collection, map, reduce, collectionName,
                    hasOutputType ? outputType : OutputType.REPLACE, null);
            if (outDb != null) {
                mapReduceCommand.setOutputDB(String.valueOf(outDb));
            }
            Object finalizeObject = mapReduceObject.removeField(FINALIZE_KEY);
            if (finalizeObject != null) {
                mapReduceCommand.setFinalize(String.valueOf(finalizeObject));
            }
            MapReduceOutput mapReduceOutput = collection.mapReduce(mapReduceCommand);
            DBCollection mapReduceCollection = mapReduceOutput.getOutputCollection();
            if (mapReduceCollection != null) {
                collection = mapReduceCollection;
            }
        }
    }

    iterator = collection.find(findQueryObject, (DBObject) queryObject.get(FIND_FIELDS_KEY));
    if (queryObject.containsField(SORT_KEY)) {
        iterator = iterator.sort((DBObject) queryObject.get(SORT_KEY));
    }
    if (queryObject.containsField(LIMIT_KEY)) {
        Integer value = processInteger(queryObject.get(LIMIT_KEY));
        if (value != null) {
            iterator = iterator.limit(value.intValue());
        }
    }
}

From source file:com.jhkt.playgroundArena.db.nosql.mongodb.beans.AbstractDocument.java

License:Apache License

private final static Object convertBacktoClassInstanceHelper(DBObject dBObject) {

    Object returnValue = null;/*from  www . ja va  2 s  .  co m*/

    try {
        String className = dBObject.get(JPAConstants.CONVERTER_CLASS.CLASS.name()).toString();
        Class<?> classCheck = Class.forName(className);

        if (AbstractDocument.class.isAssignableFrom(classCheck)) {
            Class<? extends AbstractDocument> classToConvertTo = classCheck.asSubclass(AbstractDocument.class);
            AbstractDocument dInstance = classToConvertTo.newInstance();

            for (String key : dBObject.keySet()) {
                Object value = dBObject.get(key);

                char[] propertyChars = key.toCharArray();
                String methodMain = String.valueOf(propertyChars[0]).toUpperCase() + key.substring(1);
                String methodName = "set" + methodMain;
                String getMethodName = "get" + methodMain;

                if (key.equals(JPAConstants.CONVERTER_CLASS.CLASS.name())) {
                    continue;
                }

                if (value instanceof BasicDBObject) {
                    value = convertBacktoClassInstanceHelper(BasicDBObject.class.cast(value));
                }

                try {
                    Method getMethod = classToConvertTo.getMethod(getMethodName);
                    Class<?> getReturnType = getMethod.getReturnType();
                    Method method = classToConvertTo.getMethod(methodName, getReturnType);

                    if (getMethod.isAnnotationPresent(IDocumentKeyValue.class)) {
                        method.invoke(dInstance, value);
                    }
                } catch (NoSuchMethodException nsMe) {
                    _log.warn("Within convertBacktoClassInstance, following method was not found " + methodName,
                            nsMe);
                }

            }

            returnValue = dInstance;

        } else if (Enum.class.isAssignableFrom(classCheck)) {

            List<?> constants = Arrays.asList(classCheck.getEnumConstants());
            String name = String.class.cast(dBObject.get(JPAConstants.CONVERTER_CLASS.CONTENT.name()));
            for (Object constant : constants) {
                if (constant.toString().equals(name)) {
                    returnValue = constant;
                }
            }

        } else if (Collection.class.isAssignableFrom(classCheck)) {

            @SuppressWarnings("unchecked")
            Class<? extends Collection<? super Object>> classToConvertTo = (Class<? extends Collection<? super Object>>) classCheck;
            Collection<? super Object> cInstance = classToConvertTo.newInstance();

            BasicDBList bDBList = (BasicDBList) dBObject.get(JPAConstants.CONVERTER_CLASS.CONTENT.name());
            cInstance.addAll(bDBList);

            returnValue = cInstance;

        } else if (Map.class.isAssignableFrom(classCheck)) {

            @SuppressWarnings("unchecked")
            Class<? extends Map<String, ? super Object>> classToConvertTo = (Class<? extends Map<String, ? super Object>>) classCheck;
            Map<String, ? super Object> mInstance = classToConvertTo.newInstance();

            BasicDBObject mapObject = (BasicDBObject) dBObject.get(JPAConstants.CONVERTER_CLASS.CONTENT.name());
            mInstance.putAll(mapObject);

            returnValue = mInstance;

        }

    } catch (Exception e) {
        throw new RuntimeException(e);
    }

    return returnValue;
}

From source file:com.joyfulmongo.db.javadriver.JFDBUtil.java

License:Apache License

public static JSONObject toJSONObject(DBObject o) {
    JSONObject result = new JSONObject();

    try {/*from   w  w  w. j  a  va2s  . co  m*/
        Iterator<String> i = o.keySet().iterator();
        while (i.hasNext()) {
            String k = (String) i.next();
            Object v = o.get(k);
            if (LOGGER.isLoggable(Level.FINE)) {
                LOGGER.log(Level.FINE, "toJSON Key=[" + k + "]=[" + v + "] " + v.getClass());
            }

            if (v instanceof BasicDBList) {
                result.put(k, toJSONArray((BasicDBList) v));
            } else if (v instanceof DBObject) {
                DBObject dv = (DBObject) v;
                String op = (String) dv.get("__op");
                if (op != null) {
                    Object objs = dv.get("objects");
                    if (objs == null) {
                        // ignore
                    } else if (objs instanceof BasicDBList) {
                        JSONArray jarray = toJSONArray((BasicDBList) objs);
                        result.put(k, jarray);
                    } else {
                        result.put(k, toJSONObject((DBObject) objs));
                    }
                } else {
                    result.put(k, toJSONObject((DBObject) v));
                }
            } else if (v instanceof ObjectId) {
                // ignore the mongo objectId;
            } else if (v instanceof Date) {
                DateFormat format = Utils.getParseDateFormat();
                result.put(k, format.format((Date) v));
            } else {
                result.put(k, v);
            }
        }
        return result;
    } catch (JSONException je) {
        return null;
    }
}

From source file:com.kurento.kmf.repository.internal.repoimpl.filesystem.ItemsMetadata.java

License:Open Source License

private void loadItemsMetadata() throws IOException {
    itemsMetadata = new ConcurrentHashMap<>();
    DBObject contents = (DBObject) JSON.parse(loadFileAsString());
    if (contents != null) {
        for (String key : contents.keySet()) {
            try {
                DBObject metadata = (DBObject) contents.get(key);
                Map<String, String> map = new HashMap<>();
                for (String metadataKey : metadata.keySet()) {
                    map.put(metadataKey, metadata.get(metadataKey).toString());
                }/*from   w ww .  ja va2s.c o  m*/
                itemsMetadata.put(key, map);
            } catch (ClassCastException e) {
                log.warn("Attribute '{}' should be an object", key);
            }
        }
    }
}

From source file:com.kurento.kmf.repository.internal.repoimpl.mongo.MongoRepository.java

License:Open Source License

private MongoRepositoryItem createRepositoryItem(GridFSDBFile dbFile) {

    MongoRepositoryItem item = new MongoRepositoryItem(this, dbFile);

    Map<String, String> metadata = new HashMap<>();
    DBObject object = dbFile.getMetaData();
    for (String key : object.keySet()) {
        metadata.put(key, object.get(key).toString());
    }/*from   ww  w .j ava 2s . c om*/
    item.setMetadata(metadata);
    return item;
}

From source file:com.mebigfatguy.mongobrowser.dialogs.MongoDataPanel.java

License:Apache License

/**
 * installs the event listeners for the components on this panel
 */// w  ww .  j a v  a 2 s .  c om
private void initListeners() {
    final JPopupMenu menu = new JPopupMenu();

    tree.addMouseListener(new MouseAdapter() {
        @Override
        public void mouseClicked(MouseEvent e) {
            showPopup(e);
        }

        @Override
        public void mousePressed(MouseEvent e) {
            showPopup(e);
        }

        @Override
        public void mouseReleased(MouseEvent e) {
            showPopup(e);
        }

        private void showPopup(MouseEvent e) {
            int x = e.getX();
            int y = e.getY();
            if (e.isPopupTrigger()) {
                menu.removeAll();
                TreePath path = tree.getPathForLocation(x, y);
                if (path == null) {
                    menu.add(newCollectionItem);
                    menu.show(tree, x, y);
                } else {
                    MongoTreeNode node = (MongoTreeNode) path.getLastPathComponent();
                    context.setSelectedNode(node);
                    if (node.getType() == MongoTreeNode.Type.Collection) {
                        if (!node.isReadOnly()) {
                            menu.add(newObjectItem);
                            menu.show(tree, x, y);
                        }
                    } else if (node.getType() == MongoTreeNode.Type.Object) {
                        if (!node.isReadOnly()) {
                            menu.add(newKeyValueItem);
                            menu.addSeparator();
                            menu.add(deleteItem);
                            menu.show(tree, x, y);
                        }
                    } else if (node.getType() == MongoTreeNode.Type.KeyValue) {
                        if (!node.isReadOnly()) {
                            MongoTreeNode.KV kv = (MongoTreeNode.KV) node.getUserObject();
                            Object value = kv.getValue();
                            boolean needsSeparator = false;
                            if (value instanceof DBObject) {
                                menu.add(newKeyValueItem);
                                needsSeparator = true;
                            }

                            if (!kv.getKey().startsWith("_")) {
                                if (needsSeparator) {
                                    menu.addSeparator();
                                }
                                menu.add(deleteItem);
                                menu.show(tree, x, y);
                            }
                        }
                    }
                }
            }
        }
    });

    tree.addTreeWillExpandListener(new TreeWillExpandListener() {
        @Override
        public void treeWillExpand(TreeExpansionEvent event) throws ExpandVetoException {
            MongoTreeNode node = (MongoTreeNode) event.getPath().getLastPathComponent();
            MongoTreeNode slug = (MongoTreeNode) node.getFirstChild();
            if (slug.getType() == MongoTreeNode.Type.ExpansionSlug) {
                node.removeAllChildren();
                switch (node.getType()) {
                case Collection: {
                    DBCollection collection = (DBCollection) node.getUserObject();
                    DBCursor cursor = collection.find();
                    while (cursor.hasNext()) {
                        DBObject obj = cursor.next();
                        MongoTreeNode objNode = new MongoTreeNode(obj, node.isReadOnly());
                        node.add(objNode);
                        slug = new MongoTreeNode();
                        objNode.add(slug);
                    }
                }
                    break;

                case Object: {
                    DBObject object = (DBObject) node.getUserObject();
                    for (String key : object.keySet()) {
                        Object value = object.get(key);
                        MongoTreeNode kv = new MongoTreeNode(new MongoTreeNode.KV(key, value),
                                node.isReadOnly());
                        node.add(kv);
                        if (value instanceof DBObject) {
                            slug = new MongoTreeNode();
                            kv.add(slug);
                        }
                    }
                }
                    break;

                case KeyValue: {
                    MongoTreeNode.KV topKV = (MongoTreeNode.KV) node.getUserObject();
                    DBObject object = (DBObject) topKV.getValue();
                    for (String key : object.keySet()) {
                        Object value = object.get(key);
                        MongoTreeNode kv = new MongoTreeNode(new MongoTreeNode.KV(key, value),
                                node.isReadOnly());
                        node.add(kv);
                        if (value instanceof DBObject) {
                            slug = new MongoTreeNode();
                            kv.add(slug);
                        }
                    }
                }
                    break;
                }
            }

            DefaultTreeModel model = (DefaultTreeModel) tree.getModel();
            model.nodeStructureChanged(node);
        }

        @Override
        public void treeWillCollapse(TreeExpansionEvent event) throws ExpandVetoException {
            MongoTreeNode node = (MongoTreeNode) event.getPath().getLastPathComponent();
            node.removeAllChildren();
            MongoTreeNode slug = new MongoTreeNode();
            node.add(slug);
            DefaultTreeModel model = (DefaultTreeModel) tree.getModel();
            model.nodeStructureChanged(node);
        }

    });

    tree.addTreeSelectionListener(new TreeSelectionListener() {
        @Override
        public void valueChanged(TreeSelectionEvent tse) {
            TreePath path = tse.getNewLeadSelectionPath();
            if (path != null) {
                MongoTreeNode node = (MongoTreeNode) path.getLastPathComponent();
                context.setSelectedNode(node);
            } else {
                context.setSelectedNode(null);
            }
        }
    });
}

From source file:com.mobileman.kuravis.core.services.entity.impl.AbstractEntityServiceImpl.java

License:Apache License

/**
 * @param entityName/*from  w w w .ja va 2 s  .c  o  m*/
 * @param query
 * @return list of all documents by query
 */
@Override
public List<DBObject> findAllByQuery(String entityName, DBObject query, DBObject projection) {
    if (query.containsField(EntityUtils.NAME)) {
        String name = (String) query.get(EntityUtils.NAME);
        query.put(EntityUtils.NAME,
                new BasicDBObject("$regex", "^" + name.toLowerCase() + "$").append("$options", "i"));
    }

    final DBCursor cursor;
    if (projection != null && projection.keySet().size() > 0) {
        cursor = getCollection(entityName).find(query, projection);
    } else {
        cursor = getCollection(entityName).find(query);
    }

    List<DBObject> result = cursor.toArray();
    return result;
}

From source file:com.mulesoft.quartz.mongo.MongoDBJobStore.java

License:Open Source License

public JobDetail retrieveJob(JobKey jobKey) throws JobPersistenceException {
    DBObject dbObject = retrieveJobDBObject(jobKey);

    try {/*from   w  w  w .jav a 2  s  .co m*/
        Class<Job> jobClass = (Class<Job>) loadHelper.getClassLoader()
                .loadClass((String) dbObject.get(JOB_CLASS));

        JobBuilder builder = JobBuilder.newJob(jobClass)
                .withIdentity((String) dbObject.get(JOB_KEY_NAME), (String) dbObject.get(JOB_KEY_GROUP))
                .withDescription((String) dbObject.get(JOB_KEY_NAME));

        JobDataMap jobData = new JobDataMap();
        for (String key : dbObject.keySet()) {
            if (!key.equals(JOB_KEY_NAME) && !key.equals(JOB_KEY_GROUP) && !key.equals(JOB_CLASS)
                    && !key.equals(JOB_DESCRIPTION) && !key.equals("_id")) {
                jobData.put(key, dbObject.get(key));
            }
        }

        return builder.usingJobData(jobData).build();
    } catch (ClassNotFoundException e) {
        throw new JobPersistenceException("Could not load job class " + dbObject.get(JOB_CLASS), e);
    }
}

From source file:com.novemberain.quartz.mongodb.MongoDBJobStore.java

License:Open Source License

@SuppressWarnings("unchecked")
public JobDetail retrieveJob(JobKey jobKey) throws JobPersistenceException {
    DBObject dbObject = findJobDocumentByKey(jobKey);
    if (dbObject == null) {
        //Return null if job does not exist, per interface
        return null;
    }/*from   ww w  . jav  a 2  s .c om*/

    try {
        Class<Job> jobClass = (Class<Job>) getJobClassLoader().loadClass((String) dbObject.get(JOB_CLASS));

        JobBuilder builder = JobBuilder.newJob(jobClass)
                .withIdentity((String) dbObject.get(KEY_NAME), (String) dbObject.get(KEY_GROUP))
                .withDescription((String) dbObject.get(JOB_DESCRIPTION));

        JobDataMap jobData = new JobDataMap();

        String jobDataString = (String) dbObject.get(JOB_DATA);

        if (jobDataString != null) {
            jobDataMapFromString(jobData, jobDataString);
        } else {
            for (String key : dbObject.keySet()) {
                if (!key.equals(KEY_NAME) && !key.equals(KEY_GROUP) && !key.equals(JOB_CLASS)
                        && !key.equals(JOB_DESCRIPTION) && !key.equals("_id")) {
                    jobData.put(key, dbObject.get(key));
                }
            }
        }

        jobData.clearDirtyFlag();

        return builder.usingJobData(jobData).build();
    } catch (ClassNotFoundException e) {
        throw new JobPersistenceException("Could not load job class " + dbObject.get(JOB_CLASS), e);
    } catch (IOException e) {
        throw new JobPersistenceException("Could not load job class " + dbObject.get(JOB_CLASS), e);
    }
}