Example usage for com.mongodb DBObject containsField

List of usage examples for com.mongodb DBObject containsField

Introduction

In this page you can find the example usage for com.mongodb DBObject containsField.

Prototype

boolean containsField(String s);

Source Link

Document

Checks if this object contains a field with the given name.

Usage

From source file:com.redhat.lightblue.mongo.crud.BsonMerge.java

License:Open Source License

@Override
protected boolean hasField(DBObject value, String field) {
    return value.containsField(field);
}

From source file:com.restfeel.controller.rest.EntityDataController.java

License:Apache License

@RequestMapping(value = "/api/{projectId}/entities/{name}/{uuid}", method = RequestMethod.PUT, headers = "Accept=application/json", consumes = "application/json")
public @ResponseBody String updateEntityData(@PathVariable("projectId") String projectId,
        @PathVariable("name") String entityName, @PathVariable("uuid") String uuid,
        @RequestBody Object genericEntityDataDTO,
        @RequestHeader(value = "authToken", required = false) String authToken) {

    DBRef user;//ww  w .  j a  v  a  2s  .  co  m
    JSONObject authRes = authService.authorize(projectId, authToken, "USER");
    if (authRes.getBoolean(SUCCESS)) {
        user = (DBRef) authRes.get("user");
    } else {
        return authRes.toString(4);
    }

    DBObject resultObject = new BasicDBObject();
    if (genericEntityDataDTO instanceof Map) {
        Map map = (Map) genericEntityDataDTO;
        if (map.get("id") != null && map.get("id") instanceof String) {
            String entityDataId = (String) map.get("id");
            logger.debug("Updating Entity Data with Id " + entityDataId);
        }
        JSONObject uiJson = new JSONObject(map);
        // ID is stored separately (in a different column).
        DBObject obj = (DBObject) JSON.parse(uiJson.toString());
        obj.removeField("_id");

        DBCollection dbCollection = mongoTemplate.getCollection(projectId + "_" + entityName);
        BasicDBObject queryObject = new BasicDBObject();
        queryObject.append("_id", new ObjectId(uuid));
        resultObject = dbCollection.findOne(queryObject);

        Set<String> keySet = obj.keySet();
        for (String key : keySet) {
            resultObject.put(key, obj.get(key));
        }

        if (entityName.equals("User")) {
            DBObject loggedInUser = dbCollection.findOne(user);
            if (loggedInUser.get(USERNAME).equals(resultObject.get(USERNAME))) {
                return handleUserEntityData(projectId, resultObject, obj.containsField(PASSWORD));
            } else {
                return new JSONObject().put(SUCCESS, false).put("msg", "unauthorized").toString(4);
            }
        }

        relationToDBRef(resultObject, projectId);

        resultObject.put("updatedBy", user);
        resultObject.put("updatedAt", new Date());

        dbCollection.save(resultObject);
    }
    dbRefToRelation(resultObject);
    String json = resultObject.toString();

    // Indentation
    JSONObject jsonObject = new JSONObject(json);
    return jsonObject.toString(4);
}

From source file:com.restfeel.controller.rest.EntityDataController.java

License:Apache License

private void dbRefToRelation(DBObject dbObject) {
    if (dbObject == null) {
        return;//from   w  w  w.jav  a2  s .c  om
    }
    if (dbObject.containsField("_id"))
        dbObject.put("_id", ((ObjectId) dbObject.get("_id")).toHexString());
    for (String key : dbObject.keySet()) {
        Object obj = dbObject.get(key);
        if (obj instanceof DBRef) {
            DBRef ref = (DBRef) obj;
            dbObject.put(key, dbRefToRel(ref));
        } else if (obj instanceof DBObject) {
            dbRefToRelation((DBObject) obj);
        }
    }

}

From source file:com.restfeel.controller.rest.EntityDataController.java

License:Apache License

private void relationToDBRef(DBObject dbObject, String projectId) {
    for (String key : dbObject.keySet()) {
        Object obj = dbObject.get(key);
        if (obj instanceof DBObject) {
            DBObject doc = (DBObject) obj;
            if (doc.containsField("_rel")) {
                DBObject relation = (DBObject) doc.get("_rel");
                dbObject.put(key, new DBRef(projectId + "_" + (String) relation.get("entity"),
                        new ObjectId((String) relation.get("_id"))));
            } else {
                relationToDBRef(doc, projectId);
            }/*from w w  w.  ja va 2s  .  c  om*/
        }
    }
}

From source file:com.restfeel.controller.rest.EntityDataController.java

License:Apache License

