Example usage for com.mongodb.util JSON parse

List of usage examples for com.mongodb.util JSON parse

Introduction

In this page you can find the example usage for com.mongodb.util JSON parse.

Prototype

public static Object parse(final String jsonString) 

Source Link

Document

Parses a JSON string and returns a corresponding Java object.

Usage

From source file:com.redhat.thermostat.gateway.service.jvms.mongo.JvmInfoMongoStorageHandler.java

License:Open Source License

public void updateTimestamps(MongoCollection<Document> collection, String body, String systemId,
        Long timeStamp) {/* w  ww.  j a  v  a2  s.  c  o m*/
    final Bson filter;
    if (body != null && body.length() > 0) {
        List<String> jvms = (List<String>) JSON.parse(body);
        List<Bson> jvmFilters = new ArrayList<>();
        for (String id : jvms) {
            jvmFilters.add(eq(StorageFields.JVM_ID, id));
        }
        filter = and(eq(StorageFields.SYSTEM_ID, systemId), or(jvmFilters));
    } else {
        filter = eq(StorageFields.SYSTEM_ID, systemId);
    }

    final Bson lastUpdated = new Document(StorageFields.LAST_UPDATED, timeStamp);
    final Bson update = new Document(SET_KEY, lastUpdated);
    collection.updateMany(filter, update);
}

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

License:Apache License

@RequestMapping(value = "/api/{projectId}/entities/{name}/list", method = RequestMethod.GET, headers = "Accept=application/json")
public @ResponseBody String getEntityDataList(@PathVariable("projectId") String projectId,
        @PathVariable("name") String entityName, @RequestParam(value = "page", required = false) Integer page,
        @RequestParam(value = "limit", required = false) Integer limit,
        @RequestParam(value = "sort", required = false) String sort,
        @RequestParam(value = "query", required = false) String query,
        @RequestHeader(value = "authToken", required = false) String authToken) {

    JSONObject authRes = authService.authorize(projectId, authToken, "USER");
    if (!authRes.getBoolean(SUCCESS)) {
        return authRes.toString(4);
    }//  w ww.  jav  a 2s . c o m

    DBCollection dbCollection = mongoTemplate.getCollection(projectId + "_" + entityName);
    DBCursor cursor;
    if (query != null && !query.isEmpty()) {
        Object queryObject = JSON.parse(query);
        cursor = dbCollection.find((BasicDBObject) queryObject);
    } else {
        cursor = dbCollection.find();
    }

    if (sort != null && !sort.isEmpty()) {
        Object sortObject = JSON.parse(sort);
        cursor.sort((BasicDBObject) sortObject);
    }

    if (limit != null && limit > 0) {
        if (page != null && page > 0) {
            cursor.skip((page - 1) * limit);
        }
        cursor.limit(limit);
    }
    List<DBObject> array = cursor.toArray();

    if (entityName.equals("User")) {
        for (DBObject dbObject : array) {
            dbObject.removeField(PASSWORD);
        }
    }

    for (DBObject dbObject : array) {
        dbRefToRelation(dbObject);
    }
    String json = JSON.serialize(array);

    // Indentation
    JSONArray jsonArr = new JSONArray(json);
    return jsonArr.toString(4);
}

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

License:Apache License

/**
 * [NOTE] http://stackoverflow.com/questions/25953056/how-to-access-fields-of-converted-json-object-sent-in-post-body
 *///ww w.java2s .  c  o  m
