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.slc.sli.domain.MongoEntity.java

License:Apache License

@SuppressWarnings("unchecked")
private static Map<String, List<Entity>> extractContainerData(DBObject dbObj) {
    ContainerDocumentHolder containerDocumentHolder = new ContainerDocumentHolder();
    Map<String, List<Entity>> containerData = new HashMap<String, List<Entity>>();

    for (String key : dbObj.keySet()) {
        if (containerDocumentHolder.isContainerDocument(key)) {
            List<DBObject> values = (List<DBObject>) dbObj.get(key);
            List<Entity> subEntityList = new ArrayList<Entity>();
            for (DBObject subEntity : values) {
                subEntityList.add(fromDBObject(subEntity));
            }/*from  w ww . j  a  v a2s . c o  m*/
            containerData.put(key, subEntityList);
        }
    }

    return containerData;
}

From source file:org.slc.sli.ingestion.csv.CsvCombine.java

License:Apache License

/**
 * Parse an element (table row) representing a complex type and return the associated NR map.
 *///from  w  w  w  .j  ava2  s .  c  o m
private Map<String, Object> parseDbElement(DBObject dbElement, int joinKey, String entityName,
        List<DBCollection> supportingCollections) {
    Map<String, Object> result = new HashMap<String, Object>();

    Set<String> keySet = dbElement.keySet();

    // add all entries from this table rowprefix
    for (Iterator<String> it = keySet.iterator(); it.hasNext();) {
        String curKey = it.next();
        if (curKey.equals("_id") || curKey.equals("JoinKey") || curKey.equals("ParentJoinKey")) {
            continue;
        }

        String curVal = "" + dbElement.get(curKey);
        addMapEntry(curKey, curVal, result);

        /**
         * Now pick up the supporting list of list files.
         * The outer 'if' statement ensures this is only called if
         * further levels of hierarchy exist
         */
        for (Iterator<DBCollection> iter = supportingCollections.iterator(); iter.hasNext();) {
            String collectionName = iter.next().toString();
            if (collectionName.lastIndexOf('_') == entityName.length()) {
                String listName = collectionName.substring(entityName.length() + 1);
                addMapEntry(listName, getListFromCollection(collectionName, joinKey, supportingCollections),
                        result);
            }
        }
    }
    return result;
}

From source file:org.springframework.data.document.mongodb.convert.MappingMongoConverter.java

License:Apache License

private <S extends Object> S read(final MongoPersistentEntity<S> entity, final DBObject dbo) {

    final StandardEvaluationContext spelCtx = new StandardEvaluationContext();
    if (null != applicationContext) {
        spelCtx.setBeanResolver(new BeanFactoryResolver(applicationContext));
    }//from   w w w  .  jav  a2s  .  c o  m
    if (!(dbo instanceof BasicDBList)) {
        String[] keySet = dbo.keySet().toArray(new String[] {});
        for (String key : keySet) {
            spelCtx.setVariable(key, dbo.get(key));
        }
    }

    final List<String> ctorParamNames = new ArrayList<String>();
    final MongoPersistentProperty idProperty = entity.getIdProperty();
    final S instance = constructInstance(entity, new PreferredConstructor.ParameterValueProvider() {
        @SuppressWarnings("unchecked")
        public <T> T getParameterValue(PreferredConstructor.Parameter<T> parameter) {
            String name = parameter.getName();
            TypeInformation<T> type = parameter.getType();
            Class<T> rawType = parameter.getRawType();
            String key = idProperty == null ? name
                    : idProperty.getName().equals(name) ? idProperty.getKey() : name;
            Object obj = dbo.get(key);

            ctorParamNames.add(name);
            if (obj instanceof DBRef) {
                return read(type, ((DBRef) obj).fetch());
            } else if (obj instanceof BasicDBList) {
                BasicDBList objAsDbList = (BasicDBList) obj;
                List<?> l = unwrapList(objAsDbList, type);
                return conversionService.convert(l, rawType);
            } else if (obj instanceof DBObject) {
                return read(type, ((DBObject) obj));
            } else if (null != obj && obj.getClass().isAssignableFrom(rawType)) {
                return (T) obj;
            } else if (null != obj) {
                return conversionService.convert(obj, rawType);
            }

            return null;
        }
    }, spelCtx);

    // Set properties not already set in the constructor
    entity.doWithProperties(new PropertyHandler<MongoPersistentProperty>() {
        public void doWithPersistentProperty(MongoPersistentProperty prop) {

            boolean isConstructorProperty = ctorParamNames.contains(prop.getName());
            boolean hasValueForProperty = dbo.containsField(prop.getKey());

            if (!hasValueForProperty || isConstructorProperty) {
                return;
            }

            Object obj = getValueInternal(prop, dbo, spelCtx, prop.getSpelExpression());
            try {
                setProperty(instance, prop, obj, useFieldAccessOnly);
            } catch (IllegalAccessException e) {
                throw new MappingException(e.getMessage(), e);
            } catch (InvocationTargetException e) {
                throw new MappingException(e.getMessage(), e);
            }
        }
    });

    // Handle associations
    entity.doWithAssociations(new AssociationHandler<MongoPersistentProperty>() {
        public void doWithAssociation(Association<MongoPersistentProperty> association) {
            MongoPersistentProperty inverseProp = association.getInverse();
            Object obj = getValueInternal(inverseProp, dbo, spelCtx, inverseProp.getSpelExpression());
            try {
                setProperty(instance, inverseProp, obj);
            } catch (IllegalAccessException e) {
                throw new MappingException(e.getMessage(), e);
            } catch (InvocationTargetException e) {
                throw new MappingException(e.getMessage(), e);
            }
        }
    });

    return instance;
}

