List of usage examples for com.mongodb DBObject toMap
Map toMap();
From source file:org.fastmongo.odm.dbobject.mapping.core.DbObjectToDomainConverter.java
License:Apache License
/** * Fills collection of elements with the given type using provided mongo values. * * @param collection the collection of elements. * @param dbList the list of mongo values. * @param elementType the type of elements in the result collection. * @param context the context for this operation, bounded to the root document. *//*from w ww.j av a 2s . c o m*/ private void fillCollection(Collection<Object> collection, List<Object> dbList, Class<?> elementType, Context context) { // try to bulk load the whole collection instead of loading inside a loop if (tryLoadAndFillEntireCollection(collection, dbList, elementType, context)) { // if we successfully loaded and converted collection then return return; } // otherwise convert each element in the loop for (Object dbObject : dbList) { if (dbObject instanceof DBObject) { DBObject db = (DBObject) dbObject; String className = classNameResolver.getClassName(elementType, db, classPrefix); if (className != null) { String link = (String) db.get(LINK_KEY); if (link != null) { final Object id = db.get(ID_KEY); final Class<?> clazz = loadClass(className); collection.add(loadObject(id, clazz, context)); } else { Object element = newInstance(className); fillObject(element, db, context); collection.add(element); } } else { collection.add(db.toMap()); } } else { collection.add(toSimpleType(elementType, dbObject)); } } }
From source file:org.forgerock.openidm.repo.mongodb.impl.MongoDBRepoService.java
License:Open Source License
/** * Gets an object from the repository by identifier. The returned object is not validated * against the current schema and may need processing to conform to an updated schema. * <p>// w w w .ja v a 2 s . c o m * * @param fullId the identifier of the object to retrieve from the object set. * @throws NotFoundException if the specified object could not be found. * @throws ForbiddenException if access to the object is forbidden. * @throws BadRequestException if the passed identifier is invalid * @return the requested object. */ @Override public Map<String, Object> read(String fullId) throws ObjectSetException { String localId = getLocalId(fullId); String type = getObjectType(fullId, false); if (fullId == null || localId == null) { throw new NotFoundException("The repository requires clients to supply an identifier " + "for the object to create. Full identifier: " + fullId + " local identifier: " + localId); } else if (type == null) { throw new NotFoundException("The object identifier did not include " + "sufficient information to determine the object type: " + fullId); } Map<String, Object> result = null; DBCollection collection = getCollection(type); DBObject doc = predefinedQueries.getByID(localId, collection); if (doc == null) { throw new NotFoundException("Object " + fullId + " not found in " + type); } doc = DocumentUtil.normalizeForRead(doc); result = doc.toMap(); logger.trace("Completed get for id: {} result: {}", fullId, result); return result; }
From source file:org.forgerock.openidm.repo.mongodb.impl.MongoDBRepoService.java
License:Open Source License
/** * Performs the query on the specified object and returns the associated results. * <p>// w w w . j a va 2 s . co m * Queries are parametric; a set of named parameters is provided as the query criteria. * The query result is a JSON object structure composed of basic Java types. * * The returned map is structured as follow: * - The top level map contains meta-data about the query, plus an entry with the actual result records. * - The <code>QueryConstants</code> defines the map keys, including the result records (QUERY_RESULT) * * @param fullId identifies the object to query. * @param params the parameters of the query to perform. * @return the query results, which includes meta-data and the result records in JSON object structure format. * @throws NotFoundException if the specified object could not be found. * @throws BadRequestException if the specified params contain invalid arguments, e.g. a query id that is not * configured, a query expression that is invalid, or missing query substitution tokens. * @throws ForbiddenException if access to the object or specified query is forbidden. */ @Override public Map<String, Object> query(String fullId, Map<String, Object> params) throws ObjectSetException { String type = getObjectType(fullId, true); logger.trace("Full id: {} Extracted type: {}", fullId, type); Map<String, Object> result = new HashMap<String, Object>(); DBCollection collection = getCollection(type); List<Map<String, Object>> docs = new ArrayList<Map<String, Object>>(); result.put(QueryConstants.QUERY_RESULT, docs); long start = System.currentTimeMillis(); List<DBObject> queryResult = queries.query(params, collection); long end = System.currentTimeMillis(); if (queryResult != null) { long convStart = System.currentTimeMillis(); for (DBObject entry : queryResult) { entry = DocumentUtil.normalizeForRead(entry); Map<String, Object> convertedEntry = entry.toMap(); docs.add(convertedEntry); } long convEnd = System.currentTimeMillis(); result.put(QueryConstants.STATISTICS_CONVERSION_TIME, Long.valueOf(convEnd - convStart)); } result.put(QueryConstants.STATISTICS_QUERY_TIME, Long.valueOf(end - start)); if (logger.isDebugEnabled()) { logger.debug("Query result contains {} records, took {} ms and took {} ms to convert result.", new Object[] { ((List) result.get(QueryConstants.QUERY_RESULT)).size(), result.get(QueryConstants.STATISTICS_QUERY_TIME), result.get(QueryConstants.STATISTICS_CONVERSION_TIME) }); logger.debug("Query result: {}", result); } return result; }
From source file:org.grails.datastore.mapping.mongo.MongoDatastore.java
License:Apache License
/** * Indexes any properties that are mapped with index:true * @param entity The entity//from w w w . j a v a2s . c o m * @param template The template */ protected void initializeIndices(final PersistentEntity entity, final MongoTemplate template) { template.execute(new DbCallback<Object>() { @SuppressWarnings({ "unchecked", "rawtypes" }) public Object doInDB(DB db) throws MongoException, DataAccessException { final DBCollection collection = db.getCollection(getCollectionName(entity)); final ClassMapping<MongoCollection> classMapping = entity.getMapping(); if (classMapping != null) { final MongoCollection mappedForm = classMapping.getMappedForm(); if (mappedForm != null) { for (Map compoundIndex : mappedForm.getCompoundIndices()) { DBObject indexDef = new BasicDBObject(compoundIndex); collection.ensureIndex(indexDef); } } } for (PersistentProperty<MongoAttribute> property : entity.getPersistentProperties()) { final boolean indexed = isIndexed(property); if (indexed) { final MongoAttribute mongoAttributeMapping = property.getMapping().getMappedForm(); DBObject dbObject = new BasicDBObject(); final String fieldName = getMongoFieldNameForProperty(property); dbObject.put(fieldName, 1); DBObject options = new BasicDBObject(); if (mongoAttributeMapping != null) { Map attributes = mongoAttributeMapping.getIndexAttributes(); if (attributes != null) { attributes = new HashMap(attributes); if (attributes.containsKey(MongoAttribute.INDEX_TYPE)) { dbObject.put(fieldName, attributes.remove(MongoAttribute.INDEX_TYPE)); } options.putAll(attributes); } } if (options.toMap().isEmpty()) { collection.ensureIndex(dbObject); } else { collection.ensureIndex(dbObject, options); } } } return null; } String getMongoFieldNameForProperty(PersistentProperty<MongoAttribute> property) { PropertyMapping<MongoAttribute> pm = property.getMapping(); String propKey = null; if (pm.getMappedForm() != null) { propKey = pm.getMappedForm().getField(); } if (propKey == null) { propKey = property.getName(); } return propKey; } }); }
From source file:org.graylog2.alarmcallbacks.AlarmCallbackConfigurationServiceImpl.java
License:Open Source License
@Override public List<AlarmCallbackConfiguration> getForStreamId(String streamId) { final List<AlarmCallbackConfiguration> alarmCallbackConfigurations = Lists.newArrayList(); final List<DBObject> respConfigurations = query(AlarmCallbackConfigurationImpl.class, new BasicDBObject("stream_id", streamId)); for (DBObject configuration : respConfigurations) { alarmCallbackConfigurations.add( new AlarmCallbackConfigurationImpl((ObjectId) configuration.get("_id"), configuration.toMap())); }/*www . j a va 2 s. c o m*/ return alarmCallbackConfigurations; }
From source file:org.graylog2.alarmcallbacks.AlarmCallbackConfigurationServiceImpl.java
License:Open Source License
@Override public AlarmCallbackConfiguration load(String alarmCallbackId) { DBObject rawModel = get(AlarmCallbackConfigurationImpl.class, alarmCallbackId); return (rawModel == null ? null : new AlarmCallbackConfigurationImpl((ObjectId) (rawModel.get("_id")), rawModel.toMap())); }
From source file:org.graylog2.alerts.AlertServiceImpl.java
License:Open Source License
@Override public List<Alert> loadRecentOfStream(String streamId, DateTime since) { QueryBuilder qb = QueryBuilder.start("stream_id").is(streamId); if (since != null) { qb.and("triggered_at").greaterThanEquals(since.toDate()); }/*from w w w . jav a 2 s.co m*/ BasicDBObject sort = new BasicDBObject("triggered_at", -1); final List<DBObject> alertObjects = query(AlertImpl.class, qb.get(), sort, AlertImpl.MAX_LIST_COUNT, 0); List<Alert> alerts = Lists.newArrayList(); for (DBObject alertObj : alertObjects) { alerts.add(new AlertImpl(new ObjectId(alertObj.get("_id").toString()), alertObj.toMap())); } return alerts; }
From source file:org.graylog2.cluster.NodeServiceImpl.java
License:Open Source License
@Override public Node byNodeId(String nodeId) throws NodeNotFoundException { DBObject query = new BasicDBObject("node_id", nodeId); DBObject o = findOne(NodeImpl.class, query); if (o == null || !o.containsField("node_id")) { throw new NodeNotFoundException("Unable to find node " + nodeId); }/*from ww w . j av a 2s . co m*/ return new NodeImpl((ObjectId) o.get("_id"), o.toMap()); }
From source file:org.graylog2.cluster.NodeServiceImpl.java
License:Open Source License
@Override public Map<String, Node> allActive(Node.Type type) { Map<String, Node> nodes = Maps.newHashMap(); BasicDBObject query = new BasicDBObject(); query.put("last_seen", new BasicDBObject("$gte", Tools.getUTCTimestamp() - pingTimeout)); query.put("type", type.toString()); for (DBObject obj : query(NodeImpl.class, query)) { Node node = new NodeImpl((ObjectId) obj.get("_id"), obj.toMap()); String nodeId = (String) obj.get("node_id"); nodes.put(nodeId, node);/*from w w w.j a v a 2 s . co m*/ } return nodes; }
From source file:org.graylog2.dashboards.DashboardServiceImpl.java
License:Open Source License
@Override public List<Dashboard> all() { List<Dashboard> dashboards = Lists.newArrayList(); List<DBObject> results = query(DashboardImpl.class, new BasicDBObject()); for (DBObject o : results) { Map<String, Object> fields = o.toMap(); Dashboard dashboard = new DashboardImpl((ObjectId) o.get("_id"), fields); // Add all widgets of this dashboard. if (fields.containsKey(DashboardImpl.EMBEDDED_WIDGETS)) { for (BasicDBObject widgetFields : (List<BasicDBObject>) fields .get(DashboardImpl.EMBEDDED_WIDGETS)) { DashboardWidget widget = null; try { widget = DashboardWidget.fromPersisted(metricRegistry, searches, widgetFields); } catch (DashboardWidget.NoSuchWidgetTypeException e) { LOG.error("No such widget type: [" + widgetFields.get("type") + "] - Dashboard: [" + dashboard.getId() + "]", e); continue; } catch (InvalidRangeParametersException e) { LOG.error("Invalid range parameters of widget in dashboard: [" + dashboard.getId() + "]", e);//from ww w. ja v a 2 s .c om continue; } catch (InvalidWidgetConfigurationException e) { LOG.error("Invalid configuration of widget in dashboard: [" + dashboard.getId() + "]", e); continue; } dashboard.addPersistedWidget(widget); } } dashboards.add(dashboard); } return dashboards; }