Example usage for com.google.gson JsonObject toString

List of usage examples for com.google.gson JsonObject toString

Introduction

In this page you can find the example usage for com.google.gson JsonObject toString.

Prototype

@Override
public String toString() 

Source Link

Document

Returns a String representation of this element.

Usage

From source file:com.bid.online.presentation.bidmanagement.BidItemServlet.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from  w w  w  .  ja  v  a  2  s .  c  o m*/
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    List<Item> itemList = bidService.getItemList();
    List<ItemView> itemViewList = new ArrayList<>();
    for (Item item : itemList) {
        ItemView view = new ItemView();
        view.setId(String.valueOf(item.getId()));
        view.setName(item.getName());
        view.setDescription(item.getDescription());
        Date currentDate = new Date();
        long diff = item.getBidEndDate().getTime().getTime() - currentDate.getTime();
        if (diff < 0) {
            diff = 0;
        }
        view.setTimeInSeconds(String.valueOf((long) (diff / 1000)));
        DateFormat df = new SimpleDateFormat("dd/mm/yyyy hh:mm:ss");
        view.setEndDate(df.format(item.getBidEndDate().getTime()));
        view.setStartDate(df.format(item.getBidStartDate().getTime()));

        Bid bid = bidService.getHighestBid(item.getId());

        StringBuilder sb = new StringBuilder();
        if (bid != null && bid.getValue().compareTo(item.getInitialBidValue()) == 1) {
            sb.append(bid.getValue());
        } else {
            sb.append(item.getInitialBidValue());
        }

        sb.append(StringUtils.SPACE);
        sb.append(StringUtils.SGD);

        view.setPrice(sb.toString());

        view.setImgUrl(item.getImage().getUrl());
        view.setMarketPrice(item.getActualValue().toString());
        itemViewList.add(view);
    }

    response.setContentType("text/html;charset=UTF-8");
    Gson gson = new Gson();
    JsonObject jResponse = new JsonObject();
    JsonElement items = gson.toJsonTree(itemViewList);
    jResponse.addProperty("success", Boolean.TRUE);
    jResponse.add("items", items);

    PrintWriter out = response.getWriter();
    response.setContentType("text/html");
    response.setHeader("Cache-control", "no-cache, no-store");
    response.setHeader("Pragma", "no-cache");
    response.setHeader("Expires", "-1");

    response.setHeader("Access-Control-Allow-Origin", "*");
    response.setHeader("Access-Control-Allow-Methods", "POST");
    response.setHeader("Access-Control-Allow-Headers", "Content-Type");
    response.setHeader("Access-Control-Max-Age", "86400");
    System.out.println(jResponse.toString());
    out.println(jResponse.toString());
    out.close();

}

From source file:com.bid.online.presentation.bidmanagement.CategoryServlet.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from  www .j a  v a  2  s.  c o m*/
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String code = request.getParameter("code");
    Map<String, List<CategoryView>> map = (Map<String, List<CategoryView>>) request.getServletContext()
            .getAttribute("subCategoryMap");
    List<CategoryView> catList = map.get(code);
    Gson gson = new Gson();
    JsonObject jResponse = new JsonObject();
    JsonElement items = gson.toJsonTree(catList);

    jResponse.addProperty("success", Boolean.TRUE);
    jResponse.add("items", items);

    PrintWriter out = response.getWriter();
    response.setContentType("text/html");
    response.setHeader("Cache-control", "no-cache, no-store");
    response.setHeader("Pragma", "no-cache");
    response.setHeader("Expires", "-1");

    response.setHeader("Access-Control-Allow-Origin", "*");
    response.setHeader("Access-Control-Allow-Methods", "POST");
    response.setHeader("Access-Control-Allow-Headers", "Content-Type");
    response.setHeader("Access-Control-Max-Age", "86400");
    System.out.println(jResponse.toString());
    out.println(jResponse.toString());
    out.close();

}