From source file:org.springframework.data.document.mongodb.convert.SimpleMongoConverter.java

License:Apache License

/**
 * Reads every key/value pair from the {@link DBObject} into a {@link Map} instance.
 *
 * @param pd/*from  ww w.j  av a 2 s . co  m*/
 * @param dbo
 * @param targetType
 * @return
 */
protected Map<?, ?> readMap(MongoPropertyDescriptor pd, DBObject dbo, Class<?> targetType) {
    Map<String, Object> map = createMap();
    for (String key : dbo.keySet()) {
        Object value = dbo.get(key);
        if (!isSimpleType(value.getClass())) {
            map.put(key, read(targetType, (DBObject) value));
            // Can do some reflection tricks here -
            // throw new RuntimeException("User types not supported yet as values for Maps");
        } else {
            map.put(key, conversionService.convert(value, targetType));
        }
    }
    return map;
}

From source file:org.springframework.data.document.mongodb.MongoTemplate.java

License:Apache License

protected Object insertDBObject(String collectionName, final DBObject dbDoc) {

    // DATADOC-95: This will prevent null objects from being saved.
    //if (dbDoc.keySet().isEmpty()) {
    //return null;
    //}/* w  w w. j a va 2  s  . c o  m*/

    //TODO: Need to move this to more central place
    if (dbDoc.containsField("_id")) {
        if (dbDoc.get("_id") instanceof String) {
            ObjectId oid = convertIdValue(this.mongoConverter, dbDoc.get("_id"));
            if (oid != null) {
                dbDoc.put("_id", oid);
            }
        }
    }
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug(
                "insert DBObject containing fields: " + dbDoc.keySet() + " in collection: " + collectionName);
    }
    return execute(collectionName, new CollectionCallback<Object>() {
        public Object doInCollection(DBCollection collection) throws MongoException, DataAccessException {
            if (writeConcern == null) {
                collection.insert(dbDoc);
            } else {
                collection.insert(dbDoc, writeConcern);
            }
            return dbDoc.get(ID);
        }
    });
}

From source file:org.springframework.data.document.mongodb.MongoTemplate.java

License:Apache License

protected Object saveDBObject(String collectionName, final DBObject dbDoc) {

    if (dbDoc.keySet().isEmpty()) {
        return null;
    }//w ww. j ava 2  s.  c om

    //TODO: Need to move this to more central place
    if (dbDoc.containsField("_id")) {
        if (dbDoc.get("_id") instanceof String) {
            ObjectId oid = convertIdValue(this.mongoConverter, dbDoc.get("_id"));
            if (oid != null) {
                dbDoc.put("_id", oid);
            }
        }
    }
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("save DBObject containing fields: " + dbDoc.keySet());
    }
    return execute(collectionName, new CollectionCallback<Object>() {
        public Object doInCollection(DBCollection collection) throws MongoException, DataAccessException {
            if (writeConcern == null) {
                collection.save(dbDoc);
            } else {
                collection.save(dbDoc, writeConcern);
            }
            return dbDoc.get(ID);
        }
    });
}

From source file:org.springframework.data.document.mongodb.MongoTemplate.java

License:Apache License

