List of usage examples for org.json.simple.parser JSONParser JSONParser
JSONParser
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);//from w w w . j a v a2 s . c o 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:com.AandC.GemsCraft.Configuration.ConfigKey.java
public static String getServerName() { try {/*from w ww. ja va 2s . co m*/ JSONParser parser = new JSONParser(); Object obj = parser.parse(new FileReader("/sdcard/GemsCraft/config.json")); JSONObject jsonObject = (JSONObject) obj; ServerName = String.valueOf(jsonObject.get("ServerName")); } catch (Exception e) { e.printStackTrace(); } return ServerName; }
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;/* ww w . j ava 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.ijuru.ijambo.Context.java
/** * Connects to the database/*from ww w. j a va 2 s . c om*/ * @return the Mongo DB * @throws ParseException * @throws UnknownHostException */ public static DB connectDatabase() throws ParseException, UnknownHostException { // Check for AppFog environment String appFogEnv = System.getenv("VCAP_SERVICES"); if (appFogEnv != null) { // Connect to MongoDB as AppFog service JSONParser parser = new JSONParser(); JSONObject svcs = (JSONObject) parser.parse(appFogEnv); JSONArray mongoSettings = (JSONArray) svcs.get("mongodb-1.8"); JSONObject mongoSettings0 = (JSONObject) mongoSettings.get(0); JSONObject mongoCreds0 = (JSONObject) mongoSettings0.get("credentials"); //String db = (String)mongoCreds0.get("db"); String connectionURL = (String) mongoCreds0.get("url"); log.info("Running as AppFog instance with connection URL: " + connectionURL); DB db = new MongoURI(connectionURL).connectDB(); // https://jira.mongodb.org/browse/JAVA-436 db.authenticate((String) mongoCreds0.get("username"), ((String) mongoCreds0.get("password")).toCharArray()); return db; } // Create default MongoDB instance m = new Mongo(); return m.getDB("ijambo"); }
From source file:com.aerospike.example.cache.Flights.java
public Flights(AerospikeClient client, String namespace, String set, int ttl) { this.asClient = client; this.namespace = namespace; this.set = set; this.defaultTTL = ttl; this.writePolicy = new WritePolicy(); this.writePolicy.expiration = this.defaultTTL; this.parser = new JSONParser(); }
From source file:AddProductModel.AddProductWS.java
@WebMethod(operationName = "addProduct") public int addProduct(@WebParam(name = "access_token") String access_token, @WebParam(name = "product_name") String product_name, @WebParam(name = "description") String description, @WebParam(name = "price") String price, @WebParam(name = "img_name") String img_name, @WebParam(name = "img_byte") byte[] img_byte) throws ProtocolException, IOException, ParseException { int status = 0; Connection dbConn = DbConnectionManager.getConnection(); java.util.Date date = new java.util.Date(); java.sql.Date dateadded = new java.sql.Date(date.getTime()); java.sql.Time timeadded = new java.sql.Time(date.getTime()); int purchases = 0; 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"); switch (statusResp) { case "valid": try {/* www . j a v a 2s .c om*/ String image_path = uploadImage(img_byte, img_name); String query = "INSERT INTO catalogue(productname,price,productdesc,username,dateadded,timeadded,purchases,imagepath) VALUES ('" + product_name + "','" + price + "','" + description + "','" + username + "','" + dateadded + "','" + timeadded + "','" + purchases + "','" + image_path + "')"; PreparedStatement ps = dbConn.prepareStatement(query); int i = ps.executeUpdate(); } catch (SQLException ex) { System.out.println("Inser to database failed: An Exception has occurred! " + ex); } finally { if (dbConn != null) { try { dbConn.close(); } catch (SQLException e) { System.out.println(e); } dbConn = null; } } status = 1; break; case "non-valid": status = 2; break; default: status = 3; break; } return status; }
From source file:amulet.resourceprofiler.JSONResourceReader.java
/** * Parse the input JSON file for energy data collected during our * evaluation of the amulet hardware. JSON data content will be * loaded into Plain Old Java Objects (POJOs) for easy handling * in later parts of the AFT. //from ww w . j a va2s . co m * * @param filename The JSON file with energy data. */ public void read(String filename) { this.filename = filename; JSONParser parser = new JSONParser(); try { // Top-level JSON object. JSONObject jsonRootObj = (JSONObject) parser.parse(new FileReader(this.filename)); // System.out.println("DEBUG:: jsonRootObj="+jsonRootObj); // Extract Device Information. JSONObject jsonDeviceInfo = (JSONObject) jsonRootObj.get("device_information"); deviceInformation.jsonDeviceInfo = jsonDeviceInfo; deviceInformation.deviceName = (String) jsonDeviceInfo.get("device_name"); deviceInformation.batterySize = (Long) jsonDeviceInfo.get("battery_size"); deviceInformation.batterySizeUnits = (String) jsonDeviceInfo.get("battery_size_units"); deviceInformation.memTypeVolatile = (String) jsonDeviceInfo.get("volatile_mem_type"); deviceInformation.memSizeVolatile = (Long) jsonDeviceInfo.get("volatile_mem_size_bytes"); deviceInformation.memTypeNonVolatile = (String) jsonDeviceInfo.get("non_volatile_mem_type"); deviceInformation.memSizeNonVolatile = (Long) jsonDeviceInfo.get("non_volatile_mem_size_bytes"); deviceInformation.memTypeSecondary = (String) jsonDeviceInfo.get("secondary_storage_type"); deviceInformation.memSizeSecondary = (Double) jsonDeviceInfo.get("secondary_storage_size_bytes"); deviceInformation.avgNumInstructionsPerLoC = (Double) jsonDeviceInfo.get("instructions_per_loc"); deviceInformation.avgBasicInstructionPower = (Double) jsonDeviceInfo.get("basic_instruction_power"); deviceInformation.avgBasicInstructionTime = (Double) jsonDeviceInfo.get("basic_instruction_time"); deviceInformation.avgBasicInstructionUnit = (String) jsonDeviceInfo.get("basic_loc_time_unit"); // Extract Steady-State Information. JSONObject jsonSteadyStateInfo = (JSONObject) jsonRootObj.get("steady_state_info"); steadyStateInformation.jsonSteadyStateInfo = jsonSteadyStateInfo; steadyStateInformation.radioBoardSleepPower = (Double) jsonSteadyStateInfo .get("radio_board_sleep_power"); steadyStateInformation.appBoardSleepPower = (Double) jsonSteadyStateInfo.get("app_board_sleep_power"); steadyStateInformation.displayIdlePower = (Double) jsonSteadyStateInfo.get("display_idle_power"); steadyStateInformation.sensorAccelerometer = (Double) jsonSteadyStateInfo.get("sensor_accelerometer"); steadyStateInformation.sensorHeartRate = (Double) jsonSteadyStateInfo.get("sensor_heartrate"); // Array of "parameters". JSONArray paramArray = (JSONArray) jsonRootObj.get("api_calls"); apiInfo = paramArray; for (int i = 0; i < paramArray.size(); i++) { JSONObject jsonObj = (JSONObject) paramArray.get(i); /* * Build POJO based on energy parameter element from JSON data file. * * NOTE: Extend this section of code to parse more parameters * as needed. Also, see: `JSONEnergyParam` below. */ EnergyParam param = new EnergyParam(); param.name = jsonObj.get("resource_name").toString(); param.type = jsonObj.get("resource_type").toString(); param.avgPower = (Double) jsonObj.get("avg_power"); param.avgTime = (Double) jsonObj.get("time"); param.timeUnit = jsonObj.get("time_unit").toString(); // Add the param to the collection of params read in. addEnergyParam(param); } // DEBUG OUTPUT BLOCK ///////////////////////////////////// if (debugEnabled) { System.out.println(this.toString()); } /////////////////////////////////////////////////////////// } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (ParseException e) { e.printStackTrace(); } }
From source file:com.nubits.nubot.trading.wrappers.TradeUtilsCCEDK.java
public static String getCCDKEvalidNonce(String htmlString) { //used by ccedkqueryservice JSONParser parser = new JSONParser(); try {//from w ww .j a va2 s . com //{"errors":{"nonce":"incorrect range `nonce`=`1234567891`, must be from `1411036100` till `1411036141`"} JSONObject httpAnswerJson = (JSONObject) (parser.parse(htmlString)); JSONObject errors = (JSONObject) httpAnswerJson.get("errors"); String nonceError = (String) errors.get("nonce"); //String startStr = " must be from"; //int indexStart = nonceError.lastIndexOf(startStr) + startStr.length() + 2; //String from = nonceError.substring(indexStart, indexStart + 10); String startStr2 = " till"; int indexStart2 = nonceError.lastIndexOf(startStr2) + startStr2.length() + 2; String to = nonceError.substring(indexStart2, indexStart2 + 10); //if (to.equals(from)) { // LOG.info("Detected ! " + to + " = " + from); // return "retry"; //} return to; } catch (ParseException ex) { LOG.error(htmlString + " " + ex.toString()); return "1234567891"; } }
From source file:org.kitodo.data.elasticsearch.index.type.PropertyTypeTest.java
@Test public void shouldCreateDocument() throws Exception { PropertyType propertyType = new PropertyType(); DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); JSONParser parser = new JSONParser(); Property property = prepareData().get(0); HttpEntity document = propertyType.createDocument(property); JSONObject actual = (JSONObject) parser.parse(EntityUtils.toString(document)); JSONObject expected = (JSONObject) parser.parse( "{\"title\":\"Property1\",\"value\":\"processes\",\"workpieces\":[],\"processes\":[{\"id\":1}," + "{\"id\":2}],\"type\":\"process\",\"templates\":[],\"creationDate\":\"" + dateFormat.format(property.getCreationDate()) + "\"}"); assertEquals("Property JSONObject doesn't match to given JSONObject!", expected, actual); property = prepareData().get(1);//from w w w.ja v a2 s . c o m document = propertyType.createDocument(property); actual = (JSONObject) parser.parse(EntityUtils.toString(document)); expected = (JSONObject) parser.parse("{\"title\":\"Property2\",\"value\":\"templates\",\"workpieces\":[]," + "\"processes\":[],\"type\":\"template\",\"templates\":[{\"id\":1}],\"creationDate\":\"" + dateFormat.format(property.getCreationDate()) + "\"}"); assertEquals("Property JSONObject doesn't match to given JSONObject!", expected, actual); }
From source file:math.tools.Browse.java
/** * Creates new form jsontable//from w ww.j a va2 s . com */ public Browse() { BufferedReader in; FileOutputStream fos; new File(System.getProperty("user.home") + "//MathHelper//tools//").mkdirs(); try { URL website = new URL("https://dl.dropboxusercontent.com/u/67622419/mathTools/toolInfo.json"); ReadableByteChannel rbc = Channels.newChannel(website.openStream()); fos = new FileOutputStream(System.getProperty("user.home") + "//MathHelper//toolInfo.json"); fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE); } catch (IOException ex) { Logger.getLogger(Browse.class.getName()).log(Level.SEVERE, null, ex); } try { in = new BufferedReader( new FileReader(System.getProperty("user.home") + "//MathHelper//toolInfo.json")); String inputLine; int i = -1; JSONObject json; while ((inputLine = in.readLine()) != null) { i++; json = (JSONObject) new JSONParser().parse(inputLine); table[i][0] = json.get("name"); table[i][1] = json.get("author"); table[i][2] = json.get("rating"); File f = new File( System.getProperty("user.home") + "//MathHelper//tools//" + json.get("name") + ".jar"); if (!f.exists()) { table[i][3] = "Not Downloaded Yet"; } else { table[i][3] = "Downloaded"; } table[i][4] = json.get("adress"); } in.close(); } catch (IOException | ParseException ex) { Logger.getLogger(Browse.class.getName()).log(Level.SEVERE, null, ex); } initComponents(); }