Example usage for com.mongodb BasicDBObject append

List of usage examples for com.mongodb BasicDBObject append

Introduction

In this page you can find the example usage for com.mongodb BasicDBObject append.

Prototype

@Override
public BasicDBObject append(final String key, final Object val) 

Source Link

Document

Add a key/value pair to this object

Usage

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;//  w w w  . j  a v  a  2  s . 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.restfeel.controller.rest.EntityDataController.java

License:Apache License

@RequestMapping(value = "/api/{projectId}/entities/{name}/{uuid}", method = RequestMethod.DELETE, headers = "Accept=application/json")
public @ResponseBody StatusResponse deleteEntityData(@PathVariable("projectId") String projectId,
        @PathVariable("name") String entityName, @PathVariable("uuid") String uuid,
        @RequestHeader(value = "authToken", required = false) String authToken) {

    StatusResponse res = new StatusResponse();

    JSONObject authRes = authService.authorize(projectId, authToken, "USER");
    if (!authRes.getBoolean(SUCCESS)) {
        res.setStatus("Unauthorized");
        return res;
    }/*from  ww w  .j a v a 2s  . c  om*/

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

    res.setStatus("DELETED");

    return res;
}

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);
    }// w ww.j ava 2  s .  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.restfiddle.controller.rest.EntityDataController.java

License:Apache License

@RequestMapping(value = "/api/{projectId}/entities/{name}/{id}", method = RequestMethod.GET, headers = "Accept=application/json")
public @ResponseBody String getEntityDataById(@PathVariable("projectId") String projectId,
        @PathVariable("name") String entityName, @PathVariable("id") String entityDataId) {
    DBCollection dbCollection = mongoTemplate.getCollection(entityName);

    BasicDBObject queryObject = new BasicDBObject();
    queryObject.append("_id", new ObjectId(entityDataId));

    DBObject resultObject = dbCollection.findOne(queryObject);
    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}/{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) {
    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);
        }/*from w  w w. ja va  2  s. c o m*/
        JSONObject uiJson = createJsonFromMap(map);
        // ID is stored separately (in a different column).
        uiJson.remove("id");

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

        Set<String> keySet = uiJson.keySet();
        for (String key : keySet) {
            resultObject.put(key, uiJson.get(key));
        }
        dbCollection.save(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}/{uuid}", method = RequestMethod.DELETE, headers = "Accept=application/json")
public @ResponseBody StatusResponse deleteEntityData(@PathVariable("projectId") String projectId,
        @PathVariable("name") String entityName, @PathVariable("uuid") String uuid) {
    DBCollection dbCollection = mongoTemplate.getCollection(entityName);
    BasicDBObject queryObject = new BasicDBObject();
    queryObject.append("_id", new ObjectId(uuid));
    dbCollection.remove(queryObject);//  ww w  . j  a v  a  2s.  co m

    StatusResponse res = new StatusResponse();
    res.setStatus("DELETED");

    return res;
}

From source file:com.servlet.IndividualExpense.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request//from  w  w w .j  a v a2 s .  com
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    PrintWriter out = response.getWriter();
    DBcon dbcon = new DBcon();
    dbcon.getDbCon();
    JSONObject json = new JSONObject();
    DBCollection coll = dbcon.getData("claims");

    String searchid = request.getParameter("searchId");
    int empid = Integer.parseInt(searchid);
    BasicDBObject search = new BasicDBObject();
    search.append("status", "Approved");
    search.append("empid", empid);

    DBCursor cursor = coll.find(search);
    int foodSum = 0;
    int internetSum = 0;
    int otherSum = 0;
    while (cursor.hasNext()) {
        DBObject obj = cursor.next();
        ArrayList li = (ArrayList) obj.get("details");

        if (!li.isEmpty()) {

            Iterator<BasicDBObject> intI = li.iterator();
            while (intI.hasNext()) {
                BasicDBObject o = intI.next();
                Claims cl = Claims.fromDBObject(o);
                String billType = (String) cl.getBillType();
                if (billType.equals("Food")) {
                    foodSum += (int) cl.getAmount();

                } else if (billType.equals("Internet")) {
                    internetSum += (int) cl.getAmount();
                } else {
                    otherSum += (int) cl.getAmount();
                }

            }

        }
    }
    json.put("foodsum", foodSum);
    json.put("internetsum", internetSum);
    json.put("othersum", otherSum);
    out.print(json);
}

