List of usage examples for com.google.gson JsonObject add
public void add(String property, JsonElement value)
From source file:com.bios.controller.services.StartRoundService.java
/** * Handles the HTTP <code>GET</code> method which starts a bidding round. It checks that the user is a verified admin * and proceeds to start the round if the round is not yet started. Subsequently, it creates a json object with the status * "success" and stores the current bidding round. However, if round 2 has already ended, it creates a json object with the * status "error" and stores the error message "round 2 ended" in a json array. Additionally, if the user is not a verified admin with a valid * token, it creates a json object with the status "error" and stores the error message in a json array "invalid username/token". * * @param request servlet request// w w w . j av a 2s.c o m * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // String token = request.getParameter("token"); JsonObject object = new JsonObject(); if (request.getParameter("token") == null) { JsonArray array = new JsonArray(); object.addProperty("status", "error"); array.add(new JsonPrimitive("missing token")); object.add("message", array); } else if (request.getParameter("token").length() == 0) { JsonArray array = new JsonArray(); object.addProperty("status", "error"); array.add(new JsonPrimitive("blank token")); object.add("message", array); } else { String token = request.getParameter("token"); try { String result = JWTUtility.verify(token, "abcdefgh12345678"); if (result.equals("admin")) { JsonArray array = new JsonArray(); ConnectionManager manager = new ConnectionManager(); if (manager.getBiddingRoundStatus().equals("started")) { // Stop the round here object.addProperty("status", "success"); object.add("round", new JsonPrimitive(manager.getBiddingRound())); } else if (manager.getBiddingRound() == 1) { BiddingRoundServlet.incrementBiddingRound("true"); object.addProperty("status", "success"); object.add("round", new JsonPrimitive(manager.getBiddingRound())); } else { object.addProperty("status", "error"); array.add(new JsonPrimitive("round 2 ended")); object.add("message", array); } } } catch (JWTException e) { // This means not an admin, or token expired JsonArray array = new JsonArray(); JsonPrimitive value = new JsonPrimitive("invalid token"); 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.StopRoundService.java
/** * Handles the HTTP <code>GET</code> method which stops a bidding round. It checks that the user is a verified admin * and proceeds to stop the round if the round is started. Subsequently, it creates a json object with the status * "success". However, if a round is already stopped, it creates a json object with the status "error" and stores the error * message "round already ended" in a json array. Additionally, if the user is not a verified admin with a valid token, it * creates a json object with the status "error" and stores the error message in a json array "invalid username/token". * * @param request servlet request// w w w.ja v a2 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 { JsonObject object = new JsonObject(); if (request.getParameter("token") == null) { JsonArray array = new JsonArray(); object.addProperty("status", "error"); array.add(new JsonPrimitive("missing token")); object.add("message", array); } else if (request.getParameter("token").length() == 0) { JsonArray array = new JsonArray(); object.addProperty("status", "error"); array.add(new JsonPrimitive("blank token")); object.add("message", array); } else { String token = request.getParameter("token"); try { String result = JWTUtility.verify(token, "abcdefgh12345678"); if (result.equals("admin")) { JsonArray array = new JsonArray(); ConnectionManager manager = new ConnectionManager(); if (manager.getBiddingRoundStatus().equals("started") && manager.getBiddingRound() == 1) { // Stop the round here object.addProperty("status", "success"); // RoundOneBidDAO.getInstance().drop(); // // add all round 1 pending bids into roundonebiddao // ArrayList<Bid> allBids = BidDAO.getInstance().getPendingBids(); // for (Bid bid : allBids){ // RoundOneBidDAO.getInstance().addBid(bid); // } BiddingRoundServlet.incrementBiddingRound("true"); } else if (manager.getBiddingRoundStatus().equals("started") && manager.getBiddingRound() == 2) { // Stop the round here object.addProperty("status", "success"); // RoundTwoBidDAO.getInstance().drop(); // // add all round 1 pending bids into roundonebiddao // ArrayList<Bid> allBids = BidDAO.getInstance().getPendingBids(); // for (Bid bid : allBids){ // RoundTwoBidDAO.getInstance().addBid(bid); // } BiddingRoundServlet.incrementBiddingRound("true"); } else { object.addProperty("status", "error"); array.add(new JsonPrimitive("round already ended")); object.add("message", array); } } } catch (JWTException e) { // This means not an admin, or token expired JsonArray array = new JsonArray(); JsonPrimitive value = new JsonPrimitive("invalid token"); 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; }
From source file:com.bios.controller.services.StudentCalendarBidService.java
/** * Handles the HTTP <code>GET</code> method uses the userID of a student to * generates a json object with a timetable of that particular student that * consists of both the student's exams and classes. * * @param request servlet request// w ww . j a v a 2s . 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 doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String userID = request.getParameter("userID"); System.out.println(userID); ArrayList<Bid> allBids = BidDAO.getInstance().getStudentBids(userID); JsonArray arr = new JsonArray(); System.out.println(allBids.size()); for (Bid bid : allBids) { if (bid.getStatus().equals("success") || bid.getStatus().equals("pending")) { JsonObject obj = new JsonObject(); Course course = CourseDAO.getInstance().findCourse(bid.getCourseID()); Section section = SectionDAO.getInstance().findSection(bid.getCourseID(), bid.getSectionID()); DateFormat sourceFormat = new SimpleDateFormat("yyyyMMdd"); DateFormat df = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH); // Adding a Course exam object obj.add("title", new JsonPrimitive(course.getTitle())); try { Date source = sourceFormat.parse(course.getExamDate()); String target = df.format(source); System.out.println(target); System.out.println(sourceFormat.parse(course.getExamDate()).toString()); obj.add("start", new JsonPrimitive(target)); obj.add("end", new JsonPrimitive(target)); obj.add("className", new JsonPrimitive("bg-blue")); } catch (Exception e) { e.printStackTrace(); } obj.add("description", new JsonPrimitive(course.getDescription())); arr.add(obj); // Adding a Section class timetable object obj = new JsonObject(); obj.add("title", new JsonPrimitive(course.getTitle())); obj.add("start", new JsonPrimitive(section.getStart())); System.out.println(section.getStart()); obj.add("end", new JsonPrimitive(section.getEnd())); obj.add("className", new JsonPrimitive("bg-green")); obj.add("description", new JsonPrimitive(section.getCourseID())); JsonArray dow = new JsonArray(); dow.add(new JsonPrimitive(section.getDay())); obj.add("dow", dow); arr.add(obj); } } response.setContentType("application/json"); response.getWriter().write(arr.toString()); }
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/*from ww 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 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.bizideal.whoami.utils.cloopen.CCPRestSmsSDK.java
License:Open Source License
/** * ???/* w ww .j a va 2 s. c o m*/ * * @param to * ? ??????????100 * @param templateId * ? ?Id * @param datas * ?? ???{??} * @return */ public HashMap<String, Object> sendTemplateSMS(String to, String templateId, String[] datas) { HashMap<String, Object> validate = accountValidate(); if (validate != null) return validate; if ((isEmpty(to)) || (isEmpty(App_ID)) || (isEmpty(templateId))) throw new IllegalArgumentException("?:" + (isEmpty(to) ? " ?? " : "") + (isEmpty(templateId) ? " ?Id " : "") + ""); CcopHttpClient chc = new CcopHttpClient(); DefaultHttpClient httpclient = null; try { httpclient = chc.registerSSL(SERVER_IP, "TLS", Integer.parseInt(SERVER_PORT), "https"); } catch (Exception e1) { e1.printStackTrace(); throw new RuntimeException("?httpclient" + e1.getMessage()); } String result = ""; try { HttpPost httppost = (HttpPost) getHttpRequestBase(1, TemplateSMS); String requsetbody = ""; if (BODY_TYPE == BodyType.Type_JSON) { JsonObject json = new JsonObject(); json.addProperty("appId", App_ID); json.addProperty("to", to); json.addProperty("templateId", templateId); if (datas != null) { StringBuilder sb = new StringBuilder("["); for (String s : datas) { sb.append("\"" + s + "\"" + ","); } sb.replace(sb.length() - 1, sb.length(), "]"); JsonParser parser = new JsonParser(); JsonArray Jarray = parser.parse(sb.toString()).getAsJsonArray(); json.add("datas", Jarray); } requsetbody = json.toString(); } else { StringBuilder sb = new StringBuilder("<?xml version='1.0' encoding='utf-8'?><TemplateSMS>"); sb.append("<appId>").append(App_ID).append("</appId>").append("<to>").append(to).append("</to>") .append("<templateId>").append(templateId).append("</templateId>"); if (datas != null) { sb.append("<datas>"); for (String s : datas) { sb.append("<data>").append(s).append("</data>"); } sb.append("</datas>"); } sb.append("</TemplateSMS>").toString(); requsetbody = sb.toString(); } LoggerUtil.info("sendTemplateSMS Request body = " + requsetbody); BasicHttpEntity requestBody = new BasicHttpEntity(); requestBody.setContent(new ByteArrayInputStream(requsetbody.getBytes("UTF-8"))); requestBody.setContentLength(requsetbody.getBytes("UTF-8").length); httppost.setEntity(requestBody); HttpResponse response = httpclient.execute(httppost); HttpEntity entity = response.getEntity(); if (entity != null) result = EntityUtils.toString(entity, "UTF-8"); EntityUtils.consume(entity); } catch (IOException e) { e.printStackTrace(); LoggerUtil.error(e.getMessage()); return getMyError("172001", ""); } catch (Exception e) { e.printStackTrace(); LoggerUtil.error(e.getMessage()); return getMyError("172002", ""); } finally { if (httpclient != null) httpclient.getConnectionManager().shutdown(); } LoggerUtil.info("sendTemplateSMS response body = " + result); try { if (BODY_TYPE == BodyType.Type_JSON) { return jsonToMap(result); } else { return xmlToMap(result); } } catch (Exception e) { return getMyError("172003", ""); } }
From source file:com.blackducksoftware.integration.email.batch.processor.ProcessorTestUtil.java
License:Apache License
public VulnerabilityView createVulnerability(final String vulnId, final VulnerabilitySeverityEnum severity, final Gson gson) throws IntegrationException { final Map<String, Object> fieldMap = new HashMap<>(); fieldMap.put("vulnerabilityName", vulnId); fieldMap.put("description", "A vulnerability"); fieldMap.put("vulnerabilityPublishedDate", "today"); fieldMap.put("vulnerabilityUpdatedDate", "a minute ago"); fieldMap.put("baseScore", 10.0); fieldMap.put("impactSubscore", 5.0); fieldMap.put("exploitabilitySubscore", 1.0); fieldMap.put("source", ""); if (severity != null) { fieldMap.put("severity", severity.name()); }/*from w w w . j a v a 2 s . c om*/ fieldMap.put("accessVector", ""); fieldMap.put("accessComplexity", ""); fieldMap.put("authentication", ""); fieldMap.put("confidentialityImpact", ""); fieldMap.put("integrityImpact", ""); fieldMap.put("availabilityImpact", ""); fieldMap.put("cweId", vulnId); final VulnerabilityView view = ObjectFactory.INSTANCE.createPopulatedInstance(VulnerabilityView.class, fieldMap); view.json = gson.toJson(view); final JsonElement element = jsonParser.parse(view.json); final JsonObject jsonObject = element.getAsJsonObject(); final JsonObject links = new JsonObject(); links.addProperty(MetaService.VULNERABILITIES_LINK, ""); jsonObject.add("_meta", links); view.json = gson.toJson(jsonObject); return view; }
From source file:com.blackducksoftware.integration.email.extension.config.ExtensionConfigManager.java
License:Apache License
public String createJSonString(final Reader reader) { final JsonElement element = parser.parse(reader); final JsonArray array = element.getAsJsonArray(); final JsonObject object = new JsonObject(); object.addProperty("totalCount", array.size()); object.add("items", array); return object.toString(); }
From source file:com.blackducksoftware.integration.hub.api.report.ReportRestService.java
License:Apache License
/** * Generates a new Hub report for the specified version. * * @return the Report URL/*www . ja va 2 s . c o m*/ * */ public String startGeneratingHubReport(final ProjectVersionItem version, final ReportFormatEnum reportFormat, final ReportCategoriesEnum[] categories) throws IOException, BDRestException, URISyntaxException, UnexpectedHubResponseException { if (ReportFormatEnum.UNKNOWN == reportFormat) { throw new IllegalArgumentException("Can not generate a report of format : " + reportFormat); } final JsonObject json = new JsonObject(); json.addProperty("reportFormat", reportFormat.name()); if (categories != null) { final JsonArray categoriesJson = new JsonArray(); for (final ReportCategoriesEnum category : categories) { categoriesJson.add(category.name()); } json.add("categories", categoriesJson); } final HubRequest hubRequest = new HubRequest(getRestConnection()); hubRequest.setMethod(Method.POST); hubRequest.setLimit(HubRequest.EXCLUDE_INTEGER_QUERY_PARAMETER); hubRequest.setUrl(getVersionReportLink(version)); final StringRepresentation stringRep = new StringRepresentation(getRestConnection().getGson().toJson(json)); stringRep.setMediaType(MediaType.APPLICATION_JSON); stringRep.setCharacterSet(CharacterSet.UTF_8); String location = null; try { location = hubRequest.executePost(stringRep); } catch (final ResourceDoesNotExistException ex) { throw new BDRestException("There was a problem generating a report for this Version.", ex, ex.getResource()); } return location; }
From source file:com.blackducksoftware.integration.hub.HubIntRestService.java
License:Apache License
/** * Generates a new Hub report for the specified version. * * @return the Report URL//from ww w . java 2s .c o m * */ public String generateHubReport(final ProjectVersionItem version, final ReportFormatEnum reportFormat, final ReportCategoriesEnum[] categories) throws IOException, BDRestException, URISyntaxException, UnexpectedHubResponseException { if (ReportFormatEnum.UNKNOWN == reportFormat) { throw new IllegalArgumentException("Can not generate a report of format : " + reportFormat); } final JsonObject json = new JsonObject(); json.addProperty("reportFormat", reportFormat.name()); if (categories != null) { final JsonArray categoriesJson = new JsonArray(); for (final ReportCategoriesEnum category : categories) { categoriesJson.add(category.name()); } json.add("categories", categoriesJson); } final StringRepresentation stringRep = new StringRepresentation( hubServicesFactory.getRestConnection().getGson().toJson(json)); stringRep.setMediaType(MediaType.APPLICATION_JSON); stringRep.setCharacterSet(CharacterSet.UTF_8); String location = null; try { location = hubServicesFactory.getRestConnection().httpPostFromAbsoluteUrl(getVersionReportLink(version), stringRep); } catch (final ResourceDoesNotExistException ex) { throw new BDRestException("There was a problem generating a report for this Version.", ex, ex.getResource()); } return location; }
From source file:com.blackducksoftware.integration.hub.teamcity.server.global.ServerHubConfigPersistenceManager.java
License:Apache License
public void persist() throws IOException { if (!configFile.getParentFile().exists() && configFile.getParentFile().mkdirs()) { Loggers.SERVER.info("Directory created for the Hub configuration file at : " + configFile.getParentFile().getCanonicalPath()); } else if (configFile.exists() && configFile.delete()) { Loggers.SERVER.info("Old Hub configuration file removed, to be replaced by a new configuration."); }/*w ww .ja va2 s . co m*/ configFile.createNewFile(); final JsonObject globalConfigJson = new JsonObject(); final JsonElement hubServerConfigJson = gson.toJsonTree(getHubServerConfig(), HubServerConfig.class); globalConfigJson.add("hubServerConfig", hubServerConfigJson); globalConfigJson.addProperty("hubWorkspaceCheck", hubWorkspaceCheck); try (BufferedWriter writer = new BufferedWriter(new FileWriter(configFile))) { writer.write(gson.toJson(globalConfigJson)); } catch (final IOException e) { Loggers.SERVER.error("Failed to save Hub config file: " + configFile, e); } }