List of usage examples for org.json.simple.parser JSONParser parse
public Object parse(Reader in) throws IOException, ParseException
From source file:com.yifanlu.Kindle.JSONMenu.java
/** * Takes the JSON file stored in the object and converts it to menu item objects. * * @throws IOException if there is a problem reading the JSON text * @throws ParseException if there is a problem parsing the JSON text */// ww w . ja v a2 s . c om public void parseJSONMenu() throws IOException, ParseException { mMenuItems = new LauncherMenu[] {}; FileReader read = new FileReader(mJsonFile); JSONParser parse = new JSONParser(); JSONObject obj = (JSONObject) parse.parse(read); LauncherAction action = jsonToAction(obj, null); if (action instanceof LauncherMenu && action.getValue().equals("No Text")) { mMenuItems = ((LauncherMenu) action).getMenuItems(); } else { mMenuItems = new LauncherAction[] { action }; } }
From source file:mx.com.sagarpa.snics.SeguridadFiltro.java
@Override public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws ServletException, IOException { HttpServletRequest request = (HttpServletRequest) req; String requestURI = request.getRequestURI(); // LOG.info(requestURI); //hardcodear la request uri requestURI = "testteooo"; ////w w w . ja v a 2 s . c om System.out.println(requestURI); RestClientImpl clienteRest = new RestClientImpl(); // usr 4 para que truene String respuesta = clienteRest.POST("{\"token\":1,\"ruta\":\"" + requestURI + "\"}", "http://localhost:8081/snics-services/Usuario/validarPermiso.do", ""); System.out.println(respuesta); JSONParser parser = new JSONParser(); JSONObject jsonRespuesta = null; try { jsonRespuesta = (JSONObject) parser.parse(respuesta); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } Boolean autorizacion = (Boolean) jsonRespuesta.get("autorizacion"); String token = (String) jsonRespuesta.get("token"); System.out.println(autorizacion); //validacion del token tiempo de espera if (token.length() != 0) { //validacion de los permisos if (autorizacion == true) { chain.doFilter(req, res); } else { ((HttpServletResponse) res) .sendRedirect(((HttpServletRequest) req).getContextPath() + "/views/admin/forbidden.jsp"); } } else { ((HttpServletResponse) res) .sendRedirect(((HttpServletRequest) req).getContextPath() + "/views/admin/login.jsp"); } // if (requestURI.startsWith("/Check_License/Dir_My_App/")) { // String toReplace = requestURI.substring(requestURI.indexOf("/Dir_My_App"), requestURI.lastIndexOf("/") + 1); // String newURI = requestURI.replace(toReplace, "?Contact_Id="); // req.getRequestDispatcher(newURI).forward(req, res); // } else { // chain.doFilter(req, res); // } // HttpServletResponse resp = (HttpServletResponse) res; // resp.reset(); // resp.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY); // resp.setHeader("Location", "/mus-web/views/admin/diagnostico.jsp"); // return; }
From source file:boosta.artem.services.TaskQuery.java
public String getStatus(int id) throws UnsupportedEncodingException, IOException, ParseException { String result = "{\n" + " \"password\" : \"\",\n" + " \"action\" : \"getTaskState\",\n" + " \"data\" : {\n" + " \"taskUid\" : \"" + String.valueOf(id) + "\"\n" + " }\n" + "}"; DefaultHttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost("http://62.210.82.210:9091/API"); StringEntity requestEntity = new StringEntity(result); requestEntity.setContentType("application/json"); httpPost.setEntity(requestEntity);// w ww . ja v a 2 s .c o m HttpResponse response = httpClient.execute(httpPost); InputStream in = response.getEntity().getContent(); //System.out.println(getStringFromInputStream(in)); String resp = getStringFromInputStream(in); JSONParser parser = new JSONParser(); JSONObject json = (JSONObject) parser.parse(resp); json = (JSONObject) json.get("data"); String status = json.get("status").toString(); System.out.println(status); //return getStringFromInputStream(in); return status; }
From source file:data.GoogleBooksWS.java
@Override public void parse(String tekst) throws Exception { //List<Book> lista=new ArrayList<>(); JSONParser parser = new JSONParser(); Object obj = parser.parse(tekst); JSONObject jsonObject = (JSONObject) obj; if (prvi) {/*from w ww . ja v a2 s.c o m*/ int brojRezultata = Integer.parseInt(jsonObject.get("totalItems") + ""); ukupanBrojStrana = brojRezultata / RESULTS_PER_PAGE + 1; System.out.println("Broj strana" + ukupanBrojStrana); prvi = false; } System.out.println("Trenutni broj strane " + trenutniBrojStrane); JSONArray niz = (JSONArray) jsonObject.get("items"); if (niz == null) { kraj = true; } else { Iterator iterator = niz.iterator(); while (iterator.hasNext()) { Book b = new Book(); b.setUri(URIGenerator.generateUri(b)); JSONObject book = (JSONObject) iterator.next(); b.setTitle((String) ((JSONObject) book.get("volumeInfo")).get("title")); JSONArray autori = (JSONArray) ((JSONObject) book.get("volumeInfo")).get("authors"); if (autori != null) { Iterator it = autori.iterator(); while (it.hasNext()) { Person p = new Person(); p.setUri(URIGenerator.generateUri(p)); p.setName((String) it.next()); b.getAuthors().add(p); } } else { System.out.println("Autori su null"); } Organization o = new Organization(); o.setUri(URIGenerator.generateUri(o)); o.setName((String) ((JSONObject) book.get("volumeInfo")).get("publisher")); b.setPublisher(o); String date = (String) ((JSONObject) book.get("volumeInfo")).get("publishedDate"); System.out.println(date); b.setDatePublished(date); String description = (String) ((JSONObject) book.get("volumeInfo")).get("description"); b.setDescription(description); Object brStr = ((JSONObject) book.get("volumeInfo")).get("pageCount"); if (brStr != null) { long broj = Long.parseLong(brStr.toString()); b.setNumberOfPages((int) broj); } JSONArray identifiers = (JSONArray) ((JSONObject) book.get("volumeInfo")) .get("industryIdentifiers"); if (identifiers != null) { for (int i = 0; i < identifiers.size(); i++) { JSONObject identifier = (JSONObject) identifiers.get(i); if ("ISBN_13".equals((String) identifier.get("type"))) { b.setIsbn((String) identifier.get("identifier")); } } } //b.setIsbn((String) ((JSONObject) ((JSONArray)((JSONObject)book.get("volumeInfo")).get("industryIdentifiers")).get(1)).get("identifier")); lista.add(b); } if (trenutniBrojStrane < ukupanBrojStrana) { trenutniBrojStrane++; } else { kraj = true; } } }
From source file:boosta.artem.services.TaskQuery.java
public int addTask() throws UnsupportedEncodingException, IOException, ParseException { int task_id = 0; DefaultHttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost("http://62.210.82.210:9091/API"); StringEntity requestEntity = new StringEntity(this.task.toJSON(), "UTF-8"); requestEntity.setContentType("application/json"); System.out.println(getStringFromInputStream(requestEntity.getContent()) + "\n"); httpPost.setEntity(requestEntity);/* w w w. j a v a 2 s. co m*/ HttpResponse response = httpClient.execute(httpPost); InputStream in = response.getEntity().getContent(); String resp = getStringFromInputStream(in); //resp.getBytes("UTF-8"); //resp = resp.getBytes(resp).toString(); System.out.println(resp); JSONParser parser = new JSONParser(); JSONObject json = (JSONObject) parser.parse(resp); //json.toJSONString(); task_id = Integer.parseInt(json.get("data").toString()); System.out.println(task_id); return task_id; }
From source file:boosta.artem.services.TaskQuery.java
public int getResultCounts(int id) throws UnsupportedEncodingException, IOException, ParseException { String result = "{\n" + " \"password\" : \"\",\n" + " \"action\" : \"getTaskState\",\n" + " \"data\" : {\n" + " \"taskUid\" : \"" + String.valueOf(id) + "\"\n" + " }\n" + "}"; DefaultHttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost("http://62.210.82.210:9091/API"); StringEntity requestEntity = new StringEntity(result); requestEntity.setContentType("application/json"); httpPost.setEntity(requestEntity);// w w w . ja v a2s . co m HttpResponse response = httpClient.execute(httpPost); InputStream in = response.getEntity().getContent(); //System.out.println(getStringFromInputStream(in)); String resp = getStringFromInputStream(in); JSONParser parser = new JSONParser(); JSONObject json = (JSONObject) parser.parse(resp); json = (JSONObject) json.get("data"); json = (JSONObject) json.get("state"); int counts = Integer.parseInt(json.get("resultsCount").toString()); System.out.println(counts); //return getStringFromInputStream(in); return counts; }
From source file:com.neu.bigdata.service.PredictionService.java
public double getSuccessPrediction() { double successRate = 0; String response = rrsHttpPost(); JSONParser parser = new JSONParser(); try {/* www . ja va2 s . c om*/ Object responseJSON = parser.parse(response); JSONObject root = (JSONObject) responseJSON; JSONObject results = getJSONObject("Results", root); JSONObject output1 = getJSONObject("output1", results); JSONObject value = getJSONObject("value", output1); JSONArray values = getJSONArray("Values", value); JSONArray firstValues = getJSONArray(0, values); Object finalValue = firstValues.get(35); successRate = Double.parseDouble(finalValue.toString()); successRate = (successRate / 7.5) * 100.000; } catch (Exception ex) { ex.printStackTrace(); } return successRate; }
From source file:com.nubits.nubot.pricefeeds.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 v a2s . c o m*/ 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(); 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); last = Utils.round(1 / last, 8); lastPrice = new LastPrice(false, name, pair.getOrderCurrency(), new Amount(last, pair.getPaymentCurrency())); return lastPrice; } else { LOG.warning("Cannot find currency :" + lookingfor + " on feed :" + name); return new LastPrice(true, name, pair.getOrderCurrency(), null); } } catch (ParseException 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:com.stackmob.example.CreateVerifiedUser.java
@Override public ResponseToProcess execute(ProcessedAPIRequest request, SDKServiceProvider serviceProvider) { String username = ""; String password = ""; String uuid = ""; LoggerService logger = serviceProvider.getLoggerService(com.stackmob.example.CreateVerifiedUser.class); //Log the JSON object passed to the StackMob Logs logger.debug(request.getBody());// w w w. ja va 2 s .c o m // I'll be using these maps to print messages to console as feedback to the operation Map<String, SMValue> feedback = new HashMap<String, SMValue>(); Map<String, String> errMap = new HashMap<String, String>(); JSONParser parser = new JSONParser(); try { Object obj = parser.parse(request.getBody()); JSONObject jsonObject = (JSONObject) obj; //We use the username passed to query the StackMob datastore //and retrieve the user's name and email address username = (String) jsonObject.get("username"); password = (String) jsonObject.get("password"); uuid = (String) jsonObject.get("uuid"); } catch (ParseException e) { return Util.internalErrorResponse("parse_exception", e, errMap); // error 500 } if (Util.hasNulls(username, password, uuid)) { return Util.badRequestResponse(errMap); } // get the StackMob datastore service and assemble the query DataService dataService = serviceProvider.getDataService(); // build a query List<SMCondition> query = new ArrayList<SMCondition>(); query.add(new SMEquals("username", new SMString(username))); query.add(new SMEquals("uuid", new SMString(uuid))); List<SMObject> result; try { // return results from unverified user query result = dataService.readObjects("user_unverified", query); if (result != null && result.size() == 1) { SMObject newUserObject; try { // Create new User Map<String, SMValue> objMap = new HashMap<String, SMValue>(); objMap.put("username", new SMString(username)); objMap.put("password", new SMString(password)); newUserObject = dataService.createObject("user", new SMObject(objMap)); feedback.put("user_created", new SMString(newUserObject.toString())); } catch (InvalidSchemaException e) { return Util.internalErrorResponse("invalid_schema", e, errMap); // error 500 // http 500 - internal server error } catch (DatastoreException e) { return Util.internalErrorResponse("datastore_exception", e, errMap); // http 500 - internal server error } catch (Exception e) { return Util.internalErrorResponse("unknown_exception", e, errMap); // http 500 - internal server error } } } catch (InvalidSchemaException e) { return Util.internalErrorResponse("invalid_schema", e, errMap); // error 500 // http 500 - internal server error } catch (DatastoreException e) { return Util.internalErrorResponse("datastore_exception", e, errMap); // http 500 - internal server error } catch (Exception e) { return Util.internalErrorResponse("unknown_exception", e, errMap); // http 500 - internal server error } return new ResponseToProcess(HttpURLConnection.HTTP_OK, feedback); }
From source file:Model.MHaze.java
public void addHazeInfo(String pStrString) throws ParseException { IDataStorage objDS = CDataStorageFactory.getMasterStorage(); StringBuilder objSB = new StringBuilder(); objSB.append("INSERT INTO `haze`(`region`, `psiValue`, `airQualityDescriptor`)" + " VALUES"); JSONParser jsonParser = new JSONParser(); JSONArray aryJSON = (JSONArray) jsonParser.parse(pStrString); for (Object objJson : aryJSON) { objSB.append("('"); JSONObject objInnerObj = (JSONObject) objJson; int intPsi = Integer.parseInt(objInnerObj.get("psi").toString()); String strRegionCode = objInnerObj.get("region").toString(); switch (strRegionCode.toUpperCase()) { case "RNO": objSB.append("north"); objSB.append("',"); break; case "RSO": objSB.append("south"); objSB.append("',"); break; case "RCE": objSB.append("central"); objSB.append("',"); break; case "RWE": objSB.append("west"); objSB.append("',"); break; case "REA": objSB.append("east"); objSB.append("',"); break; default:/*from w w w. j a v a2 s.co m*/ objSB.append("national"); objSB.append("',"); break; } objSB.append(intPsi); objSB.append(",'"); if (intPsi <= 50) { objSB.append("Good"); } else if (intPsi <= 100) { objSB.append("Moderate"); } else if (intPsi <= 200) { objSB.append("Unhealthy"); } else if (intPsi <= 300) { objSB.append("Very unhealthy"); } else { objSB.append("Hazardous"); } objSB.append("'),"); } objSB.deleteCharAt(objSB.lastIndexOf(",")); objSB.append(";"); System.out.println(objSB); objDS.openConnection(); objDS.executeScalar("truncate table haze;"); objDS.executeScalar(objSB.toString()); objDS.closeConnection(); }