List of usage examples for org.json.simple.parser JSONParser parse
public Object parse(Reader in) throws IOException, ParseException
From source file:ch.newscron.encryption.EncryptionJUnitTest.java
@Test public void decodeTest() throws UnsupportedEncodingException, NoSuchAlgorithmException, ParseException { // With null string assertNull(Encryption.decode(null)); // With working string String stringEncoded = Encryption.encode(inviteData); String stringDecoded = Encryption.decode(stringEncoded); assertNotNull(stringDecoded);/* w ww . j a v a 2s.co m*/ JSONParser parser = new JSONParser(); JSONObject decodedJSON = (JSONObject) parser.parse(stringDecoded); inviteData.remove("hash"); assertTrue(compareJSONObjects(inviteData, decodedJSON)); // With not appropriate string (invalid) String encodedWrong = "vKnxBLGBGdG3PIZlv4w8DpyQfvPhtz_7HayuA6b2-DC1M45RL7LcBc_p2IIXl4eXDphGxx5esQx74kE-txVij1KuqgW6J7pC2yCSIDxVfJkfHdubKRdvC7aFhclXq"; assertNull(Encryption.decode(encodedWrong)); // Hash of valid data byte[] hash = Encryption.createMD5Hash(inviteData); // Corrupt data JSONObject inviteData2 = new JSONObject(); inviteData2.put("custID", "12345"); inviteData2.put("rew1", "40%"); inviteData2.put("rew2", "100%"); //!! Changed (in comparison to inviteData) inviteData2.put("val", "05/10/2015"); //Send corrupt data (inviteData2) with valid hash of inviteData. //The hash of the corrupt data will differ from the hash of the valid data. String corruptEncodedURL = Encryption.encode(inviteData2, new String(hash, "UTF-8")); assertTrue(Encryption.decode(corruptEncodedURL) == null); //Indicating corrupt data }
From source file:com.hurence.logisland.repository.json.JsonTagsFileParser.java
/** * parses the file and returns a dictionnary of domain / tags * * @param filename//from ww w.j av a 2s . c om * @return */ public Map<String, List<String>> parse(String filename) { Map<String, List<String>> repository = new HashMap<>(); JSONParser parser = new JSONParser(); int domainCount = 0; try { logger.debug("parsing json file : " + filename); Object obj = parser.parse(new FileReader(filename)); JSONArray domains = (JSONArray) obj; for (Object object : domains) { domainCount++; JSONObject jsonObject = (JSONObject) object; String domain = (String) jsonObject.get("term"); JSONArray tags = (JSONArray) jsonObject.get("tags"); String company = (String) jsonObject.get("company"); if (company != null) { tags.add(company); } repository.put(domain, tags); } logger.debug("succesfully parsed " + domainCount + "domains"); } catch (ParseException | IOException ex) { logger.error(ex.getMessage()); } return repository; }
From source file:de.fraunhofer.iosb.tc_lib_helloworld.HelloWorldTcParam.java
public HelloWorldTcParam(final String paramJson) throws TcInconclusive { JSONParser jsonParser = new JSONParser(); JSONObject jsonObject;/* ww w . j av a 2s. com*/ try { jsonObject = (JSONObject) jsonParser.parse(paramJson); // get a String from the JSON object federation_name = (String) jsonObject.get("federationName"); if (federation_name == null) { throw new TcInconclusive("The key federationName was not found"); } // get a String from the JSON object rtiHost = (String) jsonObject.get("rtiHostName"); if (rtiHost == null) { throw new TcInconclusive("The key rtiHostName was not found"); } settingsDesignator = "crcAddress=" + this.rtiHost; // get a String from the JSON object sutFederate = (String) jsonObject.get("sutFederateName"); if (sutFederate == null) { throw new TcInconclusive("The key sutFederateName was not found"); } } catch (ParseException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } this.urls[0] = this.getClass().getClassLoader().getResource("HelloWorld.xml"); }
From source file:fr.smile.services.PatchService.java
private JSONArray jsonParser(String json) { JSONParser parser = new JSONParser(); JSONArray a = null;//from w ww. j a va 2 s . com try { a = (JSONArray) parser.parse(json); } catch (ParseException e) { LOGGER.error("", e); } return a; }
From source file:com.ebay.logstorm.server.platform.spark.SparkExecutionPlatform.java
@Override public synchronized void status(final PipelineExecutionEntity entity) throws Exception { String applicationId = entity.getProperties().getProperty("applicationId"); if (applicationId == null) { LOG.warn("get null applicationId, may be starting"); return;/* w w w .ja v a 2 s . co m*/ } entity.requireUpdate(true); int beginPort = MIN_REST_PORT; while (beginPort++ < MAX_REST_PORT) { String restURL = sparkRestUrl + ":" + beginPort + SPARK_REST_API_PATH + applicationId; try { URL url = new URL(restURL); BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream())); String statusStr = ""; String line; while (null != (line = br.readLine())) { statusStr += line + "\n"; } br.close(); entity.setDescription(statusStr); entity.setUrl(sparkRestUrl + ":" + beginPort + SPARK_JOB_PATH); LOG.info(statusStr); //parse more json fields later, just work now JSONParser parser = new JSONParser(); Object obj = parser.parse(statusStr); JSONObject jsonObject = (JSONObject) obj; if (applicationId.equals(jsonObject.get("id"))) { LOG.info("find application {} rest url {}", applicationId, restURL); } else { LOG.warn("wrong application {} rest url {}", applicationId, restURL); continue; } JSONArray a = (JSONArray) jsonObject.get("attempts"); for (int i = 0; i < a.size(); i++) { boolean finished = (boolean) ((JSONObject) a.get(i)).get("completed"); if (!finished) { entity.setStatus(PipelineExecutionStatus.RUNNING); return; } } entity.setStatus(PipelineExecutionStatus.STOPPED); return; } catch (Exception e) { } } entity.setStatus(PipelineExecutionStatus.STOPPED); LOG.warn("get status for application {} failed, assume stopped", applicationId); }
From source file:de.Keyle.MyPet.util.Updater.java
protected Optional<Update> check() { try {//ww w.j a v a2 s . co m String parameter = ""; parameter += "&package=" + MyPetApi.getCompatUtil().getInternalVersion(); parameter += "&build=" + MyPetVersion.getBuild(); parameter += "&dev=" + MyPetVersion.isDevBuild(); String url = "http://update.mypet-plugin.de/" + plugin + "?" + parameter; // no data will be saved on the server String content = Util.readUrlContent(url); JSONParser parser = new JSONParser(); JSONObject result = (JSONObject) parser.parse(content); if (result.containsKey("latest")) { String version = result.get("latest").toString(); int build = ((Long) result.get("build")).intValue(); return Optional.of(new Update(version, build)); } } catch (Exception ignored) { ignored.printStackTrace(); } return Optional.empty(); }
From source file:es.tid.fiware.fiwareconnectors.cygnus.backends.ckan.CKANRequester.java
/** * Common method to perform HTTP request using the CKAN API with payload. * @param method HTTP method/*from www . j av a 2s.c o m*/ * @param urlPath URL path to be added to the base URL * @param payload Request payload * @return CKANResponse associated to the request * @throws Exception */ public CKANResponse doCKANRequest(String method, String urlPath, String payload) throws Exception { // build the final URL String url = baseURL + urlPath; HttpRequestBase request = null; HttpResponse response = null; try { // do the post if (method.equals("GET")) { request = new HttpGet(url); } else if (method.equals("POST")) { HttpPost r = new HttpPost(url); // payload (optional) if (!payload.equals("")) { logger.debug("request payload: " + payload); r.setEntity(new StringEntity(payload, ContentType.create("application/json"))); } // if request = r; } else { throw new CygnusRuntimeError("HTTP method not supported: " + method); } // if else // headers request.addHeader("Authorization", apiKey); // execute the request logger.debug("CKAN operation: " + request.toString()); } catch (Exception e) { if (e instanceof CygnusRuntimeError || e instanceof CygnusPersistenceError || e instanceof CygnusBadConfiguration) { throw e; } else { throw new CygnusRuntimeError(e.getMessage()); } // if else } // try catch try { response = httpClient.execute(request); } catch (Exception e) { throw new CygnusPersistenceError(e.getMessage()); } // try catch try { BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); String res = reader.readLine(); request.releaseConnection(); long l = response.getEntity().getContentLength(); logger.debug("CKAN response (" + l + " bytes): " + response.getStatusLine().toString()); // get the JSON encapsulated in the response logger.debug("response payload: " + res); JSONParser j = new JSONParser(); JSONObject o = (JSONObject) j.parse(res); // return result return new CKANResponse(o, response.getStatusLine().getStatusCode()); } catch (Exception e) { if (e instanceof CygnusRuntimeError || e instanceof CygnusPersistenceError || e instanceof CygnusBadConfiguration) { throw e; } else { throw new CygnusRuntimeError(e.getMessage()); } // if else } // try catch }
From source file:com.nubits.nubot.pricefeeds.feedservices.OpenexchangeratesPriceFeed.java
@Override public LastPrice getLastPrice(CurrencyPair pair) { long now = System.currentTimeMillis(); long diff = now - lastRequest; if (diff >= refreshMinTime) { String url = getUrl(pair); String htmlString;/*from ww w. ja va 2 s. com*/ try { LOG.trace("feed fetching from URL: " + url); htmlString = Utils.getHTML(url, true); } catch (IOException ex) { LOG.error(ex.toString()); return new LastPrice(true, name, pair.getOrderCurrency(), null); } JSONParser parser = new JSONParser(); boolean found = false; try { JSONObject httpAnswerJson = (JSONObject) (parser.parse(htmlString)); String lookingfor = pair.getOrderCurrency().getCode().toUpperCase(); JSONObject rates = (JSONObject) httpAnswerJson.get("rates"); lastRequest = System.currentTimeMillis(); if (rates.containsKey(lookingfor)) { double last = (Double) rates.get(lookingfor); LOG.trace("last " + last); last = Utils.round(1 / last, 8); lastPrice = new LastPrice(false, name, pair.getOrderCurrency(), new Amount(last, pair.getPaymentCurrency())); return lastPrice; } else { LOG.warn("Cannot find currency :" + lookingfor + " on feed :" + name); return new LastPrice(true, name, pair.getOrderCurrency(), null); } } catch (ParseException ex) { LOG.error(ex.toString()); lastRequest = System.currentTimeMillis(); return new LastPrice(true, name, pair.getOrderCurrency(), null); } } else { LOG.warn("Wait " + (refreshMinTime - (System.currentTimeMillis() - lastRequest)) + " ms " + "before making a new request. Now returning the last saved price\n\n"); return lastPrice; } }
From source file:com.releasequeue.server.ReleaseQueueServer.java
private Object getJsonRequest(URL url) throws IOException, HttpException { HttpGet request = new HttpGet(url.toString()); setAuthHeader(request);//www . j a v a2 s .co m CloseableHttpClient httpClient = HttpClients.createDefault(); try { HttpResponse response = httpClient.execute(request); StatusLine statusLine = response.getStatusLine(); int statusCode = statusLine.getStatusCode(); if (statusCode >= 400) { throw new HttpException(statusLine.getReasonPhrase()); } String json_string = EntityUtils.toString(response.getEntity()); JSONParser parser = new JSONParser(); return parser.parse(json_string); } catch (ParseException pe) { throw new RuntimeException("Failed to parse json responce", pe); } finally { httpClient.getConnectionManager().shutdown(); } }
From source file:buspathcontroller.JSONFileParser.java
public void generateAllRoutes() { JSONParser parser = new JSONParser(); try {//from w w w . ja v a 2s. c o m PrintWriter writer = new PrintWriter("/Users/Zhaowei/Desktop/BusPath/allRoutes.txt"); Object obj = parser.parse(new FileReader("/Users/Zhaowei/Desktop/BusPath/RawJSON/RouteList.json")); JSONObject jsonObject = (JSONObject) obj; JSONArray routes = (JSONArray) jsonObject.get("routes"); Iterator iterator = routes.iterator(); while (iterator.hasNext()) { JSONObject route = (JSONObject) ((JSONObject) iterator.next()).get("route"); writer.println(route.get("name") + ";" + route.get("tag") + ";" + route.get("agency")); } writer.close(); } catch (Exception e) { System.out.println(e); } }