List of usage examples for org.json.simple JSONValue parse
public static Object parse(String s)
From source file:com.precioustech.fxtrading.oanda.restapi.account.OandaAccountDataProviderService.java
@Override public Collection<Account<Long>> getLatestAccountInfo() { CloseableHttpClient httpClient = getHttpClient(); List<Account<Long>> accInfos = Lists.newArrayList(); try {//from ww w .j a v a2 s . com HttpUriRequest httpGet = new HttpGet(getAllAccountsUrl()); httpGet.setHeader(this.authHeader); LOG.info(TradingUtils.executingRequestMsg(httpGet)); HttpResponse resp = httpClient.execute(httpGet); String strResp = TradingUtils.responseToString(resp); if (strResp != StringUtils.EMPTY) { Object jsonObject = JSONValue.parse(strResp); JSONObject jsonResp = (JSONObject) jsonObject; JSONArray accounts = (JSONArray) jsonResp.get(OandaJsonKeys.accounts); /* * We are doing a per account json request because not all information is returned in the array of results */ for (Object o : accounts) { JSONObject account = (JSONObject) o; Long accountIdentifier = (Long) account.get(accountId); Account<Long> accountInfo = getLatestAccountInfo(accountIdentifier, httpClient); accInfos.add(accountInfo); } } else { TradingUtils.printErrorMsg(resp); } } catch (Exception e) { LOG.error("Exception encountered while retrieving all accounts data", e); } finally { TradingUtils.closeSilently(httpClient); } return accInfos; }
From source file:com.framework.testcase.testrail.APIClient.java
private Object sendRequest(String method, String uri, Object data) throws MalformedURLException, IOException { URL url = new URL(this.m_url + uri); // Create the connection object and set the required HTTP method // (GET/POST) and headers (content type and basic auth). HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.addRequestProperty("Content-Type", "application/json"); String auth = getAuthorization(this.m_user, this.m_password); conn.addRequestProperty("Authorization", "Basic " + auth); if (method.equalsIgnoreCase("POST")) { // Add the POST arguments, if any. We just serialize the passed // data object (i.e. a dictionary) and then add it to the // request body. if (data != null) { byte[] block = JSONValue.toJSONString(data).getBytes("UTF-8"); conn.setDoOutput(true);//w w w. j av a 2s. c o m OutputStream ostream = conn.getOutputStream(); ostream.write(block); ostream.flush(); } } // Execute the actual web request (if it wasn't already initiated // by getOutputStream above) and record any occurred errors (we use // the error stream in this case). int status = 0; try { status = conn.getResponseCode(); } catch (SocketTimeoutException e) { e.printStackTrace(); System.err.println("the request is timeout from the server ,we quite the test"); } catch (SSLHandshakeException ex) { ex.printStackTrace(); System.err.println("the request is Remote host closed connection during handshake"); } InputStream istream; if (status != 200) { istream = conn.getErrorStream(); if (istream == null) { new Exception("TestRail API return HTTP " + status + " (No additional error message received)"); } } else { istream = conn.getInputStream(); } // Read the response body, if any, and deserialize it from JSON. String text = ""; if (istream != null) { BufferedReader reader = new BufferedReader(new InputStreamReader(istream, "UTF-8")); String line; while ((line = reader.readLine()) != null) { text += line; text += System.getProperty("line.separator"); } reader.close(); } Object result; if (text != "") { result = JSONValue.parse(text); } else { result = new JSONObject(); } // Check for any occurred errors and add additional details to // the exception message, if any (e.g. the error message returned // by TestRail). if (status != 200) { String error = "No additional error message received"; if (result != null && result instanceof JSONObject) { JSONObject obj = (JSONObject) result; if (obj.containsKey("error")) { error = '"' + (String) obj.get("error") + '"'; } } new Exception("TestRail API returned HTTP " + status + "(" + error + ")"); } return result; }
From source file:com.turt2live.uuid.turt2live.v2.ApiV2Service.java
@Override public List<PlayerRecord> doBulkLookup(String... playerNames) { String list = combine(playerNames); String response = doUrlRequest(getConnectionUrl() + "/uuid/list/" + list); if (response != null) { JSONObject json = (JSONObject) JSONValue.parse(response); if (json.containsKey("results")) { JSONObject object = (JSONObject) json.get("results"); List<PlayerRecord> records = new ArrayList<>(); for (Object key : object.keySet()) { String name = key.toString(); UUID uuid = UUID.fromString((String) object.get(key)); if (uuid == null || name.equals("unknown")) continue; PlayerRecord record = new Turt2LivePlayerRecord(uuid, name); records.add(record);//from ww w . j av a 2 s. co m } return records; } } return null; }
From source file:backtype.storm.utils.Utils.java
public static Object from_json(String json) { if (json == null) { return null; } else {/*from w ww . j a v a 2s . c o m*/ // return JSON.parse(json); return JSONValue.parse(json); } }
From source file:com.noelportugal.amazonecho.AmazonEchoApi.java
public String getLatestHistory() throws IOException { String output = httpGet("/api/activities?startTime=&size=1&offset=-1"); //System.out.println(output); fLogger.log(Level.INFO, output); // Parse JSON Object obj = JSONValue.parse(output); JSONObject jsonObject = (JSONObject) obj; JSONArray values = (JSONArray) jsonObject.get("activities"); JSONObject item = (JSONObject) values.get(0); String text = item.get("description").toString(); fLogger.log(Level.INFO, text.toString()); //Get the summary text Object obj2 = JSONValue.parse(text); JSONObject jsonObject2 = (JSONObject) obj2; text = jsonObject2.get("summary").toString(); if (!checkItemId(text)) { return text; } else {/* www . j ava2 s.c o m*/ return null; } }
From source file:de.dailab.plistacontest.client.ContestHandler.java
/** * Method to handle incoming messages from the server. * // ww w. j a v a2s.c om * @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) || "recommendation".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) || "recommendation".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); item.setNumberOfRequestedResults(6); response = "handle impression eventNotification successful"; boolean recommendationExpected = false; if (properties.contains("\"event_type\": \"recommendation_request\"")) { recommendationExpected = true; } if (recommendationExpected) { List<Long> suggestedItemIDs = recommenderItemTable.getLastItems(item); 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) { // 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.walmartlabs.mupd8.application.Config.java
@SuppressWarnings("unchecked") private void loadSysConfig(String filename) throws IOException, Exception { JSONObject sysJson = (JSONObject) JSONValue.parse(readWithPreprocessing(new FileReader(filename))); configuration = new JSONObject(); /*/*from www.j ava2s. co m*/ if (!configuration.containsKey("mupd8")) { configuration.put("mupd8", new JSONObject()); } JSONObject mupd8 = configuration.get("mupd8"); for (String k : new String[]{ "mupd8_status", "slate_store" }) { // ... } */ configuration.put("mupd8", sysJson); }
From source file:com.mobicage.rogerthat.CallbackApiServlet.java
@Override public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setContentType("application/json-rpc; charset=utf-8"); // Validate incomming request final String contentType = req.getHeader("Content-type"); if (contentType == null || !contentType.startsWith("application/json-rpc")) { resp.setStatus(HttpURLConnection.HTTP_BAD_REQUEST); return;/*from w w w .ja v a2 s .co m*/ } final String sikKey = req.getHeader("X-Nuntiuz-Service-Key"); if (!validateSIK(sikKey)) { resp.setStatus(HttpURLConnection.HTTP_UNAUTHORIZED); return; } // Parse final InputStream is = req.getInputStream(); final JSONObject request; try { request = (JSONObject) JSONValue.parse(new BufferedReader(new InputStreamReader(is, "UTF-8"))); } finally { is.close(); } if (logTraffic) log.info(String.format("Incoming Rogerthat API Callback.\nSIK: %s\n\n%s", sikKey, request.toJSONString())); final String id = (String) request.get("id"); if (callbackDedup != null) { byte[] response = callbackDedup.getResponse(id); if (response != null) { ServletOutputStream outputStream = resp.getOutputStream(); outputStream.write(response); outputStream.flush(); return; } } final JSONObject result = new JSONObject(); final RequestContext requestContext = new RequestContext(id, sikKey); try { processor.process(request, result, requestContext); } finally { String jsonString = result.toJSONString(); if (logTraffic) log.info("Returning result:\n" + jsonString); byte[] response = jsonString.getBytes("UTF-8"); if (callbackDedup != null) { callbackDedup.storeResponse(id, response); } ServletOutputStream outputStream = resp.getOutputStream(); outputStream.write(response); outputStream.flush(); } }
From source file:de.mpg.imeji.presentation.servlet.autocompleter.java
/** * Parse a JSON file from CoNE with authors, and return a JSON which can be read by imeji autocomplete * /* w ww.jav a 2 s .c o m*/ * @param cone * @return * @throws IOException */ @SuppressWarnings("unchecked") private String parseConeAuthor(String cone) throws IOException { Object obj = JSONValue.parse(cone); JSONArray array = (JSONArray) obj; JSONArray result = new JSONArray(); for (int i = 0; i < array.size(); ++i) { JSONObject parseObject = (JSONObject) array.get(i); JSONObject sendObject = new JSONObject(); sendObject.put("label", parseObject.get("http_purl_org_dc_elements_1_1_title")); sendObject.put("family", parseObject.get("http_xmlns_com_foaf_0_1_family_name")); sendObject.put("givenname", parseObject.get("http_xmlns_com_foaf_0_1_givenname")); sendObject.put("id", parseObject.get("id")); sendObject.put("orgs", writeJsonArrayToOneString(parseObject.get("http_purl_org_escidoc_metadata_terms_0_1_position"), "http_purl_org_eprint_terms_affiliatedInstitution")); sendObject.put("alternatives", writeJsonArrayToOneString(parseObject.get("http_purl_org_dc_terms_alternative"), "")); result.add(sendObject); } StringWriter out = new StringWriter(); JSONArray.writeJSONString(result, out); return out.toString(); }
From source file:com.precioustech.fxtrading.oanda.restapi.account.transaction.OandaTransactionDataProviderService.java
@Override public List<Transaction<Long, Long, String>> getTransactionsGreaterThanId(Long minTransactionId, Long accountId) {/* w ww .j a v a 2 s .c om*/ Preconditions.checkNotNull(minTransactionId); Preconditions.checkNotNull(accountId); CloseableHttpClient httpClient = getHttpClient(); List<Transaction<Long, Long, String>> allTransactions = Lists.newArrayList(); try { HttpUriRequest httpGet = new HttpGet(getAccountMinTransactionUrl(minTransactionId, accountId)); httpGet.setHeader(authHeader); httpGet.setHeader(OandaConstants.UNIX_DATETIME_HEADER); LOG.info(TradingUtils.executingRequestMsg(httpGet)); HttpResponse httpResponse = httpClient.execute(httpGet); String strResp = TradingUtils.responseToString(httpResponse); if (strResp != StringUtils.EMPTY) { Object obj = JSONValue.parse(strResp); JSONObject jsonResp = (JSONObject) obj; JSONArray transactionsJson = (JSONArray) jsonResp.get(TRANSACTIONS); for (Object o : transactionsJson) { try { JSONObject transactionJson = (JSONObject) o; final String type = transactionJson.get(OandaJsonKeys.type).toString(); Event transactionEvent = OandaUtils.toOandaTransactionType(type); Transaction<Long, Long, String> transaction = null; if (transactionEvent instanceof TradeEvents) { transaction = handleTradeTransactionEvent((TradeEvents) transactionEvent, transactionJson); } else if (transactionEvent instanceof AccountEvents) { transaction = handleAccountTransactionEvent((AccountEvents) transactionEvent, transactionJson); } else if (transactionEvent instanceof OrderEvents) { transaction = handleOrderTransactionEvent((OrderEvents) transactionEvent, transactionJson); } if (transaction != null) { allTransactions.add(transaction); } } catch (Exception e) { LOG.error("error encountered whilst parsing:" + o, e); } } } else { TradingUtils.printErrorMsg(httpResponse); } } catch (Exception e) { LOG.error("error encountered->", e); } return allTransactions; }