List of usage examples for com.mongodb BasicDBObject get
public Object get(final String key)
From source file:com.redhat.thermostat.gateway.common.mongodb.MongoStorageHandler.java
License:Open Source License
public void updateOneSystemObject(MongoCollection<Document> collection, final String systemId, String queries, String body) {/* w ww. jav a2s . c o m*/ Bson sysQuery = buildEq(ThermostatFields.SYSTEM_ID, systemId); Bson query = buildAnd(sysQuery, MongoRequestFilters.buildQueriesFilter(queries)); BasicDBObject inputObject = (BasicDBObject) JSON.parse(body); BasicDBObject setObject = (BasicDBObject) inputObject.get(SET_FIELD_NAME); if (setObject.containsField(ThermostatFields.SYSTEM_ID)) { throw new UnsupportedOperationException( "Updating " + ThermostatFields.SYSTEM_ID + " field is not allowed"); } final Bson fields = new Document("$set", setObject); collection.updateMany(query, fields); }
From source file:com.redhat.thermostat.gateway.common.mongodb.MongoStorageHandler.java
License:Open Source License
public void updateOneJvmObject(MongoCollection<Document> collection, final String systemId, final String jvmId, String queries, String body) { Bson sysQuery = buildEq(ThermostatFields.SYSTEM_ID, systemId); Bson jvmQuery = buildEq(ThermostatFields.JVM_ID, jvmId); Bson query = buildAnd(buildAnd(sysQuery, jvmQuery), MongoRequestFilters.buildQueriesFilter(queries)); BasicDBObject inputObject = (BasicDBObject) JSON.parse(body); BasicDBObject setObject = (BasicDBObject) inputObject.get(SET_FIELD_NAME); if (setObject.containsField(ThermostatFields.SYSTEM_ID)) { throw new UnsupportedOperationException( "Updating " + ThermostatFields.SYSTEM_ID + " field is not allowed"); }/*ww w . ja v a 2 s.c o m*/ if (setObject.containsField(ThermostatFields.JVM_ID)) { throw new UnsupportedOperationException( "Updating " + ThermostatFields.JVM_ID + " field is not allowed"); } final Bson fields = new Document("$set", setObject); collection.updateMany(query, fields); }
From source file:com.seyren.mongo.MongoMapper.java
License:Apache License
@SuppressWarnings({ "unchecked", "rawtypes" }) private Map propertiesToMap(Check check) { Map map = new HashMap(); map.put("_id", check.getId()); map.put("name", check.getName()); map.put("description", check.getDescription()); map.put("target", check.getTarget()); map.put("from", check.getFrom()); map.put("until", check.getUntil()); if (check.getWarn() != null) { map.put("warn", check.getWarn().toPlainString()); }//ww w .java 2 s . co m if (check.getError() != null) { map.put("error", check.getError().toPlainString()); } map.put("enabled", check.isEnabled()); map.put("live", check.isLive()); map.put("allowNoData", check.isAllowNoData()); map.put("state", check.getState().toString()); if (check.getLastCheck() != null) { map.put("lastCheck", new Date(check.getLastCheck().getMillis())); } if (check.getSubscriptions() != null && !check.getSubscriptions().isEmpty()) { final ArrayList<DBObject> dbSubscriptions = new ArrayList<DBObject>(); for (Subscription s : check.getSubscriptions()) { final BasicDBObject dbObject = new BasicDBObject(propertiesToMap(s)); if (dbObject.get("_id") == null) { dbObject.put("_id", new ObjectId().toHexString()); } dbSubscriptions.add(dbObject); } map.put("subscriptions", dbSubscriptions); } return map; }
From source file:com.simonschlueter.gantic.ObjectParser.java
License:MIT License
public static DBObject parseObject(Object object, boolean ignoreNull, String... fields) { BasicDBObject data = new BasicDBObject(); for (Field field : object.getClass().getDeclaredFields()) { MongoSync sync = field.getAnnotation(MongoSync.class); if (sync != null) { if (!field.isAccessible()) { field.setAccessible(true); }/*from w w w.j a v a 2 s. co m*/ String f = field.getName(); String parent = null; if (!sync.field().isEmpty()) { f = sync.field(); if (f.contains(".")) { String[] path = f.split("\\."); f = path[1]; parent = path[0]; } } if (fields != null && fields.length > 0) { if (!arrayContains(fields, f)) { continue; } } else if (!sync.save()) { continue; } Object value = null; try { value = field.get(object); } catch (IllegalArgumentException | IllegalAccessException ex) { Logger.getLogger(ObjectParser.class.getName()).log(Level.SEVERE, null, ex); } if (value != null && field.getType().getAnnotation(MongoObject.class) != null) { value = parseObject(value, ignoreNull); } if (ignoreNull && !sync.insertNull()) { if (value == null) { continue; } } if (value != null) { if (value instanceof List) { value = new ArrayList(((List) value)); } else if (value instanceof HashMap) { BasicDBObject newValue = new BasicDBObject(); HashMap<Object, Object> map = (HashMap) value; for (Map.Entry<Object, Object> set : map.entrySet()) { newValue.put(set.getKey().toString(), set.getValue()); } value = newValue; } else if (value.getClass().isEnum()) { value = value.toString(); } } if (parent != null) { if (!data.containsField(parent)) { data.put(parent, new BasicDBObject()); } ((BasicDBObject) data.get(parent)).put(f, value); } else { data.put(f, value); } } } return data; }
From source file:com.simonschlueter.gantic.ObjectParser.java
License:MIT License
public static <T> T parseDbObject(Class<T> objectClass, DBObject data) { try {// www .ja v a 2 s. c om T instance = objectClass.newInstance(); for (Field field : objectClass.getDeclaredFields()) { MongoSync sync = field.getAnnotation(MongoSync.class); if (sync != null) { String fieldName = field.getName(); String children = null; Object value = null; boolean hasData = false; if (!sync.field().isEmpty()) { fieldName = sync.field(); if (fieldName.contains(".")) { String[] path = fieldName.split("\\."); fieldName = path[0]; children = path[1]; } } if (data.containsField(fieldName)) { hasData = true; value = data.get(fieldName); } if (children != null && hasData && value != null) { BasicDBObject bdbo = (BasicDBObject) value; if (bdbo.containsField(children)) { value = bdbo.get(children); } else { hasData = false; value = null; } } if (hasData) { if (!field.isAccessible()) { field.setAccessible(true); } if (value != null) { if (field.getType().isAssignableFrom(int.class)) { value = ((Number) value).intValue(); } else if (field.getType().isAssignableFrom(double.class)) { value = ((Number) value).doubleValue(); } else if (field.getType().isAssignableFrom(float.class)) { value = ((Number) value).floatValue(); } else if (field.getType().isAssignableFrom(long.class)) { value = ((Number) value).longValue(); } else if (field.getType().isAssignableFrom(short.class)) { value = ((Number) value).shortValue(); } else if (field.getType().isEnum()) { value = field.getType().getMethod("valueOf", String.class).invoke(null, value); } else if (List.class.isAssignableFrom(field.getType())) { value = field.getType().getConstructor(List.class).newInstance(value); } else if (field.getType().getAnnotation(MongoObject.class) != null) { value = parseDbObject(field.getType(), (DBObject) value); } else if (field.getType().equals(HashMap.class)) { value = new HashMap<>((BasicDBObject) value); } } field.set(instance, value); } } } return instance; } catch (InstantiationException | IllegalAccessException | NoSuchMethodException | SecurityException | IllegalArgumentException | InvocationTargetException ex) { Logger.getLogger(ObjectParser.class.getName()).log(Level.SEVERE, null, ex); } return null; }
From source file:com.softinstigate.restheart.db.DAOUtils.java
License:Open Source License
/** * @param row a DBObject row//from w ww . j a v a2 s . com * @param fieldsToFilter list of field names to filter * @return */ private static Object getElement(Object element) { if (element == null) { return null; } if (element instanceof BasicDBList) { ArrayList<Object> ret = new ArrayList<>(); BasicDBList dblist = (BasicDBList) element; dblist.stream().forEach((subel) -> { ret.add(getElement(subel)); }); return ret; } else if (element instanceof BasicDBObject) { TreeMap<String, Object> ret = new TreeMap<>(); BasicDBObject el = (BasicDBObject) element; el.keySet().stream().forEach((key) -> { ret.put(key, el.get(key)); }); return ret; } else { return element; } }
From source file:com.sonyericsson.jenkins.plugins.bfa.db.MongoDBKnowledgeBase.java
License:Open Source License
@Override public List<FailureCauseTimeInterval> getFailureCausesPerTime(int intervalSize, GraphFilterBuilder filter, boolean byCategories) { List<FailureCauseTimeInterval> failureCauseIntervals = new ArrayList<FailureCauseTimeInterval>(); Map<MultiKey, FailureCauseTimeInterval> categoryTable = new HashMap<MultiKey, FailureCauseTimeInterval>(); DBObject matchFields = generateMatchFields(filter); DBObject match = new BasicDBObject("$match", matchFields); DBObject unwind = new BasicDBObject("$unwind", "$failureCauses"); DBObject idFields = generateTimeGrouping(intervalSize); idFields.put("failureCause", "$failureCauses.failureCause"); DBObject groupFields = new BasicDBObject(); groupFields.put("_id", idFields); groupFields.put("number", new BasicDBObject("$sum", 1)); DBObject group = new BasicDBObject("$group", groupFields); AggregationOutput output;//from w w w .j a v a 2 s. c om try { output = getStatisticsCollection().aggregate(match, unwind, group); for (DBObject result : output.results()) { int number = (Integer) result.get("number"); TimePeriod period = generateTimePeriodFromResult(result, intervalSize); BasicDBObject groupedAttrs = (BasicDBObject) result.get("_id"); DBRef failureRef = (DBRef) groupedAttrs.get("failureCause"); String id = failureRef.getId().toString(); FailureCause failureCause = getCause(id); if (byCategories) { if (failureCause.getCategories() != null) { for (String category : failureCause.getCategories()) { MultiKey multiKey = new MultiKey(category, period); FailureCauseTimeInterval interval = categoryTable.get(multiKey); if (interval == null) { interval = new FailureCauseTimeInterval(period, category, number); categoryTable.put(multiKey, interval); failureCauseIntervals.add(interval); } else { interval.addNumber(number); } } } } else { FailureCauseTimeInterval timeInterval = new FailureCauseTimeInterval(period, failureCause.getName(), failureCause.getId(), number); failureCauseIntervals.add(timeInterval); } } } catch (UnknownHostException e) { logger.fine("Unable to get failure causes by time"); e.printStackTrace(); } catch (AuthenticationException e) { logger.fine("Unable to get failure causes by time"); e.printStackTrace(); } return failureCauseIntervals; }
From source file:com.stratio.deep.mongodb.extractor.MongoNativeExtractor.java
License:Apache License
/** * Calculate splits./*from w ww .j a v a2 s.com*/ * * @param collection the collection * @return the deep partition [ ] */ private DeepPartition[] calculateSplits(DBCollection collection) { BasicDBList splitData = getSplitData(collection); List<ServerAddress> serverAddressList = collection.getDB().getMongo().getServerAddressList(); if (splitData == null) { Pair<BasicDBList, List<ServerAddress>> pair = getSplitDataCollectionShardEnviroment( getShards(collection), collection.getDB().getName(), collection.getName()); splitData = pair.left; serverAddressList = pair.right; } Object lastKey = null; // Lower boundary of the first min split List<String> stringHosts = new ArrayList<>(); for (ServerAddress serverAddress : serverAddressList) { stringHosts.add(serverAddress.toString()); } int i = 0; MongoPartition[] partitions = new MongoPartition[splitData.size() + 1]; for (Object aSplitData : splitData) { BasicDBObject currentKey = (BasicDBObject) aSplitData; Object currentO = currentKey.get(MONGO_DEFAULT_ID); partitions[i] = new MongoPartition(mongoDeepJobConfig.getRddId(), i, new DeepTokenRange(lastKey, currentO, stringHosts), MONGO_DEFAULT_ID); lastKey = currentO; i++; } QueryBuilder queryBuilder = QueryBuilder.start(MONGO_DEFAULT_ID); queryBuilder.greaterThanEquals(lastKey); partitions[i] = new MongoPartition(0, i, new DeepTokenRange(lastKey, null, stringHosts), MONGO_DEFAULT_ID); return partitions; }
From source file:com.stratio.qa.assertions.DBObjectsAssert.java
License:Apache License
private boolean isContained(List<DBObject> item, BasicDBObject doc) { boolean res = false; for (int i = 0; i < item.size() && !res; i++) { DBObject aux = item.get(i);/*w ww . j a v a 2s . c o m*/ aux.removeField("_id"); aux.removeField("timestamp"); if (aux.keySet().equals(doc.keySet())) { res = true; } // Obtenemos los columnNames List<String> cols = new ArrayList<String>(doc.keySet()); for (int x = 0; x < cols.size() && res; x++) { if (!aux.get(cols.get(x)).equals(doc.get(cols.get(x)))) { res = false; } else { res = true; } } } return res; }
From source file:com.streamreduce.core.dao.InventoryItemDAO.java
License:Apache License
/** * Returns the inventory items for the given connection id. * * @param connectionId the id of the connection whose inventory items we're interested in * @return the list of inventory items or an empty list if there are none * @throws IllegalArgumentException if connectionId is null *///w ww .j a v a 2 s .c om public List<InventoryItem> getInventoryItems(ObjectId connectionId) { Preconditions.checkNotNull(connectionId, "connectionId cannot be null."); DBCollection collection = getDatastore().getDB().getCollection("inventoryItems"); BasicDBObject query = new BasicDBObject(); DBCursor cursor; query.put("connection.$id", connectionId); cursor = collection.find(query); List<InventoryItem> inventoryItems = new ArrayList<>(); try { while (cursor.hasNext()) { BasicDBObject rawInventoryItem = (BasicDBObject) cursor.next(); inventoryItems.add(get((ObjectId) rawInventoryItem.get("_id"))); } } finally { cursor.close(); } return inventoryItems; }