List of usage examples for com.mongodb BasicDBObject containsField
public boolean containsField(final String field)
From source file:com.mongodash.dao.mapper.SettingsDBObjectMapper.java
@Override public Settings mapDBObject(BasicDBObject object) { Settings settings = null;//ww w .j a va 2 s . c o m String _id = object.getString(Config.COMMON_FIELDS._id.name()); if (SETTINGS_KEY.email.name().equals(_id)) { settings = new EmailSettings(); if (object != null) { ((EmailSettings) settings).setEnabled(object.getBoolean("enabled")); ((EmailSettings) settings).setServer(object.getString("server")); ((EmailSettings) settings).setPort(object.getString("port")); ((EmailSettings) settings).setSender(object.getString("sender")); if (object.containsField("username") && object.containsField("password")) { ((EmailSettings) settings).setUsername(object.getString("username")); ((EmailSettings) settings).setPassword(PasswordUtil.decrypt(object.getString("password"))); } ((EmailSettings) settings).setSsl(object.getBoolean("ssl")); } } else if (SETTINGS_KEY.ldap.name().equals(_id)) { settings = new LdapSettings(); if (object != null) { ((LdapSettings) settings).setEnabled(object.getBoolean("enabled")); ((LdapSettings) settings).setHost(object.getString("host")); ((LdapSettings) settings).setPort(object.getString("port")); ((LdapSettings) settings).setAdminDn(object.getString("adminDn")); ((LdapSettings) settings).setAdminPassword(object.getString("adminPassword")); ((LdapSettings) settings).setBaseDn(object.getString("baseDn")); ((LdapSettings) settings).setLoginAttribute(object.getString("loginAttr")); ((LdapSettings) settings).setSecure(object.getBoolean("secure")); } } else if (SETTINGS_KEY.alerts.name().equals(_id)) { settings = new AlertSettings(); if (object != null) { ((AlertSettings) settings).setEnabled(object.getBoolean("enabled")); ((AlertSettings) settings).setEmailSubject(object.getString("emailSubject")); ((AlertSettings) settings).setEmailRecipients(object.getString("emailRecipients")); } } else if (SETTINGS_KEY.notifications.name().equals(_id)) { settings = new NotificationSettings(); if (object != null) { ((NotificationSettings) settings).setEnabled(object.getBoolean("enabled")); ((NotificationSettings) settings).setEmailEnabled(object.getBoolean("emailEnabled")); ((NotificationSettings) settings).setEmailSubject(object.getString("emailSubject")); ((NotificationSettings) settings).setEmailRecipients(object.getString("emailRecipients")); if (object.containsField("enabledNotifications")) { BasicDBList list = (BasicDBList) object.get("enabledNotifications"); List<String> enabledNotifications = new ArrayList<String>(); for (int i = 0; i < list.size(); i++) { enabledNotifications.add((String) list.get(i)); } ((NotificationSettings) settings).setEnabledNotifications(enabledNotifications); } } } else if (SETTINGS_KEY.licenseKey.name().equals(_id)) { settings = new LicenseKeySettings(); if (object != null) { ((LicenseKeySettings) settings).setPrivateKey(object.getString("privateKey")); ((LicenseKeySettings) settings).setPublicKey(object.getString("publicKey")); } } return settings; }
From source file:com.redhat.lightblue.mongo.crud.MongoCRUDController.java
License:Open Source License
private boolean isIdIndex(DBObject index) { BasicDBObject keys = (BasicDBObject) index.get("key"); return (keys != null && keys.size() == 1 && keys.containsField("_id")); }
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) {//from w w w . j av a2 s . 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 a2s. com*/ 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.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); }/* w w w. j av a 2 s .c o 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 {//from w ww .ja va 2 s.co m 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.streamreduce.core.service.EventServiceImpl.java
License:Apache License
/** * Helper method that returns all metadata for a {@link InventoryItem}. * * @param inventoryItem the cloud inventory item to retrieve metadata for/about * @return the metadata//from ww w .ja v a 2 s .co m */ private Map<String, Object> getMetadataFromInventoryItem(InventoryItem inventoryItem) { // NOTE: We're not using CloudService methods here for performance reasons Map<String, Object> civMetadata = new HashMap<>(); // Right now, we are only creating extended metadata for AWS EC2 instance items if (inventoryItem.getConnection().getProviderId().equals(ProviderIdConstants.AWS_PROVIDER_ID) && inventoryItem.getType().equals(Constants.COMPUTE_INSTANCE_TYPE)) { DBObject cMetadata = genericCollectionDAO.getById(DAODatasourceType.BUSINESS, Constants.INVENTORY_ITEM_METADATA_COLLECTION_NAME, inventoryItem.getMetadataId()); if (cMetadata == null) { // Fill in the metadata based on the last event for this target Event previousEvent = getLastEventForTarget(inventoryItem.getId()); if (previousEvent != null) { Map<String, Object> peMetadata = previousEvent.getMetadata(); if (peMetadata != null) { civMetadata.put("targetIP", peMetadata.get("targetIP")); civMetadata.put("targetOS", peMetadata.get("targetOS")); civMetadata.put("targetISO3166Code", peMetadata.get("targetISO3166Code")); civMetadata.put("targetRegion", peMetadata.get("targetRegion")); civMetadata.put("targetZone", peMetadata.get("targetZone")); } } } else { // Fill in the metadata from the available node metadata // Get the IP address if (cMetadata.containsField("publicAddresses")) { BasicDBList publicAddresses = (BasicDBList) cMetadata.get("publicAddresses"); // TODO: How do we want to handle multiple IP addresses? if (publicAddresses.size() > 0) { civMetadata.put("targetIP", publicAddresses.get(0)); } } // Get location information (ISO 3166 code, region and availability zone) if (cMetadata.containsField("location") && cMetadata.get("location") != null) { BasicDBObject location = (BasicDBObject) cMetadata.get("location"); boolean regionProcessed = false; boolean zoneProcessed = false; while (location != null) { if (regionProcessed && zoneProcessed) { break; } String locationScope = location.containsField("scope") ? location.getString("scope") : null; if (locationScope != null) { LocationScope scope = LocationScope.valueOf(locationScope); switch (scope) { case REGION: civMetadata.put("targetRegion", location.get("id")); regionProcessed = true; break; case ZONE: BasicDBList iso3166Codes = (BasicDBList) location.get("iso3166Codes"); civMetadata.put("targetISO3166Code", iso3166Codes.get(0)); civMetadata.put("targetZone", location.get("id")); zoneProcessed = true; break; } } location = location.containsField("parent") && location.get("parent") != null ? (BasicDBObject) location.get("parent") : null; } } // Get OS name if (cMetadata.containsField("operatingSystem")) { BasicDBObject operatingSystem = (BasicDBObject) cMetadata.get("operatingSystem"); if (operatingSystem != null) { if (operatingSystem.containsField("family")) { civMetadata.put("targetOS", operatingSystem.get("family")); } } } } } return civMetadata; }
From source file:com.streamreduce.rest.resource.api.AbstractOwnableResource.java
License:Apache License
protected InventoryItemResponseDTO toFullDTO(InventoryItem inventoryItem) { InventoryItemResponseDTO dto = new InventoryItemResponseDTO(); Connection connection = inventoryItem.getConnection(); BasicDBObject payload = applicationManager.getInventoryService().getInventoryItemPayload(inventoryItem); super.toBaseDTO(inventoryItem, dto); dto.setOwner(inventoryItem.getUser().getId().equals(securityService.getCurrentUser().getId())); dto.setConnectionAlias(connection.getAlias()); dto.setConnectionId(connection.getId()); dto.setConnectionType(connection.getType()); dto.setConnectionProviderId(connection.getProviderId()); dto.setExternalId(inventoryItem.getExternalId()); dto.setType(inventoryItem.getType()); // Prune any sensitive information from the payload if (!dto.isOwner()) { if (payload.containsField("adminPassword")) { payload.removeField("adminPassword"); }/* www . j a va2s . co m*/ if (payload.containsField("credentials")) { payload.removeField("credentials"); } } dto.setPayload(payload); return dto; }
From source file:com.streamreduce.storm.spouts.EventSpout.java
License:Apache License
/** * {@inheritDoc}//ww w . ja v a 2 s .c o m */ @Override public void handleDBEntry(SpoutOutputCollector collector, BasicDBObject entry) { BasicDBObject metadata = entry.containsField("metadata") ? (BasicDBObject) entry.get("metadata") : new BasicDBObject(); String eventType = metadata.getString("targetType"); // Just in case if (eventType == null) { // TODO: Figure out the best way to handle this // Log the inability to process further logger.error("Event with id of " + entry.get("_id") + " has no target type. Unable to process."); // Early return to avoid emitting the event return; } String v = (String) metadata.get("targetVisibility"); if (v != null) { Visibility visibility = Visibility.valueOf(v); if (visibility == Visibility.SELF) { // do not process private information return; } } MongoClient.mapMongoToPlainJavaTypes(entry); // Emit the entry to the type-specific stream collector.emit(eventType, new Values(entry.toMap())); ack(entry); }
From source file:fr.cnes.sitools.dataset.database.mongodb.RequestMongoDB.java
License:Open Source License
@Override public String getFilterClause(List<Predicat> predicats, List<Column> columns) { BasicDBObject whereClause = new BasicDBObject(); // loop over the predicats // boolean first = true; // String result = "{"; ///* w w w . ja va 2 s. c om*/ // Map<String, List<Predicat>> orderedPredicats = orderPredicat(predicats); // for (Predicat predicat : predicats) { // // String filter = getFilter(predicat); // if (filter != null && !"".equals(filter)) { // // DBObject objPredicat = (DBObject) JSON.parse(filter); // // if (objPredicat != null) { // if (first) { // whereClause.append("$and", new ArrayList<DBObject>()); // } // else { // result += ","; // } // first = false; // // result += filter; // // // ((List<DBObject>) whereClause.get("$and")).add(objPredicat); // // // if (whereClause.containsField(key)) { // // // If the key already exists append the value to the existing key // // // DBObject obj = new BasicDBObject(); // // // obj.put("$and", objPredicat.get(key)); // // // // if (!whereClause.containsField("$and")) { // // whereClause.append("$and", new ArrayList<DBObject>()); // // DBObject pred = (DBObject) whereClause.get(key); // // whereClause.remove(key); // // ((List<DBObject>) whereClause.get("$and")).add(pred); // // // // } // // ((List<DBObject>) whereClause.get("$and")).add(objPredicat); // // // // // ((DBObject) whereClause.get(key)).putAll(obj); // // } // // else { // // // if the key doesn't exists just append the predicat to the whereClause // // whereClause.append(key, objPredicat.get(key)); // // } // // } // // } // } for (Predicat predicat : predicats) { String filter = getFilter(predicat); if (filter != null && !"".equals(filter)) { DBObject objPredicat = (DBObject) JSON.parse(filter); if (objPredicat != null) { Set<String> keys = objPredicat.keySet(); for (String key : keys) { if (whereClause.containsField(key)) { ((DBObject) whereClause.get(key)).putAll((DBObject) objPredicat.get(key)); } else { whereClause.append(key, objPredicat.get(key)); } } } } } return whereClause.toString(); }