List of usage examples for org.json.simple.parser JSONParser JSONParser
JSONParser
From source file:CatalogWSModel.CatalogWS.java
/** * This is a sample web service operation */// w ww. j a va 2 s . c o m @WebMethod(operationName = "viewCatalog") public ArrayList<String> viewCatalog(@WebParam(name = "access_token") String access_token) throws IOException, ParseException { int status = 0; ArrayList<String> answers = new ArrayList<String>(); Connection dbConn = DbConnectionManager.getConnection(); String targetIS = "ValidateToken"; String urlParameters = "access_token=" + access_token; HttpURLConnection urlConn = UrlConnectionManager.doReqPost(targetIS, urlParameters); String resp = UrlConnectionManager.getResponse(urlConn); JSONParser parser = new JSONParser(); JSONObject obj = (JSONObject) parser.parse(resp); String statusResp = (String) obj.get("status"); String username = (String) obj.get("username"); System.out.println("obj= " + obj.get("user_id")); String user_id = (String) obj.get("user_id"); System.out.println("String id = " + user_id); switch (statusResp) { case "valid": try { String query = "SELECT * FROM catalogue Order by product_id DESC"; Statement ps = dbConn.createStatement(); ResultSet rs = ps.executeQuery(query); while (rs.next()) { String productname = rs.getString("productname"); String seller = rs.getString("username"); int product_id = rs.getInt("product_id"); int price = rs.getInt("price"); String productdesc = rs.getString("productdesc"); Date dateAddedF = rs.getDate("dateadded"); SimpleDateFormat simpledatafo = new SimpleDateFormat("dd/MM/yyyy"); Time timeAddedF = rs.getTime("timeadded"); SimpleDateFormat simpletimefo = new SimpleDateFormat("dd/MM/yyyy"); String dateadded = rs.getString("dateadded"); String timeadded = rs.getString("timeadded"); String qLike = "SELECT * from likes WHERE product_id='" + product_id + "'"; Statement psLike = dbConn.createStatement(); ResultSet rsLike = psLike.executeQuery(qLike); int count = 0; while (rsLike.next()) { count++; } int likes = count; int purchases = rs.getInt("purchases"); String imagepath = rs.getString("imagepath"); String statuslike = "<span><a id=\"like\" href=\"like?product_id=" + product_id + "\"><b>ASD</b></a></span>"; String checkLike = "SELECT * from likes WHERE product_id='" + product_id + "' AND user_id='" + user_id + "'"; boolean hasLiked; Statement psCheckLike = dbConn.createStatement(); ResultSet rsCheckLike = psLike.executeQuery(checkLike); hasLiked = rsCheckLike.next(); if (!hasLiked) { statuslike = "<span><a id=\"like\" href=\"like?product_id=" + product_id + "\"><b>LIKE</b></a></span>"; } else { statuslike = "<span><a id=\"dislike\" href=\"dislike?product_id=" + product_id + "\"><b>LIKED</b></a></span>"; } String answer = "<li>" + "<span id='date'>" + "<b>" + seller + "</b>" + "</span>" + "<br/>" + "<span id='date'>" + dateadded + "<br/>" + "at " + timeadded + "<hr></hr>" + "</span>" + "<div class='item-list-product'>" + "<div style='position:absolute'>" + "<a href='" + imagepath + "'><img class='img-item' src='" + imagepath + "'></img></a>" + "</div>" + "<div id='product-info'>" + "<span><b>" + productname + "</b></span> <br/>" + "<span>IDR " + price + "</span> <br/>" + "<span style='font-size:12px;position:relative'>" + productdesc + "</span>" + "</div>" + "<div id='eddel'>" + "<br/>" + "<span style='font-size:14px'>" + likes + " likes</span> <br/>" + "<span style='font-size:14px'>" + purchases + " purchase</span> <br/>" + "<br/>" + statuslike + "<span style='margin-left:10px'><a id='buy' href='confirm.jsp?product_id=" + product_id + "'><b> BUY </b></a> </span>" + "</div>" + "</div>" + "</li>" + "<br/><br/>"; answers.add(answer); } } catch (SQLException ex) { System.out.println("Insert to database failed: An Exception has occurred! " + ex); } break; case "non-valid": String answer = "2"; answers.add(answer); break; default: answer = "3"; answers.add(answer); break; } System.out.println("Answer = " + answers.get(0)); return answers; }
From source file:minor.stockQuote.StockData.java
public List<StockDetails> getStockData(String ticker) { /*//from w ww .jav a 2 s. co m if(ticker.length() > 5 || ticker.length() < 3){ //System.out.println("-----------------------------------------------------------------------------------------------------"+ticker); return null; } */ //else { String requestQuery = "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.quotes%20where%20symbol%20in%20(%22" + ticker + "%22)%0A%09%09" + "&format=json&diagnostics=true&env=http%3A%2F%2Fdatatables.org%2Falltables.env&callback="; //String requestQuery ="http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.quotes%20where%20symbol%20%3D%20"+ticker+"%0A%09%09&format=json&diagnostics=true&env=http%3A%2F%2Fdatatables.org%2Falltables.env&callback="; //System.out.println(requestQuery); ArrayList<String> stockdetails = new ArrayList<String>(); URL url; try { url = new URL(requestQuery); URLConnection connection = url.openConnection(); BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); //System.out.println("jjjj"+in.readLine()); JSONParser jsonParser = new JSONParser(); try { JSONObject jsonObject = (JSONObject) jsonParser.parse(in); //System.out.println(jsonObject); JSONObject query = (JSONObject) jsonObject.get("query"); JSONObject results = (JSONObject) query.get("results"); JSONObject quote = (JSONObject) results.get("quote"); //System.out.println("iiiii"+quote.toJSONString()); stockdetails.add(quote.get("Change").toString()); stockdetails.add(quote.get("LastTradePriceOnly").toString()); stockdetails.add(quote.get("PERatio").toString()); stockdetails.add(quote.get("DaysLow").toString()); stockdetails.add(quote.get("DaysHigh").toString()); stockdetails.add(quote.get("Name").toString()); stockdetails.add(quote.get("Open").toString()); stockdetails.add(quote.get("Volume").toString()); stockdetails.add(quote.get("Ask").toString()); stockdetails.add(quote.get("AverageDailyVolume").toString()); stockdetails.add(quote.get("LastTradeDate").toString()); stockdetails.add(quote.get("EBITDA").toString()); stockdetails.add(quote.get("DaysRange").toString()); stockdetails.add(quote.get("FiftydayMovingAverage").toString()); stockdetails.add(quote.get("PreviousClose").toString()); stockdetails.add(quote.get("ChangeinPercent").toString()); stockdetails.add(quote.get("PEGRatio").toString()); stockdetails.add(quote.get("Symbol").toString()); stockdetails.add(quote.get("YearRange").toString()); stockdetails.add(quote.get("DaysValueChange").toString()); stockdetails.add(quote.get("StockExchange").toString()); stockdetails.add(quote.get("PercentChange").toString()); } catch (ParseException ex) { Logger.getLogger(StockData.class.getName()).log(Level.SEVERE, null, ex); } catch (NullPointerException ne) { } } catch (IOException e) { System.out.println(e); } for (String s : stockdetails) { System.out.println(s); } StockDetails obj = new StockDetails(stockdetails); //System.out.println("dddddD"+obj.toString()); List<StockDetails> sdList = new ArrayList<StockDetails>(); sdList.add(obj); /* for(StockDetails s: sdList){ System.out.println("ddfdfdf"+s.getChange() + s.getDaysHigh()); } */ return sdList; //} }
From source file:com.nubits.nubot.pricefeeds.feedservices.BtcePriceFeed.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 www.j a v a2s .co m try { htmlString = Utils.getHTML(url, true); } catch (IOException ex) { LOG.error(ex.toString()); return new LastPrice(true, name, pair.getOrderCurrency(), null); } JSONParser parser = new JSONParser(); try { JSONObject httpAnswerJson = (JSONObject) (parser.parse(htmlString)); JSONObject tickerObject = (JSONObject) httpAnswerJson.get("ticker"); double last = Utils.getDouble(tickerObject.get("last")); lastRequest = System.currentTimeMillis(); lastPrice = new LastPrice(false, name, pair.getOrderCurrency(), new Amount(last, pair.getPaymentCurrency())); return lastPrice; } catch (Exception ex) { LOG.error(htmlString); 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.nubits.nubot.pricefeeds.CcedkPriceFeed.java
@Override public LastPrice getLastPrice(CurrencyPair pair) { String url = TradeUtils.getCCEDKTickerUrl(pair); long now = System.currentTimeMillis(); long diff = now - lastRequest; if (diff >= refreshMinTime) { String htmlString;//from w w w.ja v a 2 s.c om try { htmlString = Utils.getHTML(url, true); } catch (IOException ex) { LOG.severe(ex.toString()); return new LastPrice(true, name, pair.getOrderCurrency(), null); } JSONParser parser = new JSONParser(); try { //{"errors":false,"response":{"entity":{"pair_id":"2","min":"510","max":"510","avg":"510","vol":"0.0130249"}}} JSONObject httpAnswerJson = (JSONObject) (parser.parse(htmlString)); JSONObject tickerObject = (JSONObject) httpAnswerJson.get("response"); JSONObject entityObject = (JSONObject) tickerObject.get("entity"); double last = Double.valueOf((String) entityObject.get("avg")); lastRequest = System.currentTimeMillis(); lastPrice = new LastPrice(false, name, pair.getOrderCurrency(), new Amount(last, pair.getPaymentCurrency())); return lastPrice; } catch (Exception ex) { LOG.severe(ex.toString()); lastRequest = System.currentTimeMillis(); return new LastPrice(true, name, pair.getOrderCurrency(), null); } } else { LOG.fine("Wait " + (refreshMinTime - (System.currentTimeMillis() - lastRequest)) + " ms " + "before making a new request. Now returning the last saved price\n\n"); return lastPrice; } }
From source file:net.bashtech.geobot.JSONUtil.java
public static String BOICharacter(String channel) { try {/*from w w w.j a va 2s . com*/ JSONParser parser = new JSONParser(); Object obj = parser.parse( BotManager.getRemoteContent("http://coebot.tv/configs/boir/" + channel.substring(1) + ".json")); JSONObject jsonObject = (JSONObject) obj; String character = (String) jsonObject.get("character"); return character; } catch (Exception ex) { return null; } }
From source file:com.stackmob.customcode.util.Logging.java
@Override public ResponseToProcess execute(ProcessedAPIRequest request, SDKServiceProvider serviceProvider) { // Initialize logger to "Classnamehere.class" when calling serviceProvider.getLoggerService() LoggerService logger = serviceProvider.getLoggerService(Logging.class); Map<String, String> errMap = new HashMap<String, String>(); String model = ""; String make = ""; String year = ""; JSONParser parser = new JSONParser(); /* The following try/catch block shows how to properly fetch parameters for PUT/POST operations * from the JSON request body. In order to get parameters from GET/DELETE operations, * you must use request.getParams() (see DeleteObject.java) *///from ww w . ja v a 2 s. com try { Object obj = parser.parse(request.getBody()); JSONObject jsonObject = (JSONObject) obj; model = (String) jsonObject.get("model"); make = (String) jsonObject.get("make"); year = (String) jsonObject.get("year"); logger.debug("Model: " + model); logger.debug("Make: " + make); logger.debug("Year: " + year.toString()); } catch (ParseException pe) { // error("Message", Throwable) logger.error(pe.getMessage(), pe); return Util.badRequestResponse(errMap, pe.getMessage()); } Map<String, Object> map = new HashMap<String, Object>(); map.put("model", new SMString(model)); map.put("make", new SMString(make)); map.put("year", new SMInt(Long.parseLong(year))); return new ResponseToProcess(HttpURLConnection.HTTP_OK, map); }
From source file:models.ACLRole.java
/** * @return never null//from ww w . j av a2 s.com */ public List<String> getPrivilegesList() { if (privileges == null) { return new ArrayList<String>(1); } if (privileges.trim().equals("")) { return new ArrayList<String>(1); } JSONParser jp = new JSONParser(); try { JSONArray ja = (JSONArray) jp.parse(privileges); if (ja.size() == 0) { return new ArrayList<String>(1); } ArrayList<String> result = new ArrayList<String>(); for (Object o : ja) { result.add((String) o); } return result; } catch (Exception e) { Log2.log.error("Can't extract privileges from DB", e, new Log2Dump("raw privileges", privileges)); return new ArrayList<String>(1); } }
From source file:com.nubits.nubot.pricefeeds.feedservices.CoinbasePriceFeed.java
@Override public LastPrice getLastPrice(CurrencyPair pair) { long now = System.currentTimeMillis(); long diff = now - lastRequest; if (diff >= refreshMinTime) { String url = getUrl(pair); String htmlString;/* ww w . jav a 2 s.c om*/ try { htmlString = Utils.getHTML(url, true); } catch (IOException ex) { LOG.error(ex.toString()); return new LastPrice(true, name, pair.getOrderCurrency(), null); } JSONParser parser = new JSONParser(); try { JSONObject httpAnswerJson = (JSONObject) (parser.parse(htmlString)); double last = Double.valueOf((String) httpAnswerJson.get("amount")); lastRequest = System.currentTimeMillis(); lastPrice = new LastPrice(false, name, pair.getOrderCurrency(), new Amount(last, pair.getPaymentCurrency())); return lastPrice; } catch (Exception 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.nubits.nubot.pricefeeds.feedservices.GooglePriceFeed.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 w w w . j a v a2 s.co m try { htmlString = Utils.getHTML(url, true); } catch (IOException ex) { LOG.error(ex.toString()); return new LastPrice(true, name, pair.getOrderCurrency(), null); } JSONParser parser = new JSONParser(); try { //Sample asnwer : // [ { "id": "-2001" ,"t" : "GBPUSD" ,"e" : "CURRENCY" ,"l" : "1.5187" ,"l_fix" : "" ,"l_cur" : "" ,"s": "0" ,"ltt":"" ,"lt" : "Apr 25, 11:55AM GMT" ,"lt_dts" : "2015-04-25T11:55:00Z" ,"c" : "0.00000" ,"c_fix" : "" ,"cp" : "0.000" ,"cp_fix" : "" ,"ccol" : "chb" ,"pcls_fix" : "" } ] htmlString = htmlString.replace("//", "").replace("[", "").replace("]", ""); JSONObject httpAnswerJson = (JSONObject) (parser.parse(htmlString)); double last = Utils.getDouble((String) httpAnswerJson.get("l")); last = Utils.round(last, 8); lastRequest = System.currentTimeMillis(); lastPrice = new LastPrice(false, name, pair.getOrderCurrency(), new Amount(last, pair.getPaymentCurrency())); return lastPrice; } catch (Exception 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.nubits.nubot.pricefeeds.feedservices.YahooPriceFeed.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. j a va 2s .c o m try { htmlString = Utils.getHTML(url, true); } catch (IOException ex) { LOG.error(ex.toString()); return new LastPrice(true, name, pair.getOrderCurrency(), null); } JSONParser parser = new JSONParser(); try { JSONObject httpAnswerJson = (JSONObject) (parser.parse(htmlString)); JSONObject query = (JSONObject) httpAnswerJson.get("query"); JSONObject results = (JSONObject) query.get("results"); JSONObject rate = (JSONObject) results.get("rate"); double last = Utils.getDouble((String) rate.get("Rate")); lastRequest = System.currentTimeMillis(); lastPrice = new LastPrice(false, name, pair.getOrderCurrency(), new Amount(last, pair.getPaymentCurrency())); return lastPrice; } catch (Exception 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; } }