Example usage for com.google.gson JsonElement getAsString

List of usage examples for com.google.gson JsonElement getAsString

Introduction

In this page you can find the example usage for com.google.gson JsonElement getAsString.

Prototype

public String getAsString() 

Source Link

Document

convenience method to get this element as a string value.

Usage

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 w w  .j  av a 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 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());
}

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

/**
 * Handles the HTTP <code>GET</code> method by allowing the administrator to drop a user's
 * enrollment in a section. This web service requires a valid token userid, course and section,
 * and a bid of the student, that was successful. The bid can only be dropped if the round 2 is active.
 * If succesful, a json object with the status "success" will be created. Otherwise, this method creates a
 * json object with the status "error" and with a json array of the errors that caused the unsuccessful
 * dropping of the section./*from  w w  w .  j  a  v a 2  s  .co  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
 */
@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;
    }

    Student stud = StudentDAO.getInstance().retrieve(user.getAsString());
    Course c = CourseDAO.getInstance().findCourse(crse.getAsString());
    SectionStudent toBeDropped = SectionStudentDAO.getInstance().findSectionStudent(crse.getAsString(),
            sec.getAsString(), user.getAsString());
    Section s = SectionDAO.getInstance().findSection(crse.getAsString(), sec.getAsString());

    if (c == null) {
        allErrors.add(new JsonPrimitive("invalid course"));
    } else if (s == null) {
        allErrors.add(new JsonPrimitive("invalid section"));
    }
    if (stud == null) {
        allErrors.add(new JsonPrimitive("invalid userid"));
    }

    if (manager.getBiddingRound() == 2 && manager.getBiddingRoundStatus().equals("started")) {
        if (user != null) {
            if (toBeDropped != null) {
                double currAmount = stud.geteDollar();
                double amountFromDropping = toBeDropped.getAmount();
                double finalAmount = currAmount + amountFromDropping;

                manager.setEDollar(user.getAsString(), finalAmount);

                String userid = user.getAsString();
                String courseID = crse.getAsString();
                String sectionID = sec.getAsString();
                SectionStudentDAO.getInstance().deleteStudentSection(userid, amountFromDropping, courseID,
                        sectionID);
                SectionStudentDAO.getInstance().deleteStudentSectionFromDB(userid, amountFromDropping, courseID,
                        sectionID);
                BidDAO.getInstance().deleteBid(userid, courseID, sectionID);
                BidDAO.getInstance().deleteBidFromDB(userid, courseID, sectionID);

                responseObject.addProperty("status", "success");
            } else {
                JsonPrimitive value = new JsonPrimitive("no such enrollment record");
                allErrors.add(value);
                responseObject.addProperty("status", "error");
                responseObject.add("message", allErrors);
            }
        }

    } else {
        //round not active
        JsonPrimitive value = new JsonPrimitive("round not active");
        allErrors.add(value);
        responseObject.addProperty("status", "error");
        responseObject.add("message", allErrors);
    }
    response.setContentType("application/json");
    response.getWriter().write(responseObject.toString());
}

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

/**
 * Handles the HTTP <code>GET</code> method which utilises a courseid and sectionid and a token of an administrator. After the courseid and
 * secitonid and token of the administrator is passed in, the method first verifies that the token is valid. If the token is valid, the
 * method checks the respective DAOs and retrieves the respective information of the bids placed and places it in the json object. If an
 * error occurs, such as a missing input, a json object is created with the status "error" with the error message respective to the error that
 * caused the unsuccessful dump./* www  .java  2s .  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
 */