From source file:com.bid.online.presentation.bidmanagement.CreateBidServlet.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from  w w w  .j  a  va  2  s  .c  om*/
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String value = request.getParameter("bidValue");
    String itemId = request.getParameter("itemId");
    User user = (User) request.getSession().getAttribute(StringUtils.USER);
    Bid bid = new Bid();
    bid.setCreateTimestamp(new Date());
    Item item = bidService.getItemById(Long.valueOf(itemId));
    bid.setItem(item);
    bid.setUser(user);
    bid.setValue(new BigDecimal(value));
    bid = bidService.createBid(bid);
    bid = bidService.getHighestBid(item.getId());

    BidView view = new BidView();
    view.setItemId(String.valueOf(item.getId()));
    if (item.getInitialBidValue().compareTo(bid.getValue()) == 1) {
        view.setValue(item.getInitialBidValue().toString());
    } else {
        view.setValue(bid.getValue().toString());
    }

    DateFormat df = new SimpleDateFormat("dd/mm/yyyy hh:mm:ss");
    view.setCreateDate(df.format(bid.getCreateTimestamp()));

    response.setContentType("text/html;charset=UTF-8");
    Gson gson = new Gson();
    JsonObject jResponse = new JsonObject();
    JsonElement bidItem = gson.toJsonTree(view);
    jResponse.addProperty("success", Boolean.TRUE);
    jResponse.add("bidItem", bidItem);

    PrintWriter out = response.getWriter();
    response.setContentType("text/html");
    response.setHeader("Cache-control", "no-cache, no-store");
    response.setHeader("Pragma", "no-cache");
    response.setHeader("Expires", "-1");

    response.setHeader("Access-Control-Allow-Origin", "*");
    response.setHeader("Access-Control-Allow-Methods", "POST");
    response.setHeader("Access-Control-Allow-Headers", "Content-Type");
    response.setHeader("Access-Control-Max-Age", "86400");
    System.out.println(jResponse.toString());
    out.println(jResponse.toString());
    out.close();
}

From source file:com.bid.online.presentation.bidmanagement.CreateItemServlet.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from   w ww  .  j  ava2s.c o  m
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String name = request.getParameter("name");
    String description = request.getParameter("description");
    String marketPrice = request.getParameter("marketPrice");
    String bidPrice = request.getParameter("bidPrice");
    String code = request.getParameter("code");
    String startDate = request.getParameter("startDate");
    String endDate = request.getParameter("endDate");
    String imgId = request.getParameter("imgId");
    String imgUrl = request.getParameter("imgUrl");

    Item item = new Item();
    item.setActualValue(new BigDecimal(marketPrice));
    SimpleDateFormat format = new SimpleDateFormat("dd/mm/yyyy hh:mm:ss");
    try {
        Date bidStartDate = format.parse(startDate);
        Date bidEndDate = format.parse(endDate);

        Calendar cs = Calendar.getInstance();
        cs.setTime(bidStartDate);
        item.setBidStartDate(cs);

        Calendar ce = Calendar.getInstance();
        ce.setTime(bidEndDate);
        item.setBidEndDate(ce);
    } catch (ParseException ex) {
        Logger.getLogger(CreateItemServlet.class.getName()).log(Level.SEVERE, null, ex);
    }

    if (code != null) {
        SubCategory category = bidService.getSubCategoryById(Long.valueOf(code));
        item.setCategory(category);
    }
    item.setCreateTimestamp(new Date());
    item.setDescription(description);
    item.setInitialBidValue(new BigDecimal(bidPrice));
    item.setName(name);
    if (request.getSession().getAttribute(StringUtils.USER) != null) {
        User user = (User) request.getSession().getAttribute(StringUtils.USER);
        item.setOwner(user);
    }
    if (imgId != null) {
        Image img = bidService.getImageById(Long.valueOf(imgId));
        item.setImage(img);
    }
    item = bidService.createItem(item);
    ItemView view = new ItemView();

    view.setId(String.valueOf(item.getId()));
    view.setName(name);
    view.setPrice(bidPrice);
    view.setImgUrl(imgUrl);
    Gson gson = new Gson();
    JsonObject jResponse = new JsonObject();
    JsonElement jasonElement = gson.toJsonTree(view);

    jResponse.addProperty("success", Boolean.TRUE);
    jResponse.add("item", jasonElement);
    PrintWriter out = response.getWriter();
    response.setContentType("text/html");
    response.setHeader("Cache-control", "no-cache, no-store");
    response.setHeader("Pragma", "no-cache");
    response.setHeader("Expires", "-1");

    response.setHeader("Access-Control-Allow-Origin", "*");
    response.setHeader("Access-Control-Allow-Methods", "POST");
    response.setHeader("Access-Control-Allow-Headers", "Content-Type");
    response.setHeader("Access-Control-Max-Age", "86400");
    System.out.println(jResponse.toString());
    out.println(jResponse.toString());
    out.close();
}

