Example usage for com.google.gson JsonParser JsonParser

List of usage examples for com.google.gson JsonParser JsonParser

Introduction

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

Prototype

@Deprecated
public JsonParser() 

Source Link

Usage

From source file:com.bedatadriven.rebar.appcache.server.DefaultSelectionServlet.java

License:Apache License

private JsonArray readPermutationMap(Path path) {
    try {//from  w w w  .j  a v a 2s.  c o  m
        InputStreamReader reader = new InputStreamReader(
                new FileInputStream(getServletContext().getRealPath(path.moduleBase + "permutations")));

        JsonParser parser = new JsonParser();
        return (JsonArray) parser.parse(reader);

    } catch (FileNotFoundException e) {
        logger.info(
                "No permutations map found, (we are probably in dev mode) will return default selection script");
        return null;
    }
}

From source file:com.betafase.mcmanager.utils.spiget.ServerRequest.java

/**
 * Converts the raw String to a JsonElement.
 *
 * @return The converted JsonElement/*w ww.  java  2 s . co m*/
 */
public JsonElement getAsJsonElement() {
    if (result == null) {
        JsonObject o = new JsonObject();
        o.addProperty("result", "error");
        o.addProperty("description", "Connection failed!");
        return o;
    }
    return new JsonParser().parse(result);
}

From source file:com.betafase.mcmanager.utils.Updater.java

License:Creative Commons License

public boolean hasUpdate() {
    try {/*  w  w  w  . ja  v  a  2 s .  c o  m*/
        PluginDescriptionFile f = plugin.getDescription();
        URL obj = new URL("https://api.betafase.com/plugins/" + f.getName() + "/version");
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();
        con.setRequestMethod("GET");
        con.setRequestProperty("User-Agent", "Mozilla/5.0");
        con.setInstanceFollowRedirects(true);

        int responseCode = con.getResponseCode();
        System.out.println("[" + plugin.getName() + "] Checking for updates");
        if (responseCode != 200) {
            System.out.println("[" + plugin.getName() + "] Response Code : " + responseCode);
            return false;
        }
        BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
        String inputLine;
        StringBuilder response = new StringBuilder();

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();
        inputLine = response.toString();
        if (inputLine == null) {
            throw new IOException("Could not read Data");
        }
        JsonElement element = new JsonParser().parse(inputLine);
        JsonObject object = element.getAsJsonObject();
        newVersion = object.get("version").getAsString();
        currentVersion = f.getVersion();
        if (!newVersion.equalsIgnoreCase(currentVersion)) {
            newTitle = object.get("title").getAsString();
            newDescription_en = object.get("description_en").getAsString();
            System.out.println("[" + plugin.getName() + "] An Update was found: v" + newVersion);
            return true;
        }
        System.out.println("[" + plugin.getName() + "] You are running the lastest version.");
        return false;
    } catch (Exception ex) {
        System.out.println("[" + plugin.getName() + "] Failed to check for updates: " + ex.getMessage());
        ex.printStackTrace();
        return false;
    }
}

From source file:com.bhuwan.eventregistration.business.boundary.EventRegistrationResource.java

@GET
public Response getAllEventData() throws FileNotFoundException, IOException {
    String path = getClass().getClassLoader().getResource("/eventdata/").getPath();
    File eventDataDirectory = new File(path);
    String[] list = eventDataDirectory.list();
    JsonArray array = new JsonArray();
    for (String fileName : list) {
        array.add(new JsonParser().parse(FileUtils.readFileToString(Paths.get(path + fileName).toFile())));
    }//from ww w.  j av  a2  s . co m
    return Response.ok(array.toString()).header("Access-Control-Allow-Origin", "*").build();
}

From source file:com.bhuwan.eventregistration.business.boundary.EventRegistrationResource.java

@GET
public Response getMaxEventId() throws FileNotFoundException, IOException {
    String path = getClass().getClassLoader().getResource("/eventdata/").getPath();
    File eventDataDirectory = new File(path);
    String[] list = eventDataDirectory.list();
    JsonArray array = new JsonArray();
    for (String fileName : list) {
        array.add(new JsonParser().parse(FileUtils.readFileToString(Paths.get(path + fileName).toFile())));
    }// w ww .ja va2s.  c  o  m
    return Response.ok(array.toString()).header("Access-Control-Allow-Origin", "*").build();
}

From source file:com.bicitools.ws.ConsumeServicios.java

public static RespuestaJson consumeTiempoDist(Object st) {
    RespuestaNuevoJson out = new RespuestaNuevoJson();
    RespuestaJson output = new RespuestaJson();
    try {//from w  w w.  ja v  a2  s .  c  om

        ClientConfig clientConfig = new DefaultClientConfig();
        clientConfig.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);
        Client client = Client.create(clientConfig);
        WebResource webResource = client.resource(
                "http://localhost:8080/bicitoolsRU/webresources/myresource/ObtenerDistanciaTiempoRuta");

        ClientResponse response = webResource.accept("application/json").type("application/json")
                .post(ClientResponse.class, st);

        if (response.getStatus() != 200) {
            output = ConstruyeRespuesta.construyeRespuestaFalla("Fallo 200");

        }
        String json = response.getEntity(String.class);
        Gson gson = new Gson();

        JsonParser jParser = new JsonParser();
        JsonObject jObject = (JsonObject) jParser.parse(json);

        JsonElement elem = jObject.get("codigo");
        JsonElement elem2 = jObject.get("valor");
        JsonElement elem3 = jObject.get("data");
        JsonElement elem4 = jObject.get("descripcion");
        JsonObject jObjectInterno = (JsonObject) jParser.parse(elem3.toString());

        JsonElement elem5 = jObjectInterno.get("tiempo");
        JsonElement elem6 = jObjectInterno.get("distancia");

        TiempoDistanciaInfo t = new TiempoDistanciaInfo(elem5.toString(), elem6.toString());
        ArrayList datos = new ArrayList();

        //RespuestaNuevoJson info = gson.fromJson(json, RespuestaNuevoJson.class);
        //System.out.println("");
        output.setCodigo(Integer.parseInt(elem.toString()));
        output.setValor(elem2.toString());
        output.setDescripcion(elem4.toString());
        datos.add(t);
        output.setDatos(datos);
        output.setDescripcion(out.getDescripcion());

    } catch (Exception e) {
        output = ConstruyeRespuesta.construyeRespuestaFalla(e.getMessage());
        e.printStackTrace();
    }
    return output;
}

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 www.j  a  va 2 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.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/*w  ww. ja  v  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.// w ww .j ava 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
 */
@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.//from  www.  j a v  a2s. 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
 */
@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());
}