public void generateObjects(String arrayName, Object... parent) { if (mRec == null) return; Object rawObj; try { rawObj = mParser.parse(mJson); if (rawObj == null) return; JSONObject obj = (JSONObject) rawObj; JSONArray arr = (JSONArray) obj.get(arrayName); int cnt = 0; if (arr != null) { for (Object jb : arr.toArray()) // each object { JSONObject jo = (JSONObject) jb; mCls.getConstructors()[0].setAccessible(true); Object w; if (parent != null && parent.length != 0) // Inner class w = mCls.getConstructors()[0].newInstance(parent[0]); else { w = mCls.getConstructors()[0].newInstance((Object) null); } for (Field f : mCls.getDeclaredFields()) // each field { try { Object fieldVal = jo.get(f.getName()); if (fieldVal == null) continue; if (f.getType() == Integer.class) f.set(w, Integer.parseInt(fieldVal.toString())); else if (f.getType() == Date.class) f.set(w, new Date(Long.parseLong(fieldVal.toString()))); else if (f.getType() == String.class) f.set(w, fieldVal.toString()); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } } mRec.receiveObject(w); } } } catch (ParseException e1) { e1.printStackTrace(); } catch (IllegalArgumentException e1) { e1.printStackTrace(); } catch (SecurityException e1) { e1.printStackTrace(); } catch (InstantiationException e1) { e1.printStackTrace(); } catch (IllegalAccessException e1) { e1.printStackTrace(); } catch (InvocationTargetException e1) { e1.printStackTrace(); } }
public Object toJSonObject(Integer column, String[] rowsRefStr) { Object jsonObject = new JSONObject(); JSONParser parser = new JSONParser(); String[] tempStr = new String[rowsRefStr.length]; Integer refPos = -1; String titleValue = ""; for (int i = 0; i < resultsRows.size(); i++) { titleValue = resultsRows.get(i).columnValues[1]; for (int j = 0; j < rowsRefStr.length; j++) { if (titleValue.equals(rowsRefStr[j])) { refPos = j; break; } } tempStr[refPos] = resultsRows.get(i).toJSonObject(column).toString(); } try { jsonObject = parser.parse(Arrays.toString(tempStr)); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } return jsonObject; }
/* Returns map of Wikipedia page-ids to number of inlinks to those pages. Page ids are pages the string 'anchor' points to in Wikipedia */ public Map<Long, Integer> getPagesMap(String anchor) { db.requestStart(); Map<Long, Integer> PageCollection = new HashMap<Long, Integer>(); BasicDBObject query = new BasicDBObject(); query.put("anchor", anchor); BasicDBObject fields = new BasicDBObject("page_id", true) .append("pages", true) .append("page_freq", true) .append("anchor_freq", true) .append("_id", false); DBObject ans = table.findOne(query, fields); // System.out.println("num of results = "+curs.count()); db.requestDone(); if (ans != null) { JSONParser jp = new JSONParser(); JSONArray jo = null; try { // System.out.println(ans.get("pages")); jo = (JSONArray) jp.parse(ans.get("pages").toString()); } catch (ParseException e) { e.printStackTrace(); } // System.out.println("Link Freq = "+o.get("anchPageFreq").toString()); for (int i = 0; i < jo.size(); i++) { JSONObject object = (JSONObject) jo.get(i); Long pId = (long) (object.get("page_id")); Long pValue0 = (long) object.get("page_freq"); int pValue = pValue0.intValue(); if (PageCollection.containsKey(pId)) { pValue = PageCollection.get(pId) + pValue; } PageCollection.put(pId, pValue); } } return PageCollection; } // End getPagesMap()
public Object toJSonObjectHeatMap() { Object jsonObject = new JSONObject(); JSONParser parser = new JSONParser(); ArrayList<String> tempArrStr = new ArrayList<String>(); for (int i = 0; i < varXUnique.size(); i++) { for (int j = 0; j < varYUnique.size(); j++) { tempArrStr.add( "{\"varX\":" + (i + 1) + ", \"varY\":" + (j + 1) + ", \"value\":" + _heatMap[i][j] + "}"); } } try { jsonObject = parser.parse(tempArrStr.toString()); } catch (ParseException e) { e.printStackTrace(); } return jsonObject; }
public static int getMatchID(int matchNumber) { int id = 0; try { JSONParser parser = new JSONParser(); FileReader file = new FileReader(saveFile); Object obj = parser.parse(file); JSONObject saveFileJSON = (JSONObject) obj; file.close(); id = Integer.parseInt(saveFileJSON.get("match" + matchNumber + "ID").toString()); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (ParseException e) { e.printStackTrace(); } return id; }
private void connectImpl() throws IOException, ClientProtocolException, ConnectException { LOGGER.info("connecting to slack"); lastPingSent = 0; lastPingAck = 0; HttpClient httpClient = getHttpClient(); HttpGet request = new HttpGet(SLACK_HTTPS_AUTH_URL + authToken); HttpResponse response; response = httpClient.execute(request); LOGGER.debug(response.getStatusLine().toString()); String jsonResponse = CharStreams.toString(new InputStreamReader(response.getEntity().getContent())); SlackJSONSessionStatusParser sessionParser = new SlackJSONSessionStatusParser(jsonResponse); try { sessionParser.parse(); } catch (ParseException e1) { LOGGER.error(e1.toString()); } if (sessionParser.getError() != null) { LOGGER.error("Error during authentication : " + sessionParser.getError()); throw new ConnectException(sessionParser.getError()); } users = sessionParser.getUsers(); channels = sessionParser.getChannels(); sessionPersona = sessionParser.getSessionPersona(); team = sessionParser.getTeam(); LOGGER.info("Team " + team.getId() + " : " + team.getName()); LOGGER.info("Self " + sessionPersona.getId() + " : " + sessionPersona.getUserName()); LOGGER.info(users.size() + " users found on this session"); LOGGER.info(channels.size() + " channels found on this session"); String wssurl = sessionParser.getWebSocketURL(); LOGGER.debug("retrieved websocket URL : " + wssurl); ClientManager client = ClientManager.createClient(); if (proxyAddress != null) { client .getProperties() .put(ClientProperties.PROXY_URI, "http://" + proxyAddress + ":" + proxyPort); } final MessageHandler handler = this; LOGGER.debug("initiating connection to websocket"); try { websocketSession = client.connectToServer( new Endpoint() { @Override public void onOpen(Session session, EndpointConfig config) { session.addMessageHandler(handler); } }, URI.create(wssurl)); } catch (DeploymentException e) { LOGGER.error(e.toString()); } if (websocketSession != null) { SlackConnectedImpl slackConnectedImpl = new SlackConnectedImpl(sessionPersona); dispatcher.dispatch(slackConnectedImpl); LOGGER.debug("websocket connection established"); LOGGER.info("slack session ready"); } }
private Trie parseGenesis() { JSONParser parser = new JSONParser(); JSONObject genesisMap = null; try { genesisMap = (JSONObject) parser.parse(GENESIS_JSON); } catch (ParseException e) { e.printStackTrace(); System.exit(-1); } Set<String> keys = genesisMap.keySet(); Trie state = new SecureTrie(null); for (String key : keys) { JSONObject val = (JSONObject) genesisMap.get(key); String denom = (String) val.keySet().toArray()[0]; String value = (String) val.values().toArray()[0]; BigInteger wei = Denomination.valueOf(denom.toUpperCase()).value().multiply(new BigInteger(value)); AccountState acctState = new AccountState(BigInteger.ZERO, wei); byte[] keyB = Hex.decode(key); state.update(keyB, acctState.getEncoded()); premine.put(wrap(keyB), acctState); } return state; }
public static long getResumeTime() { long time = 0; try { JSONParser parser = new JSONParser(); FileReader file = new FileReader(saveFile); Object obj = parser.parse(file); JSONObject saveFileJSON = (JSONObject) obj; file.close(); time = Long.parseLong(saveFileJSON.get("resumeTime").toString()); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (ParseException e) { e.printStackTrace(); } return time; }
public void loadConfig() { AssetManager am = mApp.getAssets(); BufferedReader br = null; StringBuilder sb = new StringBuilder(); try { br = new BufferedReader(new InputStreamReader(am.open("news_config.xml"))); String line; while ((line = br.readLine()) != null) { sb.append(line); } } catch (IOException e) { e.printStackTrace(); } finally { try { if (br != null) br.close(); } catch (IOException e) { e.printStackTrace(); } } JSONParser parser = new JSONParser(); JSONObject jobj; try { jobj = (JSONObject) parser.parse(sb.toString()); for (Object key : jobj.keySet()) { mProp.put(key, jobj.get(key)); } } catch (ParseException e) { e.printStackTrace(); } }
public static long getAccID() { long id = 0; try { JSONParser parser = new JSONParser(); FileReader file = new FileReader(saveFile); Object obj = parser.parse(file); JSONObject saveFileJSON = (JSONObject) obj; file.close(); id = Long.parseLong(saveFileJSON.get("accID").toString()); } catch (NumberFormatException e) { Refresh.validID = false; System.out.println("ID had an invalid character"); return 0; } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (ParseException e) { e.printStackTrace(); } return id; }
public void read(Reader reader) { JSONParser jparser = new JSONParser(); try { JSONObject root = (JSONObject) jparser.parse(reader); if (root.containsKey("type")) { TYPE type = TYPE.valueOf((String) root.get("type")); switch (type) { case NOTIFICATION: readNotification(root); break; case ABM_CONTENIDO: readABMContenido(root); break; default: break; } } reader.close(); } catch (IOException e) { e.printStackTrace(); } catch (ParseException e) { e.printStackTrace(); } }
@Override public void run() { // TODO Auto-generated method stub try { this.in = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF-8")); JSONObject message; int i = 0; // receive the first several messages while (i < 4) { message = (JSONObject) parser.parse(in.readLine()); MessageReceive(socket, message); i++; } while (run) { System.out.print("[" + room_id + "] " + identity + "> "); message = (JSONObject) parser.parse(in.readLine()); MessageReceive(socket, message); } System.exit(0); in.close(); socket.close(); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
public static Machine fromString(String input) { JSONObject machine = null; try { machine = (JSONObject) new JSONParser().parse(input); } catch (ParseException e) { e.printStackTrace(); } JSONObject cutObj = (JSONObject) machine.get("cuttingface"); Block cutFace = Bukkit.getWorld((String) cutObj.get("world")) .getBlockAt( (Integer) getNumber((String) cutObj.get("x")), (Integer) getNumber((String) cutObj.get("y")), (Integer) getNumber((String) cutObj.get("z"))); OfflinePlayer owner = Bukkit.getOfflinePlayer(UUID.fromString((String) machine.get("owner"))); JSONObject dis = (JSONObject) machine.get("dispenser"); Block dispenser = Bukkit.getWorld((String) dis.get("world")) .getBlockAt( (Integer) getNumber((String) dis.get("x")), (Integer) getNumber((String) dis.get("y")), (Integer) getNumber((String) dis.get("z"))); return new Machine(cutFace, dispenser, owner); }
/** @return a {@link JSONObject} describing the {@link Entity} */ public JSONObject getJsonDescriptor() { String jsonDescription = "{\"" + JsonStrings.ENTITY + "\":" + "{\"" + JsonStrings.ENTITY_ID + "\":\"" + this.getEntityID() + "\"," + "\"" + JsonStrings.ENTITY_TYPE + "\":\"" + this.getEntityType().name() + "\"," + "\"" + JsonStrings.DISTANCE_RANGE + "\":\"" + this.getDistanceRange().name() + "\"," + "\"" + JsonStrings.PROPERTIES + "\":" + this.getProperties() + "}}"; JSONParser parser = new JSONParser(); try { return ((JSONObject) parser.parse(jsonDescription)); } catch (ParseException e) { e.printStackTrace(); return null; } }
protected String doInBackground(String... urls) { try { downloadurl(urls[0]); if (jresult.contains("false")) { empty = "no match"; } else { empty = ""; JSONParser parser = new JSONParser(); JSONObject object = (JSONObject) parser.parse(jresult); JSONObject objectr = (JSONObject) object.get("result"); JSONObject objectc = null; objectc = (JSONObject) object.get("chart"); JSONObject objecty1 = (JSONObject) objectc.get("year1"); JSONObject objecty2 = (JSONObject) objectc.get("year5"); JSONObject objecty3 = (JSONObject) objectc.get("year10"); chart1 = new ImageGetter() { @Override public Drawable getDrawable(String source) { // TODO Auto-generated method stub return imageload(source, true); } }.getDrawable((String) objecty1.get("url")); chart2 = new ImageGetter() { @Override public Drawable getDrawable(String source) { // TODO Auto-generated method stub return imageload(source, true); } }.getDrawable((String) objecty2.get("url")); chart3 = new ImageGetter() { @Override public Drawable getDrawable(String source) { // TODO Auto-generated method stub return imageload(source, true); } }.getDrawable((String) objecty3.get("url")); // String image = "<img src = '" +(String) objectr.get("imgu") + "'/>"; image1 = imageload((String) objectr.get("imgu"), false); image2 = imageload((String) objectr.get("imgd"), false); } } catch (IOException e) { e.printStackTrace(); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; }
@Before public void parseMessages() { JSONParser parser = new JSONParser(); try { joinedMessage = (JSONObject) parser.parse(joinedMessageString); } catch (ParseException e) { e.printStackTrace(); } }
public SmsBalance getBalance() throws IOException { HttpsURLConnection connection = getConnection(BALANCE_ENDPOINT); try { return SmsBalance.fromJson( (JSONObject) new JSONParser().parse(new InputStreamReader(connection.getInputStream()))); } catch (ParseException e) { e.printStackTrace(); throw new RuntimeException("Invalid response"); } }
private JSONObject parseObject(String json) { JSONParser parser = new JSONParser(); try { JSONObject object = (JSONObject) parser.parse(json); return object; } catch (ParseException e) { e.printStackTrace(); return null; } }
/** * Takes JSON representing a Robot and decodes it into a Robot * * @param r JSON text for a Robot * @return Decoded Robot object */ public Robot decodeRobotJSON(String r) { Object obj = null; // Attempt to parse string try { obj = parser.parse(r); } catch (ParseException e) { e.printStackTrace(); } // Cast Object to jsonObject JSONObject jsonObject = (JSONObject) ((JSONObject) obj).get("script"); // Take array of code JSONArray JSONCode = (JSONArray) jsonObject.get("code"); // Make instruction map Map<String, ForthObject> code = new TreeMap<String, ForthObject>(); // Loop through code array converting each entry into a ForthObject for (int i = 0; i < JSONCode.size(); i++) { JSONObject forth = (JSONObject) JSONCode.get(i); String name = null; ForthObject v = null; // Handle case where object was a variable if (forth.containsKey("variable")) { name = (String) forth.get("variable"); v = new ForthVariable(name); } // Handle case where object was a word else if (forth.containsKey("word")) { forth = (JSONObject) forth.get("word"); name = (String) forth.get("name"); v = new ForthWord(name, (String) forth.get("body")); } // Insert ForthObject into dictionary code.put(name, v); } // Create new Robot with values from jsonObject Robot newRobot = new Robot( ((Long) jsonObject.get("health")).intValue(), ((Long) jsonObject.get("firepower")).intValue(), ((Long) jsonObject.get("movement")).intValue(), ((Long) jsonObject.get("serial")).intValue(), code); // Get metadata values from jsonObject newRobot.setName((String) jsonObject.get("name")); return newRobot; }
private String unPack(String json, String key) { try { JSONParser jsonParser = new JSONParser(); JSONObject jsonObject = (JSONObject) jsonParser.parse(json); String command = (String) jsonObject.get(key); return command; } catch (ParseException e) { System.err.println("Blad PARSOWANIA!" + e.getMessage()); } return "error"; }
/** * レスポンスボディをJSONで取得. * * @return JSONオブジェクト */ public JSONObject bodyAsJson() { String res = null; res = this.bodyWriter.toString(); JSONObject jsonobject = null; try { jsonobject = (JSONObject) new JSONParser().parse(res); } catch (ParseException e) { fail(e.getMessage()); } return jsonobject; }
/** * Returns the report for each county in a given state. * * @param state The name of the desired state * @return a list[report] */ public ArrayList<Report> getCountiesByState(String state, boolean test) { String query; if (test) { query = String.format( "SELECT data FROM demographics WHERE state=? COLLATE NOCASE LIMIT %d", this.HARDWARE); } else { query = "SELECT data FROM demographics WHERE state=? COLLATE NOCASE"; } PreparedStatement preparedQuery = null; ResultSet rs = null; try { preparedQuery = this.connection.prepareStatement(query); } catch (SQLException e) { System.err.println("Could not build SQL query for local database."); e.printStackTrace(); } try { preparedQuery.setString(1, state); } catch (SQLException e) { System.err.println("Could not build prepare argument: state"); e.printStackTrace(); } try { rs = preparedQuery.executeQuery(); } catch (SQLException e) { System.err.println("Could not execute query."); e.printStackTrace(); } ArrayList<Report> result = new ArrayList<Report>(); try { while (rs.next()) { String raw_result = rs.getString(1); Report parsed = null; if (test) { parsed = new Report(((JSONObject) this.parser.parse(raw_result))); } else { parsed = new Report(((JSONObject) this.parser.parse(raw_result))); } result.add(parsed); } } catch (SQLException e) { System.err.println("Could not iterate through query."); e.printStackTrace(); } catch (ParseException e) { System.err.println( "Could not convert the response from getCountiesByState; a parser error occurred."); e.printStackTrace(); } return result; }
void copyfs(int ver, String outputdir) { try { superBlock.copyfs(ver, outputdir, file); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
void switchVersion(int ver) { try { superBlock.loadDMap(ver, file); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
// get one map object from json text @SuppressWarnings("rawtypes") public static Map getJsonObject(String jsonText) { Map map = null; try { map = (Map) parser.parse(jsonText, containerFactory); } catch (org.json.simple.parser.ParseException e) { e.printStackTrace(); } return map; }
public Entity(Parcel parcel) { this.entityID = parcel.readString(); this.entityType = Type.valueOf(parcel.readString()); this.distanceRange = DistanceRange.valueOf(parcel.readString()); JSONParser parser = new JSONParser(); try { this.properties = (JSONObject) parser.parse(parcel.readString()); } catch (ParseException e) { e.printStackTrace(); } }
public void setMetricSpec(int sessionId, String metricMap) { try { HashMap<String, Object> metricJMap = JsonParser.parseJSONToJava(metricMap); LimesUser lu = UserManager.getInstance().getUser(sessionId); log.info(metricMap); lu.setMetricMap(metricJMap); lu.setNoUsageTime(0); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
// get List of map from json text array @SuppressWarnings({"rawtypes", "unchecked"}) public static List<Map> getJsonObjects(String jsonText) { List<Map> maps = null; try { maps = (List<Map>) parser.parse(jsonText, containerFactory); } catch (org.json.simple.parser.ParseException e) { e.printStackTrace(); } return maps; }
public void setSpecification(int sessionId, String source, String target) { try { HashMap<String, Object> sourceMap = JsonParser.parseJSONToJava(source); HashMap<String, Object> targetMap = JsonParser.parseJSONToJava(target); LimesUser lu = UserManager.getInstance().getUser(sessionId); lu.setSourceMap(sourceMap); lu.setTargetMap(targetMap); lu.setNoUsageTime(0); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
// Takes a string in JSON format and outputs a JSON object @SuppressWarnings("unchecked") static JSONObject stringToJSON(String jsonString) { JSONParser parser = new JSONParser(); JSONObject json = new JSONObject(); try { json = (JSONObject) parser.parse(jsonString); } catch (ParseException e) { e.printStackTrace(); } return json; }