List of usage examples for org.json.simple JSONObject toString
@Override
public String toString()
From source file:com.pinterest.rocksplicator.OnlineOfflineConfigGenerator.java
@Override public void onCallback(NotificationContext notificationContext) { HelixAdmin admin = helixManager.getClusterManagmentTool(); List<String> resources = admin.getResourcesInCluster(clusterName); Set<String> existingHosts = new HashSet<String>(); // compose cluster config JSONObject config = new JSONObject(); for (String resource : resources) { // Resources starting with PARTICIPANT_LEADER is for HelixCustomCodeRunner if (resource.startsWith("PARTICIPANT_LEADER")) { continue; }//from w ww. j ava2 s.com ExternalView externalView = admin.getResourceExternalView(clusterName, resource); Set<String> partitions = externalView.getPartitionSet(); // compose resource config JSONObject resourceConfig = new JSONObject(); String partitionsStr = externalView.getRecord().getSimpleField("NUM_PARTITIONS"); resourceConfig.put("num_shards", Integer.parseInt(partitionsStr)); // build host to partition list map Map<String, List<String>> hostToPartitionList = new HashMap<String, List<String>>(); for (String partition : partitions) { String partitionNumber = String.format("%05d", Integer.parseInt(partition.split("_")[1])); Map<String, String> hostToState = externalView.getStateMap(partition); for (Map.Entry<String, String> entry : hostToState.entrySet()) { if (!entry.getValue().equalsIgnoreCase("ONLINE")) { continue; } existingHosts.add(entry.getKey()); String hostWithDomain = getHostWithDomain(entry.getKey()); List<String> partitionList = hostToPartitionList.get(hostWithDomain); if (partitionList == null) { partitionList = new ArrayList<String>(); hostToPartitionList.put(hostWithDomain, partitionList); } partitionList.add(partitionNumber); } } // Add host to partition list map to the resource config for (Map.Entry<String, List<String>> entry : hostToPartitionList.entrySet()) { JSONArray jsonArray = new JSONArray(); for (String p : entry.getValue()) { jsonArray.add(p); } resourceConfig.put(entry.getKey(), jsonArray); } // add the resource config to the cluster config config.put(resource, resourceConfig); } // remove host that doesn't exist in the ExternalView from hostToHostWithDomain hostToHostWithDomain.keySet().retainAll(existingHosts); String newContent = config.toString(); if (lastPostedContent != null && lastPostedContent.equals(newContent)) { LOG.info("Identical external view observed, skip updating config."); return; } // Write the config to ZK LOG.info("Generating a new shard config..."); this.dataParameters.remove("content"); this.dataParameters.put("content", newContent); HttpPost httpPost = new HttpPost(this.postUrl); try { httpPost.setEntity(new StringEntity(this.dataParameters.toString())); HttpResponse response = new DefaultHttpClient().execute(httpPost); if (response.getStatusLine().getStatusCode() == 200) { lastPostedContent = newContent; LOG.info("Succeed to generate a new shard config."); } else { LOG.error(response.getStatusLine().getReasonPhrase()); } } catch (Exception e) { LOG.error("Failed to post the new config", e); } }
From source file:com.ba.forms.serviceBillForm.BAServiceBillAction.java
public ActionForward getPageRecords(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { logger.info(" getPageRecords method starts here"); JSONObject json = new JSONObject(); BAServiceBillDTO vo = new BAServiceBillDTO(); try {//from w w w. j av a 2 s . com // logger.info("======In GcsStockItemAction Action cmsGet method======"); vo.setServiceId((request.getParameter("serviceId"))); vo.setDateField(request.getParameter("dateField")); vo.setRoomId(request.getParameter("roomId")); vo.setCustomerName(request.getParameter("customerName")); vo.setOrderType((request.getParameter("orderType"))); vo.setAmount((request.getParameter("amount"))); vo.setServiceCharge((request.getParameter("serviceCharge"))); vo.setDiscount((request.getParameter("discount"))); vo.setServiceTax((request.getParameter("serviceTax"))); vo.setVat((request.getParameter("vat"))); vo.setNetAmount((request.getParameter("netAmount"))); vo.setPaymentMode((request.getParameter("paymentMode"))); vo.setBookingId((request.getParameter("bookingId"))); String strNavigation = request.getParameter("navigation"); int strCurrentPageNo = Integer.parseInt(request.getParameter("currentPageNo")); if (strNavigation != null && !strNavigation.equals("")) { if (strNavigation.equals("pre")) { strCurrentPageNo = strCurrentPageNo - 1; if (strCurrentPageNo <= 0) strCurrentPageNo = 1; } else if (strNavigation.equals("next")) { strCurrentPageNo = strCurrentPageNo + 1; if (strCurrentPageNo > objPageCount) strCurrentPageNo = objPageCount; } } logger.info("strCurrent PageNo ------------->" + strCurrentPageNo); List hashMpServiceBillItemDet = BAServiceBillFactory.getInstanceOfBAServiceBillFactory() .getServiceBillDtls(strCurrentPageNo, vo); json.put("exception", ""); json.put("ServiceBillDets", hashMpServiceBillItemDet); json.put("ServiceBillExit", hashMpServiceBillItemDet.size()); } catch (Exception ex) { logger.error("The Exception is :" + ex); ex.printStackTrace(); json.put("exception", BAHandleAllException.exceptionHandler(ex)); } response.getWriter().write(json.toString()); return null; }
From source file:mtis.CreateDisplayJson.java
public String getJson(String city, String duration) throws Exception { String finalReturn = ""; JSONArray list = new JSONArray(); JSONObject finalObj = new JSONObject(); ArrayList<String> month = new ArrayList<String>(); month.add("Jan"); month.add("Feb"); month.add("Mar"); month.add("Apr"); month.add("May"); month.add("Jun"); month.add("Jul"); month.add("Aug"); month.add("Sep"); month.add("Oct"); month.add("Nov"); month.add("Dec"); Date d = new Date(); int dayCount = Integer.parseInt(duration); Long dL = d.getTime();/*from w w w . ja va2 s . c om*/ FileReader fr = new FileReader( "C:\\Users\\Server\\Documents\\twitterData\\" + city + "\\traffic_data_" + city + "_display.txt"); BufferedReader br = new BufferedReader(fr); String line = br.readLine(); StringBuffer text = new StringBuffer(); while (line != null) { text.append(line); line = br.readLine(); } String textData = text.toString(); textData = textData.replaceAll("\\n", " "); String fullTokens[] = textData.split("\\$\\$\\$"); for (int i = fullTokens.length - 1; i >= 1; i--) { StringTokenizer st = new StringTokenizer(fullTokens[i], "||"); String dateString = st.nextToken(); Date date = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy").parse(dateString); Long dateL = date.getTime(); //System.out.println(dateL); String name = st.nextToken(); name = name.replaceAll("'", " "); if (dL - ((dayCount + 1) * 86400 * 1000) <= dateL && dateL <= dL - ((dayCount) * 86400 * 1000)) { //System.out.println("i am in"); JSONObject js = new JSONObject(); js.put("userScreenName", name); System.out.println(name); js.put("userProfilePic", st.nextToken()); js.put("userId", st.nextToken()); js.put("statusId", st.nextToken()); js.put("username", st.nextToken()); js.put("text", st.nextToken()); SimpleDateFormat format = new SimpleDateFormat("hh:mm a "); //System.out.println(format.format(date)); //System.out.println(date.getDate()+"-"+month.get(date.getMonth())+" "+format.format(date)); //System.out.println(dateL); js.put("time", date.getDate() + "-" + month.get(date.getMonth()) + " " + format.format(date)); list.add(js); } line = br.readLine(); } finalObj.put("locations", list); br.close(); finalReturn = finalObj.toString(); System.out.println(finalReturn); return finalReturn; }
From source file:com.ba.forms.foodBill.BAFoodBillAction.java
public ActionForward baPrint(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { Connection con = null;//from w w w . j a va 2s .com com.fins.org.json.JSONObject json = new com.fins.org.json.JSONObject(); try { logger.info("hotel_booking"); // title is the title of the report.Here we are passing dynamically.So that this class is useful to remaining reports also. String jrept = "hotel_food.jrxml"; String pdfFileName = "hotel_food"; String foodBill = request.getParameter("foodBill"); con = BADatabaseUtil.getConnection(); String reportFileName = JasperCompileManager .compileReportToFile(request.getRealPath("/reports") + "/" + jrept); java.util.Map parameters = new java.util.HashMap(); parameters.put("foodBill", foodBill); File reportFile = new File(reportFileName); if (!reportFile.exists()) { throw new JRRuntimeException( "File WebappReport.jasper not found. The report design must be compiled first."); } JasperPrint jasperPrint = JasperFillManager.fillReport(reportFileName, parameters, con); JasperExportManager.exportReportToPdfFile(jasperPrint, request.getRealPath("/PDF") + "/" + pdfFileName + "_" + foodBill + ".pdf"); File f = new File(request.getRealPath("/PDF") + "/" + pdfFileName + "_" + foodBill + ".pdf"); FileInputStream fin = new FileInputStream(f); // String path = "http://" + request.getServerName() + ":" + request.getServerPort() + "/" + request.getContextPath() + "/PDF" + "/" + pdfFileName + "_" + foodBill + ".pdf"; request.setAttribute("path", path); // outStream.flush(); fin.close(); // outStream.close(); logger.info("print feed dc"); json.put("exception", ""); json.put("bookingDets", path); json.put("bookingExit", 1); } catch (Exception ex) { ex.printStackTrace(); json.put("exception", BAHandleAllException.exceptionHandler(ex)); } finally { BADatabaseUtil.closeConnection(con); } logger.info("CmsReasonMasterDaoImpl In CmsReasonMasterAction :: cmsGet() ends Here "); response.getWriter().write(json.toString()); return null; }
From source file:com.photon.phresco.framework.rest.api.RepositoryService.java
/** * Update latest project.//from w w w.ja v a 2 s .c o m * * @param user the user * @param projectId the project id * @param appId the app id * @throws PhrescoException the phresco exception */ private void updateLatestProject(User user, String projectId, String appId) throws PhrescoException { try { File tempPath = new File(Utility.getPhrescoTemp() + File.separator + USER_PROJECT_JSON); JSONObject userProjJson = null; JSONParser parser = new JSONParser(); if (tempPath.exists()) { FileReader reader = new FileReader(tempPath); userProjJson = (JSONObject) parser.parse(reader); reader.close(); } else { userProjJson = new JSONObject(); } userProjJson.put(user.getId(), projectId + Constants.STR_COMMA + appId); FileWriter writer = new FileWriter(tempPath); writer.write(userProjJson.toString()); writer.close(); } catch (IOException e) { throw new PhrescoException(e); } catch (ParseException e) { throw new PhrescoException(e); } }
From source file:com.ba.forms.foodBill.BAFoodBillAction.java
public ActionForward getPageRecords(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { JSONObject json = new JSONObject(); BAFoodBillDTO vo = new BAFoodBillDTO(); try {/*w w w . j a v a2s. c om*/ logger.info(" getPageRecords method starts here"); vo.setFoodId((request.getParameter("foodId"))); vo.setDate(request.getParameter("date")); vo.setRoomId(request.getParameter("roomId")); vo.setCustomerName(request.getParameter("customerName")); vo.setOrderType((request.getParameter("orderType"))); vo.setAmount(request.getParameter("amount")); vo.setServiceCharge((request.getParameter("serviceCharge"))); vo.setDiscount(request.getParameter("discount")); vo.setServiceTax(request.getParameter("serviceTax")); vo.setVat(request.getParameter("vat")); vo.setNetAmount((request.getParameter("netAmount"))); vo.setPaymentMode(request.getParameter("paymentMode")); vo.setBookingId(request.getParameter("bookingId")); String strNavigation = request.getParameter("navigation"); int strCurrentPageNo = Integer.parseInt(request.getParameter("currentPageNo")); if (strNavigation != null && !strNavigation.equals("")) { if (strNavigation.equals("pre")) { strCurrentPageNo = strCurrentPageNo - 1; if (strCurrentPageNo <= 0) { strCurrentPageNo = 1; } } else if (strNavigation.equals("next")) { strCurrentPageNo = strCurrentPageNo + 1; if (strCurrentPageNo > objPageCount) { strCurrentPageNo = objPageCount; } } } logger.info("strCurrent PageNo ------------->" + strCurrentPageNo); List hashMpFoodBillDet = BAFoodBillFactory.getInstanceOfBAFoodBillFactory() .getFoodBillDtls(strCurrentPageNo, vo); json.put("exception", ""); json.put("FoodBillDets", hashMpFoodBillDet); json.put("FoodBillExit", hashMpFoodBillDet.size()); } catch (Exception ex) { logger.error("The Exception is :" + ex); ex.printStackTrace(); json.put("exception", BAHandleAllException.exceptionHandler(ex)); } response.getWriter().write(json.toString()); return null; }
From source file:bbdn.lti2.LTI2Servlet.java
@SuppressWarnings({ "unchecked", "unused", "rawtypes" }) public void registerToolProviderProfile(HttpServletRequest request, HttpServletResponse response, String profile_id) throws java.io.IOException { // Normally we would look up the deployment descriptor if (!"42".equals(profile_id)) { response.setStatus(HttpServletResponse.SC_NOT_FOUND); return;//from ww w.ja v a2 s . c o m } String key = "42"; String secret = "zaphod"; IMSJSONRequest jsonRequest = new IMSJSONRequest(request); if (!jsonRequest.valid) { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); doErrorJSON(request, response, jsonRequest, "Request is not in a valid format", null); return; } System.out.println(jsonRequest.getPostBody()); // Lets check the signature if (key == null || secret == null) { response.setStatus(HttpServletResponse.SC_FORBIDDEN); doErrorJSON(request, response, jsonRequest, "Deployment is missing credentials", null); return; } jsonRequest.validateRequest(key, secret, request); if (!jsonRequest.valid) { response.setStatus(HttpServletResponse.SC_FORBIDDEN); doErrorJSON(request, response, jsonRequest, "OAuth signature failure", null); return; } JSONObject providerProfile = (JSONObject) JSONValue.parse(jsonRequest.getPostBody()); // System.out.println("OBJ:"+providerProfile); if (providerProfile == null) { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); doErrorJSON(request, response, jsonRequest, "JSON parse failed", null); return; } JSONObject default_custom = (JSONObject) providerProfile.get(LTI2Constants.CUSTOM); JSONObject security_contract = (JSONObject) providerProfile.get(LTI2Constants.SECURITY_CONTRACT); if (security_contract == null) { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); doErrorJSON(request, response, jsonRequest, "JSON missing security_contract", null); return; } String shared_secret = (String) security_contract.get(LTI2Constants.SHARED_SECRET); System.out.println("shared_secret=" + shared_secret); if (shared_secret == null) { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); doErrorJSON(request, response, jsonRequest, "JSON missing shared_secret", null); return; } // Make sure that the requested services are a subset of the offered services ToolConsumer consumer = buildToolConsumerProfile(request, null, profile_id); JSONArray tool_services = (JSONArray) security_contract.get(LTI2Constants.TOOL_SERVICE); String retval = LTI2Util.validateServices(consumer, providerProfile); if (retval != null) { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); doErrorJSON(request, response, jsonRequest, retval, null); return; } // Parse the tool profile bit and extract the tools with error checking retval = LTI2Util.validateCapabilities(consumer, providerProfile); if (retval != null) { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); doErrorJSON(request, response, jsonRequest, retval, null); return; } // Pass the profile to the launch process PERSIST.put("profile", providerProfile.toString()); // Share our happiness with the Tool Provider Map jsonResponse = new TreeMap(); jsonResponse.put(LTI2Constants.CONTEXT, StandardServices.TOOLPROXY_ID_CONTEXT); jsonResponse.put(LTI2Constants.TYPE, StandardServices.TOOLPROXY_ID_TYPE); jsonResponse.put(LTI2Constants.JSONLD_ID, getServiceURL(request) + SVC_tc_registration + "/" + profile_id); jsonResponse.put(LTI2Constants.TOOL_PROXY_GUID, profile_id); jsonResponse.put(LTI2Constants.CUSTOM_URL, getServiceURL(request) + SVC_Settings + "/" + LTI2Util.SCOPE_ToolProxy + "/" + profile_id); response.setContentType(StandardServices.TOOLPROXY_ID_FORMAT); response.setStatus(HttpServletResponse.SC_CREATED); String jsonText = JSONValue.toJSONString(jsonResponse); M_log.debug(jsonText); PrintWriter out = response.getWriter(); out.println(jsonText); }
From source file:de.dailab.plistacontest.client.ClientAndContestHandler0MQ.java
/** * Method to handle incoming messages from the server. * /*from w w w . j av a 2 s. c om*/ * @param messageType * the messageType of the incoming contest server message. * @param properties * * @param entities * @return the response to the contest server */ private String handleIdomaarMessage(final String messageType, final String properties, final String entities) { // write all data from the server to a file logger.info(messageType + "\t" + properties + "\t" + entities); // create an jSON object from the String final JSONObject jOP = (JSONObject) JSONValue.parse(properties); final JSONObject jOE = (JSONObject) JSONValue.parse(entities); // merge the different jsonObjects and correct missing itemIDs jOP.putAll(jOE); Object itemID = jOP.get("itemID"); if (itemID == null) { jOP.put("itemID", 0); } // define a response object String response = null; if ("impression".equalsIgnoreCase(messageType)) { // parse the type of the event final RecommenderItem item = RecommenderItem.parseEventNotification(jOP.toJSONString()); final String eventNotificationType = item.getNotificationType(); // new items shall be added to the list of items if (item.getItemID() != null) { recommenderItemTable.handleItemUpdate(item); } response = "handle impression eventNotification successful"; // impression refers to articles read by the user if ("recommendation_request".equalsIgnoreCase(eventNotificationType)) { // we mark this information in the article table if (item.getItemID() != null) { item.setNumberOfRequestedResults(6); //List<Long> suggestedItemIDs = item.getListOfDisplayedRecs(); List<Long> suggestedItemIDs = recommenderItemTable.getLastItems(item); response = "{" + "\"recs\": {" + "\"ints\": {" + "\"3\": " + suggestedItemIDs + "}" + "}}"; } else { System.err.println("invalid itemID - requests are only valid for 'normal' articles"); } // click refers to recommendations clicked by the user } else if ("click".equalsIgnoreCase(eventNotificationType)) { // we mark this information in the article table if (item.getItemID() != null) { // new items shall be added to the list of items recommenderItemTable.handleItemUpdate(item); response = "handle impression eventNotification successful"; } response = "handle click eventNotification successful"; } else { System.out.println("unknown event-type: " + eventNotificationType + " (message ignored)"); } } else if ("error_notification".equalsIgnoreCase(messageType)) { System.out.println("error-notification: " + jOP.toString() + jOE.toJSONString()); } else { System.out.println("unknown MessageType: " + messageType); // Error handling logger.info(jOP.toString() + jOE.toJSONString()); // this.contestRecommender.error(jObj.toString()); } return response; }
From source file:com.ba.forms.settlement.BASettlementAction.java
public ActionForward baPrint(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { Connection con = null;// w ww . j a va 2 s. c o m com.fins.org.json.JSONObject json = new com.fins.org.json.JSONObject(); try { logger.info("hotel_booking"); // title is the title of the report.Here we are passing dynamically.So that this class is useful to remaining reports also. String jrept = "hotel settlement.jrxml"; String pdfFileName = "hotel settlement"; String sqlBookid = request.getParameter("sqlBookid"); String sqlRoomid = request.getParameter("sqlRoomid"); con = BADatabaseUtil.getConnection(); String reportFileName = JasperCompileManager .compileReportToFile(request.getRealPath("/reports") + "/" + jrept); java.util.Map parameters = new java.util.HashMap(); parameters.put("sqlBookid", Integer.parseInt(sqlBookid)); parameters.put("sqlRoomid", Integer.parseInt(sqlRoomid)); File reportFile = new File(reportFileName); if (!reportFile.exists()) { throw new JRRuntimeException( "File WebappReport.jasper not found. The report design must be compiled first."); } JasperPrint jasperPrint = JasperFillManager.fillReport(reportFileName, parameters, con); JasperExportManager.exportReportToPdfFile(jasperPrint, request.getRealPath("/PDF") + "/" + pdfFileName + "_" + sqlBookid + "_" + sqlRoomid + ".pdf"); File f = new File( request.getRealPath("/PDF") + "/" + pdfFileName + "_" + sqlBookid + "_" + sqlRoomid + ".pdf"); FileInputStream fin = new FileInputStream(f); // String path = "http://" + request.getServerName() + ":" + request.getServerPort() + "/" + request.getContextPath() + "/PDF" + "/" + pdfFileName + "_" + sqlBookid + "_" + sqlRoomid + ".pdf"; request.setAttribute("path", path); // outStream.flush(); fin.close(); // outStream.close(); logger.info("print feed dc"); json.put("exception", ""); json.put("bookingDets", path); json.put("bookingExit", 1); } catch (Exception ex) { ex.printStackTrace(); json.put("exception", BAHandleAllException.exceptionHandler(ex)); } finally { BADatabaseUtil.closeConnection(con); } logger.info("CmsReasonMasterDaoImpl In CmsReasonMasterAction :: cmsGet() ends Here "); response.getWriter().write(json.toString()); return null; }
From source file:de.dailab.plistacontest.client.ContestHandlerOfflineCheating.java
/** * Method to handle incoming messages from the server. * //from w ww.j av a2 s .c o m * @param messageType * the messageType of the incoming contest server message. * @param properties * * @param entities * @return the response to the contest server */ @SuppressWarnings("unchecked") private String handleIdomaarMessage(final String messageType, final String properties, final String entities) { // write all data from the server to a file // logger.info(messageType + "\t" + properties + "\t" + entities); // create an jSON object from the String final JSONObject jOP = (JSONObject) JSONValue.parse(properties); final JSONObject jOE = (JSONObject) JSONValue.parse(entities); // merge the different jsonObjects and correct missing itemIDs jOP.putAll(jOE); Object itemID = jOP.get("itemID"); if (itemID == null) { jOP.put("itemID", 0); } // define a response object String response = null; if ("impression".equalsIgnoreCase(messageType)) { // parse the type of the event final RecommenderItem item = RecommenderItem.parseEventNotification(jOP.toJSONString()); final String eventNotificationType = messageType; // impression refers to articles read by the user if ("impression".equalsIgnoreCase(eventNotificationType)) { // we mark this information in the article table if (item.getItemID() != null) { response = "handle impression eventNotification successful"; boolean recommendationExpected = false; if (properties.contains("\"event_type\": \"recommendation_request\"")) { recommendationExpected = true; } if (recommendationExpected) { List<Long> suggestedItemIDs = recommenderItemTable.getFutureItems(item.getTimeStamp(), item.getDomainID(), item.getUserID()); response = "{" + "\"recs\": {" + "\"ints\": {" + "\"3\": " + suggestedItemIDs + "}" + "}}"; } } // click refers to recommendations clicked by the user } else if ("click".equalsIgnoreCase(eventNotificationType)) { // we mark this information in the article table if (item.getItemID() != null) { response = "handle impression eventNotification successful"; } response = "handle click eventNotification successful"; } else { System.out.println("unknown event-type: " + eventNotificationType + " (message ignored)"); } } else if ("error_notification".equalsIgnoreCase(messageType)) { System.out.println("error-notification: " + jOP.toString() + jOE.toJSONString()); } else { System.out.println("unknown MessageType: " + messageType); // Error handling logger.info(jOP.toString() + jOE.toJSONString()); // this.contestRecommender.error(jObj.toString()); } return response; }