protected WriteResult doUpdate(final String collectionName, final Query query, final Update update,
        final Class<?> entityClass, final boolean upsert, final boolean multi) {

    return execute(collectionName, new CollectionCallback<WriteResult>() {
        public WriteResult doInCollection(DBCollection collection) throws MongoException, DataAccessException {
            DBObject queryObj = query.getQueryObject();
            DBObject updateObj = update.getUpdateObject();

            String idProperty = "id";
            if (null != entityClass) {
                idProperty = getPersistentEntity(entityClass).getIdProperty().getName();
            }//  www.  ja  v  a2  s .  co m
            for (String key : queryObj.keySet()) {
                if (idProperty.equals(key)) {
                    // This is an ID field
                    queryObj.put(ID, mongoConverter.maybeConvertObject(queryObj.get(key)));
                    queryObj.removeField(key);
                } else {
                    queryObj.put(key, mongoConverter.maybeConvertObject(queryObj.get(key)));
                }
            }

            for (String key : updateObj.keySet()) {
                updateObj.put(key, mongoConverter.maybeConvertObject(updateObj.get(key)));
            }

            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("calling update using query: " + queryObj + " and update: " + updateObj
                        + " in collection: " + collectionName);
            }

            WriteResult wr;
            if (writeConcern == null) {
                if (multi) {
                    wr = collection.updateMulti(queryObj, updateObj);
                } else {
                    wr = collection.update(queryObj, updateObj);
                }
            } else {
                wr = collection.update(queryObj, updateObj, upsert, multi, writeConcern);
            }
            handleAnyWriteResultErrors(wr, queryObj, "update with '" + updateObj + "'");
            return wr;
        }
    });

}

From source file:org.springframework.data.document.mongodb.query.QueryMapper.java

License:Apache License

/**
 * Replaces the property keys used in the given {@link DBObject} with the appropriate keys by using the
 * {@link PersistentEntity} metadata./*  w  w  w .j a  v  a  2  s  .  co  m*/
 * 
 * @param query
 * @param entity
 * @return
 */
public DBObject getMappedObject(DBObject query, MongoPersistentEntity<?> entity) {
    String idKey = null;
    if (null != entity && entity.getIdProperty() != null) {
        idKey = entity.getIdProperty().getName();
    } else if (query.containsField("id")) {
        idKey = "id";
    } else if (query.containsField("_id")) {
        idKey = "_id";
    }

    DBObject newDbo = new BasicDBObject();
    for (String key : query.keySet()) {
        String newKey = key;
        Object value = query.get(key);
        if (key.equals(idKey)) {
            if (value instanceof DBObject) {
                if ("$in".equals(key)) {
                    List<Object> ids = new ArrayList<Object>();
                    for (Object id : (Object[]) ((DBObject) value).get("$in")) {
                        if (null != converter && !(id instanceof ObjectId)) {
                            ObjectId oid = converter.convertObjectId(id);
                            ids.add(oid);
                        } else {
                            ids.add(id);
                        }
                    }
                    newDbo.put("$in", ids.toArray(new ObjectId[ids.size()]));
                }
            } else if (null != converter) {
                try {
                    value = converter.convertObjectId(value);
                } catch (ConversionFailedException ignored) {
                }
            }
            newKey = "_id";
        } else {
            // TODO: Implement other forms of conversion (like @Alias and whatnot)
        }
        newDbo.put(newKey, value);
    }
    return newDbo;
}

From source file:org.springframework.data.document.mongodb.SimpleMongoConverter.java

License:Apache License

/**
 * Reads every key/value pair from the {@link DBObject} into a {@link Map} instance.
 * /*from w w w . j  a  va2 s .  c o m*/
 * @param pd
 * @param dbo
 * @param targetType
 * @return
 */
protected Map<?, ?> readMap(MongoPropertyDescriptors.MongoPropertyDescriptor pd, DBObject dbo,
        Class<?> targetType) {
    Map<String, Object> map = createMap();
    for (String key : dbo.keySet()) {
        Object value = dbo.get(key);
        if (!isSimpleType(value.getClass())) {
            map.put(key, read(targetType, (DBObject) value));
            // Can do some reflection tricks here -
            // throw new RuntimeException("User types not supported yet as values for Maps");
        } else {
            map.put(key, conversionService.convert(value, targetType));
        }
    }
    return map;
}

From source file:org.springframework.data.mongodb.core.aggregation.ConditionalOperator.java

License:Apache License

private List<Object> getClauses(AggregationOperationContext context, DBObject mappedObject) {

    List<Object> clauses = new ArrayList<Object>();

    for (String key : mappedObject.keySet()) {

        Object predicate = mappedObject.get(key);
        clauses.addAll(getClauses(context, key, predicate));
    }//from   ww w . jav  a2  s  .  c o m

    return clauses;
}