From source file:com.servlet.MonthlyClaimLimit.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request/* w w  w . j a va  2s .  co m*/
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    PrintWriter out = response.getWriter();
    try {
        //int claimId = Integer.parseInt(request.getParameter("claimid"));// both empid and claimid are integers
        String email = request.getParameter("email");

        DBcon dbcon = new DBcon();
        dbcon.getDbCon();// setup the database connection
        DBCollection coll = dbcon.getData("claims");

        Date currentDate = new Date();//current date
        DateFormat formatter = new SimpleDateFormat("MM/yyyy");

        currentDate = formatter.parse(formatter.format(currentDate));
        Date start = currentDate;
        Calendar c = Calendar.getInstance();
        c.setTime(currentDate);
        c.add(Calendar.MONTH, 1);
        Date end = c.getTime();

        BasicDBObject searchMonthExpence = new BasicDBObject();
        searchMonthExpence.append("status", "Approved");
        searchMonthExpence.append("email", email);
        searchMonthExpence.append("date", new BasicDBObject("$gte", start).append("$lt", end)); //send notifications

        DBCursor Limitcursor = coll.find(searchMonthExpence);
        double currentMonthTotal = 0;

        while (Limitcursor.hasNext()) {
            DBObject dBObject = Limitcursor.next();
            Claims claims = Claims.fromDBObject2(dBObject);
            currentMonthTotal += claims.getTotal();

        }

        out.print(currentMonthTotal);
    } catch (ParseException ex) {
        Logger.getLogger(MonthlyClaimLimit.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:com.servlet.UpdateClaim.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request//from   w w w  . j  av  a2 s . c  om
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    PrintWriter out = response.getWriter();
    double total = 0;
    //variable declaration
    FileItem item = null;
    String fieldName = "";
    String fieldValue = "";
    String fileName = "";
    boolean isImageExist = false;
    //current sessions
    Employee emp = (Employee) request.getSession().getAttribute("user");
    Claims cla = (Claims) request.getSession().getAttribute("c");

    //bean object
    Claims claims = new Claims();

    boolean isMultipart = ServletFileUpload.isMultipartContent(request);

    if (isMultipart) {

        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);

        try {

            List items = upload.parseRequest(request);
            Iterator iterator = items.iterator();

            while (iterator.hasNext()) {
                item = (FileItem) iterator.next();
                if (!item.isFormField()) { // check for regular form field 
                    fileName = item.getName();
                    if (!fileName.equals("")) {

                        String root = getServletContext().getRealPath("/");
                        response.getWriter().write(root);
                        File path = new File(root + "/images/uploads" + File.separator + "Claims"
                                + File.separator + cla.getClaimId());

                        String filePath = "images/uploads/Claims/" + cla.getClaimId() + "/" + fileName;
                        filePath = filePath.replace("\\", "/");
                        if (!path.exists()) {
                            boolean status = path.mkdirs();
                        }
                        //File uploadedFile = new File(path + "/" + fileName);  // for copy file
                        File uploadedFile = new File(path + "/" + fileName); // for copy file

                        item.write(uploadedFile);
                        isImageExist = true;
                        claims.setAttachment(filePath);//save the url in databse

                    } else {
                        isImageExist = false;

                    }

                } else {

                    fieldName = item.getFieldName();// field name of current File item
                    fieldValue = item.getString();
                    if (fieldName.equals("docid")) {
                        claims.setDocId(Integer.parseInt(fieldValue));
                    } else if (fieldName.equals("claim_group")) {
                        claims.setClaimGroup(fieldValue);
                    } else if (fieldName.equals("type_of_claim")) {//bill type
                        claims.setBillType(fieldValue);
                    } else if (fieldName.equals("food_type")) {//meal type
                        claims.setMealType(fieldValue);
                    } else if (fieldName.equals("bill_date")) {
                        claims.setBillDate(fieldValue);
                    } else if (fieldName.equals("amount")) {
                        claims.setAmount(Double.parseDouble(fieldValue));
                    } else if (fieldName.equals("project")) {
                        claims.setProject(fieldValue);
                    } else if (fieldName.equals("description")) {
                        claims.setDescription(fieldValue);
                    } else if (fieldName.equals("employeesId")) {
                        claims.setEmpListId(fieldValue);
                    }
                    ////////////////////

                }

            } //end of while

            DBcon dbcon = new DBcon();
            dbcon.getDbCon();// set up the database connection
            DBCollection coll = dbcon.getData("claims");

            BasicDBObject search = new BasicDBObject("claimid", cla.getClaimId());
            search.append("details.docid", claims.getDocId());

            DBObject obj = claims.toDBObject();//create DBObject from data

            BasicDBObject update = new BasicDBObject();
            update.append("details.$.claimgroup", claims.getClaimGroup());
            update.append("details.$.billtype", claims.getBillType());
            update.append("details.$.mealtype", claims.getMealType());
            update.append("details.$.bill_date", claims.getBillDate());
            update.append("details.$.amount", claims.getAmount());
            update.append("details.$.project", claims.getProject());
            update.append("details.$.description", claims.getDescription());
            update.append("details.$. employeesId", claims.getEmpListId());
            if (isImageExist) {
                update.append("details.$.attachment", claims.getAttachment());
            }

            BasicDBObject push = new BasicDBObject("$set", update);
            dbcon.updateData("claims", search, push);//update the new document 

            DBCursor cursor = coll.find(search);
            DBObject findMainObject = cursor.next();
            Claims mainClaimObject = Claims.fromDBObject2(findMainObject);//create a main claim object
            ArrayList list = mainClaimObject.getDetails();

            Iterator<BasicDBObject> intI = list.iterator();
            while (intI.hasNext()) {
                BasicDBObject o = intI.next();
                Claims cl = Claims.fromDBObject(o);
                total += cl.getAmount();
            }

            mainClaimObject.setTotal(total);//update the total claim amount*/
            DBObject mainObject = mainClaimObject.toDBObject2();
            dbcon.updateData("claims", search, mainObject);//update the new document    
            response.sendRedirect("home_page_claim_add.jsp");

        } catch (FileUploadException e) {

            e.printStackTrace();
        } catch (Exception e) {

            e.printStackTrace();
        }

    }
}

From source file:com.sitewhere.mongodb.asset.MongoAsset.java

License:Open Source License

/**
 * Copy information from SPI into Mongo DBObject.
 * //from  ww w  .  ja  va2  s  .co m
 * @param source
 * @param target
 */
public static void toDBObject(IAsset source, BasicDBObject target) {
    target.append(PROP_ID, source.getId());
    target.append(PROP_NAME, source.getName());
    target.append(PROP_ASSET_TYPE, source.getType().name());
    target.append(PROP_CATEGORY_ID, source.getAssetCategoryId());
    target.append(PROP_IMAGE_URL, source.getImageUrl());

    // Save nested list of properties.
    List<BasicDBObject> props = new ArrayList<BasicDBObject>();
    for (String name : source.getProperties().keySet()) {
        BasicDBObject prop = new BasicDBObject();
        prop.put("name", name);
        prop.put("value", source.getProperties().get(name));
        props.add(prop);
    }
    target.append(PROP_PROPERTIES, props);
}