private String handleUserEntityData(String projectId, DBObject user, boolean encryptPassword) {
    JSONObject response = new JSONObject();

    if (!user.containsField(USERNAME)) {
        response.put("msg", "username is mandotary");
        return response.toString(4);
    }//from  w  w w  .  ja  v a  2s  .  c  om

    if (((String) user.get(USERNAME)).length() < 3) {
        response.put("msg", "username must be more then 3 character");
        return response.toString(4);
    }

    if (!user.containsField(PASSWORD)) {
        response.put("msg", "password is mandotary");
        return response.toString(4);
    }

    if (((String) user.get(PASSWORD)).length() < 3) {
        response.put("msg", "password must be more then 3 character");
        return response.toString(4);
    }

    DBCollection dbCollection = mongoTemplate.getCollection(projectId + "_User");

    BasicDBObject query = new BasicDBObject();
    query.append(USERNAME, user.get(USERNAME));

    DBObject existingUser = dbCollection.findOne(query);

    if (existingUser != null && !existingUser.get("_id").equals(user.get("_id"))) {
        response.put("msg", "username already exists");
        return response.toString(4);
    }

    if (encryptPassword) {
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        user.put(PASSWORD, encoder.encode((String) user.get(PASSWORD)));
    }

    relationToDBRef(user, projectId);

    dbCollection.save(user);
    user.removeField(PASSWORD);
    dbRefToRelation(user);
    String json = user.toString();

    // Indentation
    response = new JSONObject(json);
    return response.toString(4);
}

From source file:com.ricardolorenzo.identity.user.impl.UserIdentityManagerMongoDB.java

License:Open Source License

/**
 * All the scripts should have the following format:
 *
 * {/*from www .ja v  a2s. c o m*/
 *    database.collection: {
 *        operation: insert|update|find|aggregate|delete
 *        query: {}
 *    }
 * }
 *
 * For update operations, you should specify the following:
 *
 * query: {
 *     find: {}
 *     update: {}
 * }
 */
private List<DBObject> runQueryScript(final String scriptType, final Map<String, Object[]> attributes)
        throws IdentityException {
    List<DBObject> results = new ArrayList<>();
    try {
        DB database = mongoClient.getDB(this.properties.getProperty("mongodb.database"));
        final ScriptCollection sc = getScriptCollection();
        if (sc.hasScript(scriptType)) {
            final String scriptContent = sc.getScript(scriptType);
            String query = createQueryFromScript(scriptContent, attributes);
            DBObject collectionOperation = DBObject.class.cast(JSON.parse(query));

            for (String collection : collectionOperation.keySet()) {
                if (!database.collectionExists(collection)) {
                    throw new IdentityException("collection [" + collection + "] does not exists");
                }

                DBObject dbObject = DBObject.class.cast(collectionOperation.get(collection));
                if (!dbObject.containsField("operation")) {
                    throw new IdentityException("operation field not specified");
                }

                String dbOperation = String.class.cast(dbObject.get("operation")).toLowerCase();
                if (!OPERATIONS.contains(dbOperation)) {
                    throw new IdentityException("operation [" + dbOperation + "] not supported");
                }

                DBObject dbQuery = DBObject.class.cast(dbObject.get("query"));
                if (dbQuery == null) {
                    throw new IdentityException("query field not specified");
                }

                DBCollection coll = database.getCollection(collection);
                switch (dbOperation) {
                case "insert": {
                    coll.insert(dbQuery);
                }
                case "update": {
                    if (!dbObject.containsField("find")) {
                        throw new IdentityException("find field not found inside the update operation");
                    }
                    if (!dbObject.containsField("update")) {
                        throw new IdentityException("update field not found inside the update operation");
                    }
                    DBObject dbUpdateFind = DBObject.class.cast(dbQuery.get("find"));
                    DBObject dbUpdateFields = DBObject.class.cast(dbQuery.get("update"));
                    coll.update(dbUpdateFind, dbUpdateFields, false, false);
                }
                case "delete": {
                    coll.remove(dbQuery);
                }
                case "find": {
                    DBCursor cursor = coll.find(dbQuery);
                    while (cursor.hasNext()) {
                        results.add(cursor.next());
                    }
                }
                case "aggregate": {
                    List<DBObject> aggregate = new ArrayList<DBObject>();
                    aggregate.add(dbQuery);
                    for (DBObject o : coll.aggregate(aggregate).results()) {
                        results.add(o);
                    }
                }
                }
            }
            return results;
        }
    } catch (final NoSuchAlgorithmException e) {
        throw new IdentityException(e.getMessage());
    } finally {
        /**
         * TODO close cursors
         */
    }
    return null;
}

From source file:com.simonschlueter.gantic.ObjectParser.java

License:MIT License