@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");
        }
    }

    JsonArray allBids = new JsonArray();

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

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

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

    if (section == null) {
        errorList.add("missing section");
    } else if (section.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;
    }

    ArrayList<Section> sectionList = SectionDAO.getInstance().getSectionList();
    Section s = SectionDAO.getInstance().findSection(course.getAsString(), section.getAsString());
    Course c = CourseDAO.getInstance().findCourse(course.getAsString());

    if (c == null) {
        JsonPrimitive value = new JsonPrimitive("invalid course");
        allErrors.add(value);
        responseObject.addProperty("status", "error");
        responseObject.add("message", allErrors);
    } else if (c != null && s == null) {
        JsonPrimitive value = new JsonPrimitive("invalid course");
        allErrors.add(value);
        responseObject.addProperty("status", "error");
        responseObject.add("message", allErrors);
    }

    int round = manager.getBiddingRound();
    String status = manager.getBiddingRoundStatus();
    //
    //        //round active: status is '-'
    //        if (c != null && s != null && status.equals("started")) {
    //            responseObject.addProperty("status", "success");
    //            BidDAO bidDAO = BidDAO.getInstance();
    //            ArrayList<Bid> successBids = bidDAO.getSuccessfulBidsWithID(c.getCourseID(), s.getSectionID());
    //            Collections.sort(successBids, new BidComparator());
    //            //arrange the names in ascending order - undone
    //            if (successBids.size() == 0) {
    //                System.out.println("PENDING:" + successBids.size());
    //            }
    //            for (int i = 0; i < successBids.size(); i++) {
    //                Bid currBid = successBids.get(i);
    //                System.out.println("Bid: " + currBid.getStatus());
    //                JsonObject obj = new JsonObject();
    //                obj.add("row", new JsonPrimitive((i + 1)));
    //                obj.add("userid", new JsonPrimitive(currBid.getUserID()));
    //                obj.add("amount", new JsonPrimitive(currBid.getAmount()));
    //                obj.add("result", new JsonPrimitive("-"));
    //
    //                allActiveBids.add(obj);
    //            }
    //
    //            responseObject.add("bids", allActiveBids);
    //
    //        } else if (c != null && s != null && status.equals("stopped")) {//notactive: status is successful/unsuccessful; bids should be in an array
    //            responseObject.addProperty("status", "success");
    //            ArrayList<Bid> allBids = BidDAO.getInstance().getBids(c.getCourseID(), s.getSectionID());
    //            allBids.sort(new BidComparator());
    //
    //            for (int i = 0; i < allBids.size(); i++) {
    //                Bid bid = allBids.get(i);
    //
    //                JsonObject obj = new JsonObject();
    //
    //                obj.add("row", new JsonPrimitive((i + 1)));
    //                obj.add("userid", new JsonPrimitive(bid.getUserID()));
    //                obj.add("amount", new JsonPrimitive(bid.getAmount()));
    //                if (bid.getStatus().equals("success")) {
    //                    obj.add("result", new JsonPrimitive("in"));
    //                } else {
    //                    obj.add("result", new JsonPrimitive("out"));
    //                }
    //                allInactiveBids.add(obj);
    //            }
    //
    //            responseObject.add("bids", allInactiveBids);
    //        }

    ArrayList<Bid> bidList = null;
    if (round == 1 && status.equals("started")) {
        bidList = BidDAO.getInstance().getBidList();
    } else if (status.equals("stopped") && round == 1) {
        bidList = RoundOneBidDAO.getInstance().getBidList();
    } else if (round == 2 && status.equals("started")) {
        bidList = BidDAO.getInstance().getPendingBids();
    } else {
        bidList = RoundTwoBidDAO.getInstance().getBidList();
    }

    bidList.sort(new BidComparator());
    System.out.println("BIDLIST: " + bidList.size());
    int count = 1;

    for (int i = 0; i < bidList.size(); i++) {
        Bid bid = bidList.get(i);

        if (bid.getCourseID().equals(course.getAsString())
                && bid.getSectionID().equals(section.getAsString())) {
            JsonObject obj = new JsonObject();

            obj.add("row", new JsonPrimitive(count));
            obj.add("userid", new JsonPrimitive(bid.getUserID()));
            obj.add("amount", new JsonPrimitive(bid.getAmount()));
            if (bid.getStatus().equals("pending")) {
                obj.add("result", new JsonPrimitive("-"));
            } else if (bid.getStatus().equals("success")) {
                obj.add("result", new JsonPrimitive("in"));
            } else {
                obj.add("result", new JsonPrimitive("out"));
            }
            allBids.add(obj);
            count++;
        }

    }
    responseObject.addProperty("status", "success");
    responseObject.add("bids", allBids);
    response.setContentType("application/json");
    response.getWriter().write(responseObject.toString());
}

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