From source file:com.bid.online.presentation.bidmanagement.ItemByCategory.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//w w  w  .j  av a2s.c  om
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String code = request.getParameter("code");
    List<Item> itemList = bidService.getItemByCategory(Long.valueOf(code));

    List<ItemView> itemViewList = new ArrayList<>();
    for (Item item : itemList) {
        ItemView view = new ItemView();
        view.setId(String.valueOf(item.getId()));
        view.setName(item.getName());
        view.setDescription(item.getDescription());
        Date currentDate = new Date();
        long diff = item.getBidEndDate().getTime().getTime() - currentDate.getTime();
        if (diff < 0) {
            diff = 0;
        }
        view.setTimeInSeconds(String.valueOf((long) (diff / 1000)));
        DateFormat df = new SimpleDateFormat("dd/mm/yyyy hh:mm:ss");
        view.setEndDate(df.format(item.getBidEndDate().getTime()));
        view.setStartDate(df.format(item.getBidStartDate().getTime()));

        StringBuilder sb = new StringBuilder();
        sb.append(item.getInitialBidValue());
        sb.append(StringUtils.SPACE);
        sb.append(StringUtils.SGD);
        view.setPrice(sb.toString());

        view.setImgUrl(item.getImage().getUrl());
        view.setMarketPrice(item.getActualValue().toString());
        itemViewList.add(view);
    }

    response.setContentType("text/html;charset=UTF-8");
    Gson gson = new Gson();
    JsonObject jResponse = new JsonObject();
    JsonElement items = gson.toJsonTree(itemViewList);
    jResponse.addProperty("success", Boolean.TRUE);
    jResponse.add("items", items);

    PrintWriter out = response.getWriter();
    response.setContentType("text/html");
    response.setHeader("Cache-control", "no-cache, no-store");
    response.setHeader("Pragma", "no-cache");
    response.setHeader("Expires", "-1");

    response.setHeader("Access-Control-Allow-Origin", "*");
    response.setHeader("Access-Control-Allow-Methods", "POST");
    response.setHeader("Access-Control-Allow-Headers", "Content-Type");
    response.setHeader("Access-Control-Max-Age", "86400");
    System.out.println(jResponse.toString());
    out.println(jResponse.toString());
    out.close();
}

From source file:com.bid.online.presentation.bidmanagement.UploadFile.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from  w  ww.j  a v a2  s . c  om*/
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    String url = "";
    FileItem item = null;
    if (isMultipart) {
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        try {
            List items = upload.parseRequest(request);
            Iterator it = items.iterator();

            while (it.hasNext()) {
                item = (FileItem) it.next();
                if (!item.isFormField()) {
                    String fileName = item.getName();
                    String root = getServletContext().getRealPath("/");
                    File path = new File(root + "/uploads");
                    if (!path.exists()) {
                        boolean status = path.mkdir();
                    }
                    File uploadedFile = new File(path + "/" + fileName);
                    //System.out.println(uploadedFile.getAbsolutePath());
                    url = "uploads" + "/" + fileName;
                    item.write(uploadedFile);
                }
            }

        } catch (FileUploadException e) {

        } catch (Exception e) {

        }
        Gson gson = new Gson();
        JsonObject jResponse = new JsonObject();
        if (item != null) {
            Image img = new Image();
            img.setName(item.getName());
            img.setUrl(url);
            img = bidService.createImage(img);

            ImageView imgView = new ImageView();
            imgView.setId(String.valueOf(img.getId()));
            imgView.setName(item.getName());
            imgView.setUrl(url);
            JsonElement imgJason = gson.toJsonTree(imgView);
            jResponse.addProperty("success", Boolean.TRUE);
            jResponse.add("img", imgJason);
        } else {
            jResponse.addProperty("success", Boolean.FALSE);
        }
        PrintWriter out = response.getWriter();
        response.setContentType("text/html");
        response.setHeader("Cache-control", "no-cache, no-store");
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Expires", "-1");

        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "POST");
        response.setHeader("Access-Control-Allow-Headers", "Content-Type");
        response.setHeader("Access-Control-Max-Age", "86400");
        System.out.println(jResponse.toString());
        out.println(jResponse.toString());
        out.close();
    }
}

From source file:com.bios.controller.services.AuthenticationService.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request/*  w w  w.  j a v a2s.c o  m*/
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs This is for the web services
 * for authentication Service
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String username = request.getParameter("username");
    String password = request.getParameter("password");
    JsonObject object = new JsonObject();
    HttpSession session = request.getSession();

    if (username == null || username.length() == 0) {
        JsonArray array = new JsonArray();
        JsonPrimitive value = new JsonPrimitive("blank username");
        array.add(value);
        object.addProperty("status", "error");
        object.add("message", array);
        System.out.println(object);
        response.setContentType("application/json");
        response.getWriter().write(object.toString());
        return;
    }

    if (password == null || password.length() == 0) {
        JsonArray array = new JsonArray();
        JsonPrimitive value = new JsonPrimitive("blank password");
        array.add(value);
        object.addProperty("status", "error");
        object.add("message", array);
        System.out.println(object);
        response.setContentType("application/json");
        response.getWriter().write(object.toString());
        return;
    }

    if (username.equals("admin") && password.equals("admin")) {
        // Grant access and return token

        String token = JWTUtility.sign("abcdefgh12345678", username);
        object.addProperty("status", "success");
        object.addProperty("token", token);
        session.setAttribute("token", token);
    } else {
        JsonArray array = new JsonArray();
        JsonPrimitive value = new JsonPrimitive("invalid username/password");
        array.add(value);
        object.addProperty("status", "error");
        object.add("message", array);
    }

    System.out.println(object);
    response.setContentType("application/json");
    response.getWriter().write(object.toString());

}