@RequestMapping(value = "/api/{projectId}/entities/{name}", method = RequestMethod.POST, headers = "Accept=application/json", consumes = "application/json")
public @ResponseBody String createEntityData(@PathVariable("projectId") String projectId,
        @PathVariable("name") String entityName, @RequestBody Object genericEntityDataDTO,
        @RequestHeader(value = "authToken", required = false) String authToken) {

    String data;
    if (!(genericEntityDataDTO instanceof Map)) {
        return null;
    } else {
        // Note : Entity data is accessible through this map.
        Map map = (Map) genericEntityDataDTO;
        JSONObject jsonObj = createJsonFromMap(map);
        data = jsonObj.toString();
    }

    DBObject dbObject = (DBObject) JSON.parse(data);

    if (entityName.equals("User")) {
        return handleUserEntityData(projectId, dbObject, true);
    }

    DBRef user;
    JSONObject authRes = authService.authorize(projectId, authToken, "USER");
    if (authRes.getBoolean(SUCCESS)) {
        user = (DBRef) authRes.get("user");
    } else {
        return authRes.toString(4);
    }

    // Create a new document for the entity.
    DBCollection dbCollection = mongoTemplate.getCollection(projectId + "_" + entityName);

    relationToDBRef(dbObject, projectId);

    dbObject.put("createdBy", user);
    dbObject.put("createdAt", new Date());

    dbCollection.save(dbObject);
    dbRefToRelation(dbObject);
    String json = dbObject.toString();

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

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  va2s .c  o  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.restfiddle.controller.rest.EntityDataController.java

License:Apache License

@RequestMapping(value = "/api/{projectId}/entities/{name}/list", method = RequestMethod.GET, headers = "Accept=application/json")
public @ResponseBody String getEntityDataList(@PathVariable("projectId") String projectId,
        @PathVariable("name") String entityName, @RequestParam(value = "page", required = false) Integer page,
        @RequestParam(value = "limit", required = false) Integer limit,
        @RequestParam(value = "sort", required = false) String sort,
        @RequestParam(value = "query", required = false) String query) {
    DBCollection dbCollection = mongoTemplate.getCollection(entityName);
    DBCursor cursor = null;// w w w. j  ava  2s .c o  m
    if (query != null && !query.isEmpty()) {
        Object queryObject = JSON.parse(query);
        cursor = dbCollection.find((BasicDBObject) queryObject);
    } else {
        cursor = dbCollection.find();
    }

    if (sort != null && !sort.isEmpty()) {
        Object sortObject = JSON.parse(sort);
        cursor.sort((BasicDBObject) sortObject);
    }

    if (limit != null && limit > 0) {
        if (page != null && page > 0) {
            cursor.skip((page - 1) * limit);
        }
        cursor.limit(limit);
    }
    List<DBObject> array = cursor.toArray();
    String json = JSON.serialize(array);

    // Indentation
    JSONArray jsonArr = new JSONArray(json);
    return jsonArr.toString(4);
}

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

License:Apache License

/**
 * [NOTE] http://stackoverflow.com/questions/25953056/how-to-access-fields-of-converted-json-object-sent-in-post-body
 *//*from   ww  w . j av  a  2  s . co  m*/
@RequestMapping(value = "/api/{projectId}/entities/{name}", method = RequestMethod.POST, headers = "Accept=application/json", consumes = "application/json")
public @ResponseBody String createEntityData(@PathVariable("projectId") String projectId,
        @PathVariable("name") String entityName, @RequestBody Object genericEntityDataDTO) {
    String data = "";
    if (!(genericEntityDataDTO instanceof Map)) {
        return null;
    } else {
        // Note : Entity data is accessible through this map.
        Map map = (Map) genericEntityDataDTO;
        JSONObject jsonObj = createJsonFromMap(map);
        data = jsonObj.toString();
    }
    // Create a new document for the entity.
    DBCollection dbCollection = mongoTemplate.getCollection(entityName);

    Object dbObject = JSON.parse(data);
    dbCollection.save((BasicDBObject) dbObject);
    String json = dbObject.toString();

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

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

License:Open Source License

/**
 * All the scripts should have the following format:
 *
 * {/* w  w w .ja va  2  s. co 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.sample.MyGroceryListServlet.java

License:Open Source License

/**
 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
 *//*from w w  w  . jav  a  2  s  .com*/
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    // Reference: http://docs.mongodb.org/ecosystem/tutorial/getting-started-with-java-driver/#getting-started-with-java-driver

    String envVars = System.getenv("VCAP_SERVICES");

    DBObject dbO = (DBObject) JSON.parse(envVars);
    String parsedString = dbO.get("mongodb").toString();

    // Remove trailing and starting array brackets (otherwise it won't be valid JSON)
    parsedString = parsedString.replaceFirst("\\[ ", "");
    parsedString = parsedString.replaceFirst("\\]$", "");

    // Get the credentials
    dbO = (DBObject) JSON.parse(parsedString);
    parsedString = dbO.get("credentials").toString();

    // For debugging only
    // System.out.println(parsedString);

    dbO = (DBObject) JSON.parse(parsedString);

    System.out.println("Host name : " + dbO.get("hostname"));
    String hostName = dbO.get("hostname").toString();
    int port = Integer.parseInt(dbO.get("port").toString());
    String dbName = dbO.get("db").toString();
    String userName = dbO.get("username").toString();
    String password = dbO.get("password").toString();

    Mongo mongoClient = new Mongo(hostName, port);

    DB db = mongoClient.getDB(dbName);
    db.authenticate(userName, password.toCharArray());

    // Clean up old entries
    DBCollection coll = db.getCollection("testCollection");
    coll.drop();

    BasicDBObject lastAddedObject = null;
    for (String curItem : myGroceryList) {
        lastAddedObject = new BasicDBObject("i", curItem);
        coll.insert(lastAddedObject);
    }
    response.getWriter().println("<b>My grocery list is:</b>");

    coll.remove(lastAddedObject);
    DBCollection loadedCollection = db.getCollection("testCollection");
    DBCursor cursor = loadedCollection.find();
    try {
        response.getWriter().println("<ul>");
        while (cursor.hasNext()) {
            response.getWriter().println("<li>" + cursor.next().get("i") + "</li>");
        }
        response.getWriter().println("</ul>");
    } finally {
        cursor.close();
    }
}

From source file:com.shampan.model.PageModel.java

public ResultEvent updatePage(String pageInfo) {
    try {/*from w w  w .j a  va2s  .  c o  m*/
        MongoCollection<PageDAO> mongoCollection = DBConnection.getInstance().getConnection()
                .getCollection(Collections.PAGES.toString(), PageDAO.class);
        PageDAO pageInformation = new PageDAOBuilder().build(pageInfo);
        if (pageInformation != null) {
            Document selectDocument = new Document();
            selectDocument.put("pageId", pageInformation.getPageId());
            selectDocument.put("referenceId", pageInformation.getReferenceId());
            Document updatedDocument = new Document();
            updatedDocument.put("about", pageInformation.getAbout());
            updatedDocument.put("interestedAgeRange",
                    JSON.parse(pageInformation.getInterestedAgeRange().toString()));
            updatedDocument.put("intertestedGender", pageInformation.getIntertestedGender());
            updatedDocument.put("referenceInfo", JSON.parse(pageInformation.getReferenceInfo().toString()));
            PageDAO result1 = mongoCollection.findOneAndUpdate(selectDocument,
                    new Document("$set", updatedDocument));
            this.getResultEvent().setResponseCode(PropertyProvider.get("SUCCESSFUL_OPERATION"));
        }
    } catch (Exception ex) {
        this.getResultEvent().setResponseCode(PropertyProvider.get("ERROR_EXCEPTION"));
    }
    return this.resultEvent;

}

From source file:com.shampan.model.PageModel.java

public ResultEvent addPageMember(String pageId, String memberInfo) {
    try {//from w  w  w  .  j  a v  a  2  s  . c  om
        MongoCollection<PageMemberDAO> mongoCollection = DBConnection.getInstance().getConnection()
                .getCollection(Collections.PAGEMEMBERS.toString(), PageMemberDAO.class);
        Document selectDocument = new Document();
        selectDocument.put("pageId", pageId);
        MemberInfo mInfo = MemberInfo.getMemberInfo(memberInfo);
        if (mInfo != null) {
            PageMemberDAO pageInfo = mongoCollection.find(selectDocument).first();
            boolean userIsExist = false;
            if (pageInfo != null) {
                List<MemberInfo> memberList = pageInfo.getMemberList();
                List<MemberInfo> tempMemberList = new ArrayList<>();
                if (memberList.size() > 0) {
                    for (int i = 0; i < memberList.size(); i++) {
                        MemberInfo tempMemberInfo = memberList.get(i);
                        if (tempMemberInfo.getUserId().equals(mInfo.getUserId())) {
                            tempMemberInfo
                                    .setRelationTypeId(PropertyProvider.get("PAGE_MEMBER_STATUS_ID_LIKED"));
                            userIsExist = true;
                        }
                        tempMemberList.add(tempMemberInfo);
                    }
                }
                if (userIsExist != false) {
                    mongoCollection.findOneAndUpdate(selectDocument, new Document("$set",
                            new Document("memberList", JSON.parse(tempMemberList.toString()))));
                } else {
                    mongoCollection.findOneAndUpdate(selectDocument,
                            new Document("$push", new Document("memberList", JSON.parse(mInfo.toString()))));
                }
            } else {
                List<MemberInfo> mList = new ArrayList<MemberInfo>();
                mList.add(mInfo);
                PageMemberDAO pageMember = new PageMemberDAO();
                pageMember.setPageId(pageId);
                pageMember.setMemberList(mList);
                mongoCollection.insertOne(pageMember);
            }
            this.getResultEvent().setResponseCode(PropertyProvider.get("SUCCESSFUL_OPERATION"));
        } else {
            this.getResultEvent().setResponseCode(PropertyProvider.get("NULL_POINTER_EXCEPTION"));
        }
    } catch (Exception ex) {
        this.getResultEvent().setResponseCode(PropertyProvider.get("ERROR_EXCEPTION"));
    }
    return this.resultEvent;

}