/**
   * Handles the HTTP <code>GET</code> method which uses the courseid, a sectionid and  token of an administrator. After the
   * courseid, sectionid and token of the administrator is obtained, the method first verifies that the token is valid and present in the session
   * object. Subsequently, if  the token is valid, the method checks the respective DAOs and retrieves the respective information of the bids of
   * that particular courses section and places it in a json object. If an error occurs, such as a missing input, a json object will be created
   * with the status "error" and will reflect the errors in a json array within the object.
   * @param request servlet request//from www . j  a v a2s. 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 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();

    // Will now check to see if there are any errors here
    Course course = CourseDAO.getInstance().findCourse(crse.getAsString());
    Section section = null;
    if (course == null) {
        allErrors.add(new JsonPrimitive("invalid course"));
    } else {
        section = SectionDAO.getInstance().findSection(course.getCourseID(), sec.getAsString());
        if (section == null) {
            allErrors.add(new JsonPrimitive("invalid section"));
        }
    }

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

    JsonArray allResults = new JsonArray();
    ArrayList<SectionStudent> allSecStudList = SectionStudentDAO.getInstance()
            .getSectionStudentListWithID(crse.getAsString(), sec.getAsString());
    ArrayList<SectionStudent> secStudList = new ArrayList<>();

    for (SectionStudent secStud : allSecStudList) {
        if (secStud.getCourseID().equals(courseID) && secStud.getSectionID().equals(sectionID)) {
            secStudList.add(secStud);
        }
        //            String cID = secStud.getCourseID();
        //            String sID = secStud.getSectionID();
        //
        //            ArrayList<Bid> halfBids = new ArrayList<>();
        //            if (round == 1 || round == 2 && status.equals("started")) {
        //                halfBids = BidDAO.getInstance().getSuccessfulBidsWithID(cID, sID);
        //            } else if (round == 2 && status.equals("stopped")) {
        //                halfBids = BidDAO.getInstance().getBids(sID, sID);
        //            }
        //            allBids.addAll(halfBids);
    }

    secStudList.sort(new SectionStudentComparator());
    for (SectionStudent secStud : secStudList) {
        JsonObject obj = new JsonObject();
        obj.addProperty("userid", secStud.getUserID());
        obj.addProperty("amount", secStud.getAmount());
        allResults.add(obj);
    }

    //        // After we sort all the bids, then we shall add them to be responded to
    //        allBids.sort(new BidUserComparator());
    //        for (Bid bid : allBids) {
    //            JsonObject obj = new JsonObject();
    //            obj.add("userid", new JsonPrimitive(bid.getUserID()));
    //            obj.add("amount", new JsonPrimitive(bid.getAmount()));
    //            allResults.add(obj);
    //        }

    responseObject.add("status", new JsonPrimitive("success"));
    responseObject.add("students", allResults);

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

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

/**
* Handles the HTTP <code>GET</code> method which takes in the userid of a
* user and a token of an administrator. After the userid of the student and
* token of the administrator is passed in, the method first verifies that
* the token is valid. If the token is invalid, a json object is created
* with the status "error" and an error message "invalid username/token".
* Subsequently, if the token is valid, the method checks the respective
* DAOs and retrieves the respective information of the user and places it
* in the json object. If an error occurs, such as a missing input, the json
* object will also reflect the error without displaying the user's
* information.//ww  w .j a  v a2 s .c  o  m
 * @param request servlet requesty
 * @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 userID = json.get("userid");

    if (userID == null) {
        errorList.add("missing userid");
    } else if (userID.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;
    }

    Student s = StudentDAO.getInstance().retrieve(userID.getAsString());

    if (s == null) {
        allErrors.add(new JsonPrimitive("invalid userid"));
        responseObject.addProperty("status", "error");
        responseObject.add("message", allErrors);
        response.setContentType("application/json");
        response.getWriter().write(responseObject.toString());
        return;
    } else {
        responseObject.addProperty("status", "success");
        responseObject.addProperty("userid", s.getId());
        responseObject.addProperty("password", s.getPassword());
        responseObject.addProperty("name", s.getNameOfUser());
        responseObject.addProperty("school", s.getSchool());
        DecimalFormat df = new DecimalFormat("0.00");
        String result = df.format(s.geteDollar());
        double eDollar = Double.parseDouble(result);
        responseObject.addProperty("edollar", eDollar);
    }

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

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

/**
* Handles the HTTP <code>GET</code> method which updates a bid. Firstly, the token
* is checked for its validity. If the token is valid, the method then goes into the
* respective DAOs to look for the bid. If the bid is valid and can be deleted, the
* bid is then deleted from the DAO and the database. Subsequentyly, a json object
* with the status "success" will be created. If any errors occur such as an
* invalid course or missing token is detected, a json object with the status "error"
* will be created with a json array of the erros that caused the failure to update.
* @param request servlet request/*w w w.  ja v  a2s  .  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 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 reponseObject = 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 jelement = new JsonParser().parse(requestObject);
    JsonObject json = jelement.getAsJsonObject();
    Bid existingBid = null;

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

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

    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));
        }
        reponseObject.addProperty("status", "error");
        reponseObject.add("message", allErrors);
        response.setContentType("application/json");
        response.getWriter().write(reponseObject.toString());
        return;
    }

    // There may be type errors for the double here
    double amount = amt.getAsDouble();
    String courseID = crse.getAsString();
    String sectionID = sec.getAsString();
    String userID = user.getAsString();

    Course course = CourseDAO.getInstance().findCourse(courseID);
    Section section = SectionDAO.getInstance().findSection(courseID, sectionID);
    Student student = StudentDAO.retrieve(userID);

    int round = manager.getBiddingRound();
    BootstrapValidator bv = new BootstrapValidator();
    if (bv.parseBidAmount(amt.getAsString()) != null) {
        allErrors.add(new JsonPrimitive("invalid amount"));
    }

    if (course == null) {
        allErrors.add(new JsonPrimitive("invalid course"));
    }

    // only check if course code is valid
    if (course != null && section == null) {
        allErrors.add(new JsonPrimitive("invalid section"));
    }

    if (student == null) {
        allErrors.add(new JsonPrimitive("invalid userid"));
    }

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

    if (manager.getBiddingRoundStatus().equals("started")) {
        if (round == 2) {
            double minBidAmt = MinBidDAO.getInstance().getValue(courseID + "-" + sectionID);
            System.out.println(courseID + "-" + sectionID);
            System.out.println("UPDATE amount: " + amount);
            System.out.println("UPDATE min bid: " + minBidAmt);
            if (amount < minBidAmt) {
                errorList.add("bid too low");
            }
        } else if (round == 1) {
            if (amount < 10) {
                errorList.add("bid too low");
            }
        }

        existingBid = BidDAO.getInstance().getStudentBidWithCourseID(userID, courseID);
        //no existing bid
        if (existingBid == null) {
            if (bv.parseEDollarEnough(userID, courseID, sectionID, amt.getAsString()) != null) {
                errorList.add("insufficient e$");
            }
        } else if (existingBid.getStatus().equals("pending")) {
            if (bv.parseEDollarEnoughExistingBid(userID, courseID, sectionID, amt.getAsString()) != null) {
                // Think too much alr, this line is not needed
                //                    errorList.add("insufficient e$");
            }
        } else if (existingBid.getStatus().equals("success")) {
            errorList.add("course enrolled");
        }

        if (bv.parseClassTimeTableClash(userID, courseID, sectionID) != null) {
            errorList.add("class timetable clash");
        }

        if (bv.parseExamTimeTableClash(userID, courseID, sectionID) != null) {
            errorList.add("exam timetable clash");
        }

        if (bv.parseIncompletePrerequisite(userID, courseID) != null) {
            errorList.add("incomplete prerequisites");
        }

        if (bv.parseAlreadyComplete(userID, courseID) != null) {
            errorList.add("course completed");
        }

        if (bv.parseSectionLimit(userID, courseID, sectionID) != null) {
            errorList.add("section limit reached");
        }

        if (bv.parseNotOwnSchoolCourse(userID, courseID) != null) {
            errorList.add("not own school course");
        }

        ArrayList<SectionStudent> sectionStudentList = SectionStudentDAO.getInstance()
                .getSectionStudentListWithID(courseID, sectionID);
        int vacancy = section.getSize() - sectionStudentList.size();
        if (vacancy <= 0) {
            errorList.add("no vacancy");
        }
    } else {
        errorList.add("round ended");
    }

    if (errorList.size() > 0) {
        Collections.sort(errorList);
        for (String s : errorList) {
            allErrors.add(new JsonPrimitive(s));
        }
        reponseObject.addProperty("status", "error");
        reponseObject.add("message", allErrors);
        response.setContentType("application/json");
        response.getWriter().write(reponseObject.toString());
        return;
    } else { //success state
        Bid newBid = new Bid(userID, amount, courseID, sectionID, "pending");
        if (existingBid != null) { //there is an existing bid
            MinBidDAO.getInstance().getMinBidList().remove(courseID + "-" + sectionID);
            MinBidDAO.getInstance().refresh();
            BidPlacementServlet.updateCurrentBid(userID, courseID, sectionID, amount, student);
        } else {
            student.seteDollar(student.geteDollar() - amount);
            manager.setEDollar(userID, student.geteDollar());
            BidDAO.getInstance().addBid(newBid);
            manager.addBid(newBid);
            //dk if this is needed
            if (round == 1) {
                RoundOneBidDAO.getInstance().addBid(newBid);
            } else if (round == 2) {
                RoundTwoBidDAO.getInstance().addBid(newBid);
            }
        }
        MinBidDAO.getInstance().refresh();
        reponseObject.addProperty("status", "success");
    }

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

From source file:com.birbit.jsonapi.JsonApiResourceDeserializer.java

License:Apache License

private void parseLinks(JsonDeserializationContext context, T t, JsonObject jsonObject)
        throws IllegalAccessException, InvocationTargetException {
    JsonElement links = jsonObject.get("links");
    if (links != null && links.isJsonObject()) {
        JsonObject linksObject = links.getAsJsonObject();
        Setter linksObjectSetter = linkSetters.get("");
        if (linksObjectSetter != null) {
            linksObjectSetter.setOnObject(t, context.deserialize(links, JsonApiLinks.class));
        }//  www .j  av  a 2 s.com
        for (Map.Entry<String, Setter> entry : linkSetters.entrySet()) {
            JsonElement link = linksObject.get(entry.getKey());
            if (link != null && link.isJsonPrimitive()) {
                entry.getValue().setOnObject(t, link.getAsString());
            }
        }
    }
}

From source file:com.birbit.jsonapi.JsonApiResourceDeserializer.java

License:Apache License

private void parseRelationships(JsonDeserializationContext context, T t, JsonObject jsonObject)
        throws IllegalAccessException, InvocationTargetException {
    JsonElement relationships = jsonObject.get("relationships");
    if (relationships != null && relationships.isJsonObject()) {
        JsonObject relationshipsObject = relationships.getAsJsonObject();
        for (Map.Entry<String, Setter> entry : relationshipSetters.entrySet()) {
            JsonElement relationship = relationshipsObject.get(entry.getKey());
            if (relationship != null && relationship.isJsonObject()) {
                if (entry.getValue().type() == JsonApiRelationshipList.class) {
                    entry.getValue().setOnObject(t,
                            context.deserialize(relationship, JsonApiRelationshipList.class));
                } else if (entry.getValue().type() == JsonApiRelationship.class) { // JsonApiRelationship
                    entry.getValue().setOnObject(t,
                            context.deserialize(relationship, JsonApiRelationship.class));
                } else { // String list or id
                    JsonElement data = relationship.getAsJsonObject().get("data");
                    if (data != null) {
                        if (data.isJsonObject()) {
                            JsonElement relationshipIdElement = data.getAsJsonObject().get("id");
                            if (relationshipIdElement != null) {
                                if (relationshipIdElement.isJsonPrimitive()) {
                                    entry.getValue().setOnObject(t, relationshipIdElement.getAsString());
                                }/*w ww .  j  a  va 2  s.  c o m*/
                            }
                        } else if (data.isJsonArray()) {
                            List<String> idList = parseIds(data.getAsJsonArray());
                            entry.getValue().setOnObject(t, idList);
                        }
                    }
                }
            }
        }
    }
}

