List of usage examples for org.json.simple.parser JSONParser JSONParser
JSONParser
From source file:com.krypc.hl.pr.controller.PatientRecordController.java
@RequestMapping(value = "/deployChaincode", method = { RequestMethod.POST, RequestMethod.GET }) public ResponseWrapper deployChaincode(HttpServletRequest request, HttpServletResponse response) { logger.info("PatientRecordController---deployChaincode()--STARTS"); ResponseWrapper wrapper = new ResponseWrapper(); String data = request.getParameter("data"); try {//from w w w . j a v a2 s . co m if (data != null && !data.isEmpty()) { JSONObject deploymentData = (JSONObject) new JSONParser().parse(data); String path = ((String) deploymentData.get("path")); String user = ((String) deploymentData.get("user")); if (!StringUtils.isEmpty(path) && !StringUtils.isEmpty(user)) { DeployRequest deployrequest = new DeployRequest(); deployrequest.setChaincodePath(path);//comment for devmode : uncomment for production //deployrequest.setChaincodePath("");//uncomment for devmode : comment for production deployrequest.setArgs(new ArrayList<>(Arrays.asList("init"))); Member member = peerMembershipServicesAPI.getChain().getMember(user); if (!member.isEnrolled()) { RegistrationRequest registrationRequest = new RegistrationRequest(); registrationRequest.setEnrollmentID(user); registrationRequest.setAffiliation("bank_a"); member = peerMembershipServicesAPI.getChain().registerAndEnroll(registrationRequest); } deployrequest.setChaincodeName("PatientRecord");//uncomment for devmode : comment for production //deployrequest.setChaincodeName("");//comment for devmode : uncomment for production deployrequest.setChaincodeLanguage(ChaincodeLanguage.JAVA); deployrequest.setConfidential(false); ChainCodeResponse chaincoderesponse = member.deploy(deployrequest); utils.storeChaincodeName(chaincoderesponse); wrapper.resultObject = chaincoderesponse; } else { wrapper.setError(ERROR_CODES.MANDATORY_FIELDS_MISSING); } } else { wrapper.setError(ERROR_CODES.MANDATORY_FIELDS_MISSING); } } catch (Exception e) { wrapper.setError(ERROR_CODES.INTERNAL_ERROR); logger.error("PatientRecordController---deployChaincode()--ERROR " + e); } logger.info("PatientRecordController---deployChaincode()--ENDS"); return wrapper; }
From source file:autoancillarieslimited.parser.ParserUtil.java
public static WareHouses parserWarehouses(String dataJson) { try {/*from w w w . j ava 2 s . co m*/ WareHouses i = new WareHouses(); JSONParser parser = new JSONParser(); Object obj = parser.parse(dataJson); JSONObject jsonObject = (JSONObject) obj; int id = Integer.parseInt((String) jsonObject.get("P0")); String name = (String) jsonObject.get("P1"); String address = (String) jsonObject.get("P2"); String phone = (String) jsonObject.get("P3"); String email = (String) jsonObject.get("P4"); int region_ID = Integer.parseInt((String) jsonObject.get("P5")); i.setId(id); i.setName(name); i.setAddress(address); i.setPhone(phone); i.setEmail(email); i.setRegion_ID(region_ID); return i; } catch (Exception ex) { return null; } }
From source file:com.michaeljones.hellohadoop.restclient.HadoopHdfsRestClient.java
public String[] ListDirectorySimple(String remoteRelativePath) { try {//from w ww . ja v a 2 s . co m // %1 nameNodeHost, %2 username %3 resource. String uri = String.format(BASIC_URL_FORMAT, nameNodeHost, username, remoteRelativePath); List<Pair<String, String>> queryParams = new ArrayList(); queryParams.add(new Pair<>("user.name", username)); queryParams.add(new Pair<>("op", "LISTSTATUS")); String content = restImpl.GetStringContent(uri, queryParams); JSONParser parser = new JSONParser(); JSONObject jsonObject = (JSONObject) parser.parse(content); JSONObject listStatus = (JSONObject) jsonObject.get("FileStatuses"); JSONArray fileList = (JSONArray) listStatus.get("FileStatus"); String[] directoryListing = new String[fileList.size()]; int directoryIndex = 0; for (Object listing : fileList) { JSONObject jsonListing = (JSONObject) listing; String pathname = jsonListing.get("pathSuffix").toString(); directoryListing[directoryIndex++] = pathname; } return directoryListing; } catch (ParseException ex) { LOGGER.error("Hadoop List directory failed: " + ex.getMessage()); throw new RuntimeException("Hadoop List directory failed :" + ex.getMessage()); } finally { restImpl.Close(); } }
From source file:com.intuit.tank.http.json.JsonResponse.java
@SuppressWarnings({ "rawtypes", "unchecked" }) private void initialize() { try {/*from w ww . j a v a 2s . co m*/ JSONParser parser = new JSONParser(); ContainerFactory containerFactory = new ContainerFactory() { public List creatArrayContainer() { return new LinkedList(); } public Map createObjectContainer() { return new LinkedHashMap(); } }; if (!StringUtils.isEmpty(this.response)) { Object parse = parser.parse(this.response, containerFactory); if (parse instanceof List) { this.jsonMap = new LinkedHashMap(); } else { this.jsonMap = (Map) parse; } this.jsonMap.put("root", parse); } else { this.jsonMap = new HashMap(); } } catch (Exception ex) { logger.warn("Unable to parse the response string as a JSON object: " + this.response, ex); } }
From source file:com.opensoc.enrichment.adapters.threat.ThreatHbaseAdapter.java
@SuppressWarnings({ "rawtypes", "deprecation" }) protected Map getThreatObject(String key) { LOGGER.debug("=======Pinging HBase For:" + key); Get get = new Get(Bytes.toBytes(key)); Result rs;//from ww w .j a va2 s.co m Map output = new HashMap(); try { rs = table.get(get); if (!rs.isEmpty()) { byte[] source_family = Bytes.toBytes("source"); JSONParser parser = new JSONParser(); Map<byte[], byte[]> sourceFamilyMap = rs.getFamilyMap(source_family); for (Map.Entry<byte[], byte[]> entry : sourceFamilyMap.entrySet()) { String k = Bytes.toString(entry.getKey()); LOGGER.debug("=======Found intel from source: " + k); output.put(k, parser.parse(Bytes.toString(entry.getValue()))); } } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } return output; }
From source file:com.zaizi.alfresco.bolt.ProcessNodes.java
@Override public void execute(Tuple tuple) { Iterator<String> iterator = tuple.getFields().iterator(); while (iterator.hasNext()) { String fieldName = iterator.next(); Object obj = tuple.getValueByField(fieldName); if (obj instanceof byte[]) { System.out.println(fieldName + "\t" + tuple.getBinaryByField(fieldName).length + " bytes"); System.out.println(fieldName + "\t" + tuple.getValueByField(fieldName) + " something"); try { String object = ((byte[]) obj).toString(); System.out.println(object); } catch (Exception ex) { }// w ww . j a v a2s. co m } else if (obj instanceof Metadata) { Metadata md = (Metadata) obj; System.out.println(md.toString(fieldName + ".")); } else { String value = tuple.getValueByField(fieldName).toString(); System.out.println(fieldName + " : " + trimValue(value)); try { JSONObject object = (JSONObject) new JSONParser().parse(value); Set keys = object.keySet(); Metadata metadata = new Metadata(); String url = ""; for (Object key : keys) { System.out.println(key.toString() + " : " + object.get(key)); metadata.setValue(key.toString(), object.get(key).toString()); if (key.toString().equals("propertiesUrl")) { url = object.get(key).toString(); } } metadata.setValue("status", "processed"); _collector.emit(com.digitalpebble.storm.crawler.Constants.StatusStreamName, tuple, new Values(url, metadata, Status.FETCHED)); System.out.println("status : fetched"); System.out.println("bolt : " + ProcessNodes.class.getName()); System.out.println(); } catch (Exception exc) { } } } _collector.ack(tuple); }
From source file:com.example.networkPacketFormats.ServeFunction.java
public void run() { /*/*from w ww.j a v a 2s . co m*/ Get the input from the client and check if he requests for questions or performance */ String jsonString; try { jsonString = inFromClient.readLine(); JSONObject json = (JSONObject) new JSONParser().parse(jsonString); String type = (String) json.get("queryType"); if (type.equals("Questions")) { /* Now query the database and generate a JSON string to send it back to client */ String subject = (String) json.get("subject"); String dateInMs = (String) json.get("date"); String standard = (String) json.get("standard"); System.out.println("DATE : " + dateInMs); String clientString = getJSONQuestionsString(subject, dateInMs, standard); System.out.println("JSON STRING : " + clientString); outToClient.writeBytes(clientString + "\n"); } else if (type.equals("Performance")) { /* Now check whether the query is for the last test or overall */ String performanceQueryType = (String) json.get("perfType"); String studentID = (String) json.get("studentID"); String subject = (String) json.get("subject"); String result = null; if (performanceQueryType.equals("Overall")) { /* Overall performance */ result = getJSONPerformanceString(subject, studentID, 2); } else if (performanceQueryType.equals("LastTest")) { /* Individual performance */ result = getJSONPerformanceString(subject, studentID, 1); } System.out.println("JSON STRING : " + result); outToClient.writeBytes(result + "\n"); } else if (type.equals("Files")) { /* CLient is requesting the files */ String std = (String) json.get("standard"); /* Client sends subject and standard and the files will be sent */ String pathName = createPath(std); /* Now traverse the folder and create a JSON File */ String filesJSONString = traverseAndMakeJSON(pathName); System.out.println("I am sending this to client : " + filesJSONString); /* Send it to the client back */ outToClient.writeBytes(filesJSONString + "\n"); System.out.println( "Sent " + filesJSONString + " to client and its of " + filesJSONString.length() + " bytes"); /* Now wait for the file download request */ String JSONfileToDownload = inFromClient.readLine(); if (JSONfileToDownload == null) { /* Client sent nothing Exit the thread */ return; } System.out.println("CLIENT ASKED FOR :" + JSONfileToDownload); /* Get the file name from the JSON string */ ObjectMapper mapper = new ObjectMapper(); HashMap<String, String> fileMap = new HashMap<String, String>(); try { //convert JSON string to Map fileMap = mapper.readValue(JSONfileToDownload, new TypeReference<HashMap<String, String>>() { }); } catch (Exception e) { e.printStackTrace(); } Set<String> set = fileMap.keySet(); String fileName = ""; /* This loop iterates for one time and gets the value */ for (String s : set) { fileName = fileMap.get(s); } File transferFile = new File(fileName); byte[] bytearray = new byte[(int) transferFile.length()]; /* Send the file size to the client */ String senty = new String(bytearray); JSONObject fileSizeJSON = new JSONObject(); fileSizeJSON.put("fileSize", bytearray.length); outToClient.writeBytes(fileSizeJSON + "\n"); outToClient.flush(); try { /* Now send the file to client */ sleep(5000); } catch (InterruptedException ex) { Logger.getLogger(ServeFunction.class.getName()).log(Level.SEVERE, null, ex); } BufferedInputStream buff = new BufferedInputStream(new FileInputStream(transferFile)); byte[] buffer = new byte[1024]; OutputStream os = sock.getOutputStream(); int count; while ((count = buff.read(buffer)) >= 0) { os.write(buffer, 0, count); os.flush(); } os.close(); sock.close(); System.out.println("File sent to client"); } } catch (IOException ex) { Logger.getLogger(ServeFunction.class.getName()).log(Level.SEVERE, null, ex); System.out.println("CLIENT CLOSED ABRUPTLY\n"); } catch (ParseException ex) { Logger.getLogger(ServeFunction.class.getName()).log(Level.SEVERE, null, ex); System.out.println("UNABLE TO PARSE\n"); } }
From source file:com.crazytest.config.TestCase.java
public String register(String name, String email, String userPassword) throws Exception { String uniqeEmail = Emails.generateUniqueEmail(email); String endpoint = String.format(yourapiurl); List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("name", name)); params.add(new BasicNameValuePair("email", uniqeEmail)); params.add(new BasicNameValuePair("password", userPassword)); createHttpClient();/*www. j a v a 2s. c o m*/ postWithoutToken(endpoint, params); HttpResponse httpResponse = getResponseOfPostRequest(); String httpResponseStringJsonString = EntityUtils.toString(httpResponse.getEntity()); LOGGER.info("Http response registration ={}", httpResponseStringJsonString); JSONParser parser = new JSONParser(); Object obj = parser.parse(httpResponseStringJsonString); JSONObject jsonObject = (JSONObject) obj; Object userID = jsonObject.get("user_id"); LOGGER.info("userID={}", userID); return uniqeEmail; }
From source file:at.uni_salzburg.cs.ckgroup.pilot.PositionProxy.java
public void fetchCurrentPosition() { HttpClient httpclient = new DefaultHttpClient(); HttpGet httpget = new HttpGet(pilotPositionUrl); HttpResponse response;/*from w ww. j av a 2 s .co m*/ String responseString = ""; try { response = httpclient.execute(httpget); int statusCode = response.getStatusLine().getStatusCode(); if (statusCode == 200) { responseString = EntityUtils.toString(response.getEntity()); } else { LOG.error("Error at accessing " + pilotPositionUrl + " code=" + statusCode + " reason=" + response.getStatusLine().getReasonPhrase()); } } catch (Exception e) { LOG.error("Can not access " + pilotPositionUrl, e); } JSONParser parser = new JSONParser(); try { JSONObject obj = (JSONObject) parser.parse(responseString); latitude = (Double) obj.get("latitude"); longitude = (Double) obj.get("longitude"); altitude = (Double) obj.get("altitude"); // courseOverGround = (Double)obj.get("courseOverGround"); // speedOverGround = (Double)obj.get("speedOverGround"); // altitudeOverGround = (Double)obj.get("altitudeOverGround"); Boolean apf = (Boolean) obj.get("autoPilotFlight"); autoPilotFlight = apf != null ? apf.booleanValue() : false; } catch (ParseException e) { LOG.error("Error at fetching current position from " + pilotPositionUrl); } }
From source file:edu.sjsu.cohort6.esp.common.CommonUtils.java
/** * This method parses the generic jersey response to a generic JSONObject and singles out the "entity" piece * from the generic response./*www .j a v a 2 s . c o m*/ * * @param response * @return * @throws org.json.simple.parser.ParseException */ private static String getJsonFromResponse(Response response) throws org.json.simple.parser.ParseException { String c = response.readEntity(String.class); log.info(c.toString()); JSONParser parser = new JSONParser(); JSONObject json = (JSONObject) parser.parse(c); JSONObject jsonObject = (JSONObject) json.get("entity"); return jsonObject.toJSONString(); }