From source file:com.bios.controller.services.BidStatusService.java

/**
 * Handles the HTTP <code>GET</code> method to determine whether currently
 * placed bids will be successful at the end of the round. A json object
 * that contains the live bidding data relating to the bid will be created.
 *
 * @param request servlet request//from   w w  w.  j  a  va2 s  .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 doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    ConnectionManager manager = new ConnectionManager();
    String requestObject = request.getParameter("r");
    String token = request.getParameter("token");
    ArrayList<String> errorList = new ArrayList<String>();

    JsonObject responseObject = new JsonObject();
    JsonArray allErrors = new JsonArray();

    if (requestObject == null) {
        errorList.add("missing r");
    } else if (requestObject.length() == 0) {
        errorList.add("blank r");
    }

    if (token == null) {
        errorList.add("missing token");
    } else if (token.length() == 0) {
        errorList.add("blank token");
    } else {
        try {
            String result = JWTUtility.verify(token, "abcdefgh12345678");
            if (!result.equals("admin")) {
                errorList.add("invalid token");
            }
        } catch (JWTException e) { // do we need this?
            // This means not an admin, or token expired
            errorList.add("invalid username/token");
        }
    }

    JsonElement jelementRequest = new JsonParser().parse(requestObject);
    JsonObject json = jelementRequest.getAsJsonObject();

    JsonElement crse = json.get("course");
    JsonElement sec = json.get("section");

    if (crse == null) {
        errorList.add("missing course");
    } else if (crse.getAsString().length() == 0) {
        errorList.add("blank course");
    }

    if (sec == null) {
        errorList.add("missing section");
    } else if (sec.getAsString().length() == 0) {
        errorList.add("blank section");
    }

    if (errorList.size() > 0) {
        errorList.sort(new ErrorMsgComparator());
        for (String s : errorList) {
            allErrors.add(new JsonPrimitive(s));
        }
        responseObject.addProperty("status", "error");
        responseObject.add("message", allErrors);
        response.setContentType("application/json");
        response.getWriter().write(responseObject.toString());
        return;
    }

    String courseID = crse.getAsString();
    String sectionID = sec.getAsString();

    int round = manager.getBiddingRound();
    String status = manager.getBiddingRoundStatus();

    // Section that user has selected
    Section section = SectionDAO.getInstance().findSection(courseID, sectionID);

    Course course = CourseDAO.getInstance().findCourse(courseID);
    if (course == null) {
        allErrors.add(new JsonPrimitive("invalid course"));
    } else if (course != null && section == null) {
        allErrors.add(new JsonPrimitive("invalid section"));
    }

    if (allErrors.size() > 0) {
        responseObject.addProperty("status", "error");
        responseObject.add("message", allErrors);
        response.setContentType("application/json");
        response.getWriter().write(responseObject.toString());
        return;
    }

    // How many students have already been enrolled in the section successfully
    ArrayList<SectionStudent> sectionStudentList = SectionStudentDAO.getInstance()
            .getSectionStudentListWithID(courseID, sectionID);

    // Size of the class minus the already enrolled number, which essentially means vacancy
    int vacancy = section.getSize() - sectionStudentList.size();

    // Minimum bid value that has to be shown to user, default is 10
    double minBidValue = 10;

    // This lists the bids that are still pending approval in round 2, and contains the bids
    // that user has selected, and these bids are sorted from highest to lowest
    ArrayList<Bid> allBids = BidDAO.getInstance().getPendingBidsWithID(courseID, sectionID);
    //        ArrayList<Bid> allBids= null;
    //        if (round == 1 && status.equals("started")){
    //            allBids = BidDAO.getInstance().getBidList();
    //        } else if (status.equals("stopped") && round == 1){
    //            allBids = RoundOneBidDAO.getInstance().getBidList();
    //        } else if(round == 2 && status.equals("started")){
    //            allBids = BidDAO.getInstance().getPendingBids();
    //        } else{
    //            allBids = RoundTwoBidDAO.getInstance().getBidList();
    //        }
    allBids.sort(new BidComparator());

    // This JsonObject is to be used as the reponse to the user
    JsonObject object = new JsonObject();

    object.addProperty("status", "success");
    DecimalFormat df = new DecimalFormat("0.00");
    JsonArray arrayOfBids = new JsonArray();
    if (round == 1 && status.equals("started")) {
        object.addProperty("vacancy", section.getSize());
        if (section.getSize() > allBids.size() && allBids.size() > 0) {
            minBidValue = allBids.get(allBids.size() - 1).getAmount();
        } else if (allBids.size() >= section.getSize()) {
            minBidValue = allBids.get(section.getSize() - 1).getAmount();
        }
        object.addProperty("min-bid-amount", minBidValue);
        for (Bid bid : allBids) {
            JsonObject innerObject = new JsonObject();
            Student stud = StudentDAO.getInstance().retrieve(bid.getUserID());
            innerObject.add("userid", new JsonPrimitive(bid.getUserID()));
            innerObject.add("amount", new JsonPrimitive(bid.getAmount()));
            String result = df.format(stud.geteDollar());
            double eDollar = Double.parseDouble(result);
            innerObject.add("balance", new JsonPrimitive(eDollar));
            innerObject.add("status", new JsonPrimitive("pending"));
            arrayOfBids.add(innerObject);
        }

    } else if (round == 1 && status.equals("stopped")) {
        object.addProperty("vacancy",
                section.getSize() - BidDAO.getInstance().getSuccessfulBidsWithID(courseID, sectionID).size());

        allBids = BidDAO.getInstance().getBids(courseID, sectionID);
        if (allBids.size() >= vacancy && vacancy != 0) { // should this be >=? wha if vacancy==0?
            minBidValue = allBids.get(vacancy - 1).getAmount();
        } else if (allBids.size() < vacancy && allBids.size() > 0) {
            minBidValue = allBids.get(allBids.size() - 1).getAmount();
        }
        object.addProperty("min-bid-amount", minBidValue);
        allBids = BidDAO.getInstance().getBids(courseID, sectionID);

        for (Bid bid : allBids) {
            JsonObject innerObject = new JsonObject();
            Student stud = StudentDAO.getInstance().retrieve(bid.getUserID());
            innerObject.add("userid", new JsonPrimitive(bid.getUserID()));
            innerObject.add("amount", new JsonPrimitive(bid.getAmount()));
            String result = df.format(stud.geteDollar());
            double eDollar = Double.parseDouble(result);
            innerObject.add("balance", new JsonPrimitive(eDollar));
            innerObject.add("status", new JsonPrimitive(bid.getStatus()));
            arrayOfBids.add(innerObject);
        }
    } else if (round == 2 && status.equals("started")) {
        object.addProperty("vacancy", vacancy);

        // This is to re-compute the minimum bid value
        //            if (allBids.size() >= vacancy && vacancy != 0) { // should this be >=? wha if vacancy==0?
        //                minBidValue = allBids.get(vacancy - 1).getAmount() + 1;
        //            }
        // This allows us to store the minimum bids, and also to persist the bids such that it stores the min bid amount

        if (MinBidDAO.getInstance().updateMinBid(courseID + "-" + sectionID, minBidValue)) {
            // Bid was updated successfully
            object.addProperty("min-bid-amount", minBidValue);
        } else {
            object.addProperty("min-bid-amount", MinBidDAO.getInstance().getValue(courseID + "-" + sectionID));
        }

        for (int i = 0; i < allBids.size(); i++) {
            Bid bid = allBids.get(i);
            JsonObject innerObject = new JsonObject();

            Student stud = StudentDAO.getInstance().retrieve(bid.getUserID());
            innerObject.add("userid", new JsonPrimitive(bid.getUserID()));
            innerObject.add("amount", new JsonPrimitive(bid.getAmount()));
            String result = df.format(stud.geteDollar());
            double eDollar = Double.parseDouble(result);
            innerObject.add("balance", new JsonPrimitive(eDollar));

            // If there are vacancies still
            if (vacancy >= allBids.size()) {
                innerObject.add("status", new JsonPrimitive("success"));
            } else if (allBids.size() > vacancy) {
                // If this bid is still within the vacancy requirements
                if (i <= vacancy) {
                    Bid firstFailedBid = allBids.get(vacancy);

                    if (bid.getAmount() == firstFailedBid.getAmount()) {
                        innerObject.add("status", new JsonPrimitive("fail"));
                    } else {
                        innerObject.add("status", new JsonPrimitive("success"));
                    }
                } else if (i > vacancy) { //what if vacancy+1's bid amout
                    innerObject.add("status", new JsonPrimitive("fail"));
                }
            }
            arrayOfBids.add(innerObject);
        }

    } else {
        object.addProperty("vacancy",
                section.getSize() - BidDAO.getInstance().getSuccessfulBidsWithID(courseID, sectionID).size());
        allBids = BidDAO.getInstance().getSuccessfulBidsWithID(courseID, sectionID);
        allBids.sort(new BidComparator());
        minBidValue = allBids.get(allBids.size() - 1).getAmount();
        object.addProperty("min-bid-amount", minBidValue);
        for (Bid bid : allBids) {
            JsonObject innerObject = new JsonObject();
            Student stud = StudentDAO.getInstance().retrieve(bid.getUserID());
            innerObject.add("userid", new JsonPrimitive(bid.getUserID()));
            innerObject.add("amount", new JsonPrimitive(bid.getAmount()));
            String result = df.format(stud.geteDollar());
            double eDollar = Double.parseDouble(result);
            innerObject.add("balance", new JsonPrimitive(eDollar));
            innerObject.add("status", new JsonPrimitive(bid.getStatus()));
            arrayOfBids.add(innerObject);
        }
    }

    object.add("students", arrayOfBids);

    response.setContentType("application/json");

    response.getWriter().write(object.toString());
}

From source file:com.bios.controller.services.BootstrapService.java

/**
* Handles the HTTP <code>POST</code> method to perform the bootstrap function.
* Firstly, the method checks for a valid token. If there are any errors such
* as an valid token or a missing bootstrap file, a json object with the status
* "error" is created together with a json array of the errors that caused it.
* Else if the token is valid and there are no errors, the method then
* then unzips the zip file and reads the csv files to upload the relevant data
* into the respective DAOs and database. While it does this, ArrayLists are used
* to keep track of the errors such as invalid inputs or bids that cannot be bidded
* for in round 1. If these errors exist, then the json object would contain the
* status "error" and store the errors. Otherwise, the json object will have the
* status "success" to signifiy that the bootstrap was successful with no errors.
 * @param request servlet request//from   w  w w.j  a  v a 2 s .  c o  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 {
    String token = request.getParameter("token");

    Part filePart = request.getPart("bootstrap-file"); // Retrieves <input type="file" name="file">

    JsonObject responseObject = new JsonObject();
    JsonArray allErrorsArr = new JsonArray();

    if (token == null) {
        allErrorsArr.add(new JsonPrimitive("missing token"));
    }

    if (filePart == null) {
        allErrorsArr.add(new JsonPrimitive("missing bootstrap-file"));
    }

    if (allErrorsArr.size() > 0) {
        responseObject.addProperty("status", "error");
        responseObject.add("message", allErrorsArr);
        response.setContentType("application/json");
        response.getWriter().write(responseObject.toString());
        return;
    }

    if (token.length() == 0) {
        allErrorsArr.add(new JsonPrimitive("blank token"));
    }

    if (filePart.getSize() == 0) {
        allErrorsArr.add(new JsonPrimitive("blank bootstrap-file"));
    }

    if (allErrorsArr.size() > 0) {
        responseObject.addProperty("status", "error");
        responseObject.add("message", allErrorsArr);
        response.setContentType("application/json");
        response.getWriter().write(responseObject.toString());
        return;
    }

    try {
        String result = JWTUtility.verify(token, "abcdefgh12345678");
        if (!result.equals("admin")) {
            JsonPrimitive value = new JsonPrimitive("invalid token");
            allErrorsArr.add(value);
            responseObject.addProperty("status", "error");
            responseObject.add("message", allErrorsArr);
            response.setContentType("application/json");
            response.getWriter().write(responseObject.toString());
            return;
        }
    } catch (JWTException e) {
        // This means not an admin, or token expired
        JsonPrimitive value = new JsonPrimitive("invalid username/token");
        allErrorsArr.add(value);
        responseObject.addProperty("status", "error");
        responseObject.add("message", allErrorsArr);
        response.setContentType("application/json");
        response.getWriter().write(responseObject.toString());
        return;
    }

    InputStream inputStream = filePart.getInputStream();
    ServletContext context = getServletContext();

    //Uploaded to a file called bootstrap.zip
    File f = new File(context.getRealPath("/WEB-INF") + "/bootstrap.zip");
    OutputStream outputStream = new FileOutputStream(f);

    int read = 0;
    byte[] bytes = new byte[1024];
    //the total number of bytes read into the buffer, or -1 if there is no more data because the end of the stream has been reached
    //
    while ((read = inputStream.read(bytes)) != -1) {
        outputStream.write(bytes, 0, read);
    }

    if (inputStream != null) {
        try {
            inputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    if (outputStream != null) {
        try {
            outputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //TODO if the folder structure is invalid, let user know that nothing was uploaded
    //BootstrapValidator validator = new BootstrapValidator();
    ConnectionManager manager = new ConnectionManager();
    manager.deleteAllTables();

    BootstrapUnzipper unzipper = new BootstrapUnzipper();
    unzipper.unzip(context);

    BootstrapCSVReader csvReader = new BootstrapCSVReader();

    ArrayList<DataError> allCourses = csvReader.retrieveCourses(context);
    ArrayList<DataError> allSections = csvReader.retrieveSections(context);
    ArrayList<DataError> allStudents = csvReader.retrieveStudents(context);
    ArrayList<DataError> allPrerequisites = csvReader.retrievePrerequisites(context);
    ArrayList<DataError> allCompletedCourses = csvReader.retrieveCompletedCourses(context);
    ArrayList<DataError> allBids = csvReader.retrieveBids(context);
    ArrayList<ArrayList<DataError>> listOfErrors = new ArrayList<>();
    listOfErrors.add(allBids);
    listOfErrors.add(allCourses);
    listOfErrors.add(allCompletedCourses);
    listOfErrors.add(allPrerequisites);
    listOfErrors.add(allSections);
    listOfErrors.add(allStudents);

    JsonObject object = new JsonObject();

    if (!allCourses.isEmpty() || !allSections.isEmpty() || !allStudents.isEmpty() || !allBids.isEmpty()
            || !allPrerequisites.isEmpty() || !allCompletedCourses.isEmpty()) {
        object.add("status", new JsonPrimitive("error"));
    } else {
        object.add("status", new JsonPrimitive("success"));
    }

    int[] totalLines = csvReader.getTotalLines();
    int[] totalErrorLines = csvReader.getTotalErrorLines();
    String[] allHeaders = new String[] { "bid.csv", "course.csv", "course_completed.csv", "prerequisite.csv",
            "section.csv", "student.csv" };

    JsonObject item = new JsonObject();
    JsonArray itemArr = new JsonArray();

    item.add("bid.csv", new JsonPrimitive(totalLines[3] - totalErrorLines[3]));
    itemArr.add(item);
    item = new JsonObject();
    item.add("course.csv", new JsonPrimitive(totalLines[0] - totalErrorLines[0]));
    itemArr.add(item);
    item = new JsonObject();
    item.add("course_completed.csv", new JsonPrimitive(totalLines[5] - totalErrorLines[5]));
    itemArr.add(item);
    item = new JsonObject();
    item.add("prerequisite.csv", new JsonPrimitive(totalLines[4] - totalErrorLines[4]));
    itemArr.add(item);
    item = new JsonObject();
    item.add("section.csv", new JsonPrimitive(totalLines[1] - totalErrorLines[1]));
    itemArr.add(item);
    item = new JsonObject();
    item.add("student.csv", new JsonPrimitive(totalLines[2] - totalErrorLines[2]));
    itemArr.add(item);

    object.add("num-record-loaded", itemArr);

    LinkedHashMap<String, ArrayList<DataError>> allErrorMsgs = new LinkedHashMap<>();
    ArrayList<JsonObject> allErrorsArrList = new ArrayList<>();

    JsonArray allErrors = new JsonArray();
    //System.out.println(object.get("status").getAsString().equals("error"));
    if (object.get("status").getAsString().equals("error")) {

        for (int i = 0; i < allHeaders.length; i++) {

            ArrayList<DataError> list = listOfErrors.get(i);
            for (int j = 0; j < list.size(); j++) {
                DataError de = list.get(j);

                if (!allErrorMsgs.containsKey(de.getLineNum() + "")) {
                    ArrayList<DataError> l = new ArrayList<>();
                    l.add(de);
                    allErrorMsgs.put(de.getLineNum() + "", l);
                } else {
                    allErrorMsgs.get(de.getLineNum() + "").add(de);
                }
            }

            Iterator<Entry<String, ArrayList<DataError>>> iter = allErrorMsgs.entrySet().iterator();
            while (iter.hasNext()) {
                Entry<String, ArrayList<DataError>> m = iter.next();
                ArrayList<DataError> errorList = m.getValue();
                JsonObject error = new JsonObject();

                error.add("file", new JsonPrimitive(allHeaders[i]));

                JsonArray errMsgs = new JsonArray();

                for (DataError err : errorList) {
                    error.add("line", new JsonPrimitive(err.getLineNum()));
                    errMsgs.add(new JsonPrimitive(err.getDescription()));
                }

                error.add("message", errMsgs);
                allErrors.add(error);
            }
            allErrorMsgs = new LinkedHashMap<>();

        }

    }

    if (allErrors.size() > 0) {
        object.add("error", allErrors);
    }
    MinBidDAO.getInstance().drop();
    MinBidDAO.getInstance().refresh();

    response.setContentType("application/json");
    response.getWriter().write(object.toString());
}

From source file:com.bios.controller.services.DeleteBidService.java

/**
 * Handles the HTTP <code>GET</code> method and deletes the bid. It retrieves the userID, courseID, section ID, and amount bidded to verify the bid.
 * Upon verification, the bid will be deleted from bidDAO and database. Upon successful deletion, a json object is created with the
 * status "success". If the bid deletion is unsuccessful, a json object with the status "error" is created together with a
 * json array of the errors that caused the unsuccessful deletion.
 *
 * @param request servlet request/*from  w  ww.  j a v  a 2s .  com*/
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    ConnectionManager manager = new ConnectionManager();
    String requestObject = request.getParameter("r");
    String token = request.getParameter("token");
    ArrayList<String> errorList = new ArrayList<String>();

    JsonObject responseObject = new JsonObject();
    JsonArray allErrors = new JsonArray();

    if (requestObject == null) {
        errorList.add("missing r");
    } else if (requestObject.length() == 0) {
        errorList.add("blank r");
    }

    if (token == null) {
        errorList.add("missing token");
    } else if (token.length() == 0) {
        errorList.add("blank token");
    } else {
        try {
            String result = JWTUtility.verify(token, "abcdefgh12345678");
            if (!result.equals("admin")) {
                errorList.add("invalid token");
            }
        } catch (JWTException e) { // do we need this?
            // This means not an admin, or token expired
            errorList.add("invalid username/token");
        }
    }

    JsonElement jelementRequest = new JsonParser().parse(requestObject);
    JsonObject json = jelementRequest.getAsJsonObject();

    JsonElement crse = json.get("course");
    JsonElement sec = json.get("section");
    JsonElement user = json.get("userid");

    if (crse == null) {
        errorList.add("missing course");
    } else if (crse.getAsString().length() == 0) {
        errorList.add("blank course");
    }

    if (sec == null) {
        errorList.add("missing section");
    } else if (sec.getAsString().length() == 0) {
        errorList.add("blank section");
    }

    if (user == null) {
        errorList.add("missing userid");
    } else if (user.getAsString().length() == 0) {
        errorList.add("blank userid");
    }

    if (errorList.size() > 0) {
        errorList.sort(new ErrorMsgComparator());
        for (String s : errorList) {
            allErrors.add(new JsonPrimitive(s));
        }
        responseObject.addProperty("status", "error");
        responseObject.add("message", allErrors);
        response.setContentType("application/json");
        response.getWriter().write(responseObject.toString());
        return;
    }

    String courseID = crse.getAsString();
    String sectionID = sec.getAsString();
    String userID = user.getAsString();

    BidDAO bidDAO = BidDAO.getInstance();
    CourseDAO courseDAO = CourseDAO.getInstance();
    SectionDAO sectionDAO = SectionDAO.getInstance();
    StudentDAO studentDAO = StudentDAO.getInstance();

    String roundStatus = manager.getBiddingRoundStatus();
    Bid bid = bidDAO.getBid(userID, courseID, sectionID);

    if (roundStatus.equals("stopped") || !bidDAO.deleteBid(userID, courseID, sectionID)) {
        responseObject.addProperty("status", "error");
        if (courseDAO.findCourse(courseID) == null) {
            allErrors.add(new JsonPrimitive("invalid course"));
        }
        if (sectionDAO.findSection(courseID, sectionID) == null) {
            allErrors.add(new JsonPrimitive("invalid section"));
        }
        if (studentDAO.findStudent(userID) == null) {
            allErrors.add(new JsonPrimitive("invalid userid"));
        }
        if (roundStatus.equals("stopped")) {
            allErrors.add(new JsonPrimitive("round ended"));
        }

        if (roundStatus.equals("started") && allErrors.size() == 0) {
            allErrors.add(new JsonPrimitive("no such bid"));
        }
        responseObject.add("message", allErrors);

        response.setContentType("application/json");
        response.getWriter().write(responseObject.toString());
        return;
    } else {
        // no errors detected in the deletion of bids
        MinBidDAO.getInstance().getMinBidList().remove(courseID + "-" + sectionID);
        MinBidDAO.getInstance().refresh();
        responseObject.addProperty("status", "success");
        Student stud = studentDAO.retrieve(userID);
        stud.seteDollar(stud.geteDollar() + bid.getAmount());
        manager.refundEDollar(userID, bid.getAmount());
        bidDAO.deleteBidFromDB(userID, courseID, sectionID);
    }

    response.setContentType("application/json");
    response.getWriter().write(responseObject.toString());
}