From source file:com.birbit.jsonapi.JsonApiResourceDeserializer.java

License:Apache License

private List<String> parseIds(JsonArray jsonArray) {
    List<String> result = new ArrayList<String>(jsonArray.size());
    for (int i = 0; i < jsonArray.size(); i++) {
        JsonElement item = jsonArray.get(i);
        if (item.isJsonObject()) {
            JsonElement idField = item.getAsJsonObject().get("id");
            if (idField != null && idField.isJsonPrimitive()) {
                result.add(idField.getAsString());
            }//from w w  w  . ja v a  2  s  . c  o  m
        }
    }
    return result;
}

From source file:com.bizosys.dataservice.sql.KVPairsSerde.java

License:Apache License

public static final void deserJson(final String jsonStr, final Map<String, String> container) {

    if (StringUtils.isEmpty(jsonStr))
        return;//  w w  w . j  av  a  2s .  c  o  m

    Gson gson = new Gson();
    JsonElement jsonElem = gson.fromJson(jsonStr, JsonElement.class);
    JsonObject jsonObj = jsonElem.getAsJsonObject();

    if (!jsonObj.has("variables"))
        return;

    Iterator<JsonElement> variablesIterator = jsonObj.get("variables").getAsJsonArray().iterator();

    while (variablesIterator.hasNext()) {
        JsonObject variableObj = (JsonObject) variablesIterator.next();

        if (variableObj.has("key") && variableObj.has("value")) {
            String varKey = variableObj.get("key").getAsString();
            JsonElement obj = variableObj.get("value");
            String varVal = (obj.isJsonNull()) ? null : obj.getAsString();
            container.put(varKey, varVal);
        }
    }
    if (LOG.isDebugEnabled())
        LOG.debug("Parsed variables are : " + container.toString());
}