public static <T> T parseDbObject(Class<T> objectClass, DBObject data) {
    try {//  www  .j  a  v  a  2s.  c  o 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.softinstigate.restheart.handlers.collection.PatchCollectionHandler.java

License:Open Source License

/**
 *
 * @param exchange// ww  w . j  a  v a2 s  . co  m
 * @param context
 * @throws Exception
 */
@Override
public void handleRequest(HttpServerExchange exchange, RequestContext context) throws Exception {
    if (context.getDBName().isEmpty()) {
        ResponseHelper.endExchangeWithMessage(exchange, HttpStatus.SC_NOT_ACCEPTABLE,
                "wrong request, db name cannot be empty");
        return;
    }

    if (context.getCollectionName().isEmpty() || context.getCollectionName().startsWith("_")) {
        ResponseHelper.endExchangeWithMessage(exchange, HttpStatus.SC_NOT_ACCEPTABLE,
                "wrong request, collection name cannot be empty or start with _");
        return;
    }

    DBObject content = context.getContent();

    if (content == null) {
        ResponseHelper.endExchangeWithMessage(exchange, HttpStatus.SC_NOT_ACCEPTABLE, "no data provided");
        return;
    }

    // cannot PATCH with an array
    if (content instanceof BasicDBList) {
        ResponseHelper.endExchangeWithMessage(exchange, HttpStatus.SC_NOT_ACCEPTABLE,
                "data cannot be an array");
        return;
    }

    if (content.containsField(Relationship.RELATIONSHIPS_ELEMENT_NAME)) {
        try {
            Relationship.getFromJson(content);
        } catch (InvalidMetadataException ex) {
            ResponseHelper.endExchangeWithMessage(exchange, HttpStatus.SC_NOT_ACCEPTABLE,
                    "wrong relationships definition. " + ex.getMessage(), ex);
            return;
        }
    }

    ObjectId etag = RequestHelper.getWriteEtag(exchange);

    if (etag == null) {
        ResponseHelper.endExchange(exchange, HttpStatus.SC_CONFLICT);
        return;
    }

    int SC = CollectionDAO.upsertCollection(context.getDBName(), context.getCollectionName(), content, etag,
            true, true);

    // send the warnings if any (and in case no_content change the return code to ok
    if (context.getWarnings() != null && !context.getWarnings().isEmpty()) {
        if (SC == HttpStatus.SC_NO_CONTENT) {
            exchange.setResponseCode(HttpStatus.SC_OK);
        } else {
            exchange.setResponseCode(SC);
        }

        DocumentRepresentationFactory.sendDocument(exchange.getRequestPath(), exchange, context,
                new BasicDBObject());
    } else {
        exchange.setResponseCode(SC);
    }

    exchange.endExchange();

    LocalCachesSingleton.getInstance().invalidateCollection(context.getDBName(), context.getCollectionName());
}

From source file:com.softinstigate.restheart.handlers.collection.PutCollectionHandler.java

License:Open Source License

/**
 *
 * @param exchange//w ww  .  ja  v  a 2s . co m
 * @param context
 * @throws Exception
 */
@Override
public void handleRequest(HttpServerExchange exchange, RequestContext context) throws Exception {
    if (context.getCollectionName().isEmpty() || context.getCollectionName().startsWith("_")) {
        ResponseHelper.endExchangeWithMessage(exchange, HttpStatus.SC_NOT_ACCEPTABLE,
                "wrong request, collection name cannot be empty or start with _");
        return;
    }

    DBObject content = context.getContent();

    if (content == null) {
        content = new BasicDBObject();
    }

    // cannot PUT an array
    if (content instanceof BasicDBList) {
        ResponseHelper.endExchangeWithMessage(exchange, HttpStatus.SC_NOT_ACCEPTABLE,
                "data cannot be an array");
        return;
    }

    if (content.containsField(Relationship.RELATIONSHIPS_ELEMENT_NAME)) {
        try {
            Relationship.getFromJson(content);
        } catch (InvalidMetadataException ex) {
            ResponseHelper.endExchangeWithMessage(exchange, HttpStatus.SC_NOT_ACCEPTABLE,
                    "wrong relationships definition. " + ex.getMessage(), ex);
            return;
        }
    }

    ObjectId etag = RequestHelper.getWriteEtag(exchange);

    boolean updating = context.getCollectionProps() != null;

    int SC = CollectionDAO.upsertCollection(context.getDBName(), context.getCollectionName(), content, etag,
            updating, false);

    // send the warnings if any (and in case no_content change the return code to ok
    if (context.getWarnings() != null && !context.getWarnings().isEmpty()) {
        if (SC == HttpStatus.SC_NO_CONTENT) {
            exchange.setResponseCode(HttpStatus.SC_OK);
        } else {
            exchange.setResponseCode(SC);
        }

        DocumentRepresentationFactory.sendDocument(exchange.getRequestPath(), exchange, context,
                new BasicDBObject());
    } else {
        exchange.setResponseCode(SC);
    }

    exchange.endExchange();
    LocalCachesSingleton.getInstance().invalidateCollection(context.getDBName(), context.getCollectionName());
}

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/* w w w.  j a v  a  2  s.  c o  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;
}