private static String toJSON(String txt, boolean isGWTok, boolean isGWTerr) throws JSONException{ String res = null; if(txt.startsWith("[")){ JSONArray arr = new JSONArray(txt); res = arr.toString(4); } else { JSONObject obj = new JSONObject(txt); res = obj.toString(4); } if (isGWTok) { return "//OK" + res; } else if (isGWTerr) { return "//EX" + res; } else { return res; } }
/** * Parse a JSON data string into a Vector of CommentThing objects. * * @param commentsJson JSON reply to parse into Comments * @param startLevel Level of hierarchy to start at (most of the time 0) */ protected void parseComments(final String commentsJson, final int startLevel) { Vector comments = new Vector(); JSONObject listingJsonObject; try { // Recurse through any replies and their replies and ... listingJsonObject = new JSONArray(commentsJson).getJSONObject(1); recursivelyAddReplies(comments, listingJsonObject, startLevel); } catch (JSONException e) { System.out.println("Error parsing JSON response: " + e.getMessage()); } // Signal the listener when done finished = true; if (!aborted) { listener.commentsReceived(comments); } }
DisplaySnap(EncodedImage original, Bitmap img, int time, UiApplication app, JSONObject Current, String key) { _original = original; int direction = Display.DIRECTION_NORTH; Ui.getUiEngineInstance().setAcceptableDirections(direction); monApp = app; _img = img; _Current = Current; _key = key; // afficher l'image. this.addMenuItem(_ScreenShootitem); HorizontalFieldManager SnapManager = new HorizontalFieldManager(); bmp = new BitmapField(); SnapManager.add(bmp); this.add(SnapManager); t = new Timer(); t.schedule(new Chronometer(time, img), 0, 1000); }
ViewStory(JSONObject Current, UiApplication monApp) { int direction = Display.DIRECTION_NORTH; Ui.getUiEngineInstance().setAcceptableDirections(direction); _monApp = monApp; _Current = Current; this.setTitle(" CrapSnap - View Stories"); Bitmap back = EncodedImage.getEncodedImageResource("snapBack.png") .getBitmap(); this.setBackground(BackgroundFactory.createBitmapBackground(back)); // { // username: "youraccount", // timestamp: 1373207221, // req_token: create_token(auth_token, 1373207221) // } populate(); }
private void ShowScore(String Name) { SnapChatApiFx api = new SnapChatApiFx(); try { JSONObject Score = api.GetScore(Name,_Current.getString("username"),_Current.getString("auth_token")); JSONObject Friend = Score.getJSONObject(Name); JSONArray FriendsArray = Friend.getJSONArray("best_friends"); String BestString = new String(); int i = 0; for ( i = 0; i < FriendsArray.length();i++) { BestString = BestString + " " + FriendsArray.getString(i); } int score = Friend.getInt("score"); Dialog.inform(Name + "'s bests friends :" + BestString + ". Score : " + score); } catch (JSONException e) { Dialog.inform("Unable to get Score."); e.printStackTrace(); } }
/** * This function adds the layer details but also verifies that the min and max color * values don't be -1. If they are then it replaces them by the default color range of * the layer. * * @param {String} layerDetails */ public void setLayerDetails(String layerDetailsStr) { // In this case we have to update the min and max color with the // default color range of the layer. // We add the 'server' and the 'name' into the layer Details try { JSONObject layDet; if (layerDetailsStr.equals("")) { this.layerDetails = new JSONObject(); } else { this.layerDetails = new JSONObject(layerDetailsStr); if ((this.minColor == -1) && (this.maxColor == -1)) { this.minColor = Float.parseFloat((String) (((JSONArray) layerDetails.get("scaleRange")).get(0))); this.maxColor = Float.parseFloat((String) (((JSONArray) layerDetails.get("scaleRange")).get(1))); } } layerDetails.accumulate("server", server); layerDetails.accumulate("name", name); layerDetails.accumulate("srs", this.getProjection()); } catch (JSONException ex) { System.out.println("ERROR: The layerdetails JSON object can't be created on Layer class"); } }
/** * This method obtains the 'animation options' (the number of frames * available for the user selection). * @param {httpServlet} request * @param {HttpServletResponse}response * @param {PrintWriter} out * @throws ServletException * @throws IOException * @throws JSONException */ protected void getAnimationOptions(HttpServletRequest request, HttpServletResponse response, PrintWriter out) throws ServletException, IOException, JSONException, XMLFilesException { String layerName = request.getParameter("layerName"); String firstDay = request.getParameter("startDate"); String lastDay = request.getParameter("endDate"); LayerMenuManagerSingleton layers = LayerMenuManagerSingleton.getInstance(); Layer layer = layers.getLayerByName(layerName);//Search current layer //Retrieve all the times available on the first and last day of the //selected range JSONObject jsonStartDates = new JSONObject(NetCDFRequestManager.getLayerTimeStepsForAnimation(layer, firstDay, lastDay)); out.print(jsonStartDates.toString()); }
public static byte[] toByteArray(Note note) { ByteArrayOutputStream bout = new ByteArrayOutputStream(); DataOutputStream dout = new DataOutputStream(bout); JSONObject jsonNote = parseToJson(note); writeToStream(dout, jsonNote); return bout.toByteArray(); }
public static Note toNote(byte[] bytes) { ByteArrayInputStream bais = new ByteArrayInputStream(bytes); DataInputStream dis = new DataInputStream(bais); String noteFromStream = readFromStream(dis); JSONObject jsonNote = readJson(noteFromStream); Note note = parseJsonToNote(jsonNote); return note; }
private static Note parseJsonToNote(JSONObject jsonNote) { Note note = new Note( jsonNote.optString(Note.TITLE), jsonNote.optString(Note.CONTENT), jsonNote.optLong(Note.TIMESTAMP), jsonNote.optInt(Note.PRIORITY), Category.toCategory(jsonNote.optString(Note.CATEGORY)) ); return note; }
private static void writeToStream(DataOutputStream dout, JSONObject jsonNote) { try { dout.writeUTF(jsonNote.toString()); } catch (IOException e) { e.printStackTrace(); } }
private static JSONObject parseToJson(Note note) { JSONObject jsonNote = new JSONObject(); try { jsonNote.put(Note.TITLE, note.getTitle()); jsonNote.put(Note.CONTENT, note.getContent()); jsonNote.put(Note.TIMESTAMP, note.getTimestamp()); jsonNote.put(Note.PRIORITY, note.getPriority()); jsonNote.put(Note.CATEGORY, note.getCategory()); } catch (JSONException e1) { e1.printStackTrace(); } return jsonNote; }
/** * Recursively parse the given listingJsonObject for Comments, adding them * into the Vector specified. Will call itself until the comment tree is * whole (until there are no more child JSON objects to parse). * * @param comments Vector of comments * @param listingJsonObject JSON object (comment listing) to parse * @param level Depth level * @throws JSONException In case of a parsing error */ protected void recursivelyAddReplies(Vector comments, JSONObject listingJsonObject, int level) throws JSONException { JSONArray childrenJsonArray = listingJsonObject .getJSONObject("data") .getJSONArray("children"); // Reuse the same objects to avoid unnecessary overhead JSONObject thingDataObj; CommentThing comment; for (int i = 0, len = childrenJsonArray.length(); i < len && !aborted; i++) { thingDataObj = childrenJsonArray.getJSONObject(i).getJSONObject("data"); try { // Create a comment item and append it to the list comment = CommentThing.fromJson(thingDataObj); comment.setLevel(level); comments.addElement(comment); } catch (JSONException e) { System.out.println("Could not parse comment JSON: " + e.getMessage()); } // Process any further replies JSONObject repliesJsonObject = thingDataObj.optJSONObject("replies"); if (repliesJsonObject != null) { recursivelyAddReplies(comments, repliesJsonObject, level + 1); } } }
/** * Parse a login JSON response. * * A successful login response has: * - a modhash in the 'data' object * - an empty 'errors' array * * If the response doensn't meet this criteria, the login is interpreted * as failed. No further error codes are parsed in the scope of this app. * * Example of a failed login: * {"json": {"errors": [["WRONG_PASSWORD", "invalid password", "passwd"]]}} * * @param responseJson Login response as JSON */ private void parseResponse(String responseJson) { String reason = null; String modhash = null; try { JSONObject obj = new JSONObject(responseJson).getJSONObject("json"); JSONArray errors = obj.getJSONArray("errors"); JSONObject data = obj.optJSONObject("data"); if (data != null) { modhash = data.optString("modhash"); } // In case of a successful login, invoke the success callback if (errors.length() == 0 && modhash != null) { finished = true; listener.loginSucceeded(username, modhash); return; } // Otherwise try to interpret errors else if (errors.length() > 0) { String errorCode = errors.getJSONArray(0).getString(0); if ("WRONG_PASSWORD".equals(errorCode)) { reason = "wrong password"; } else if ("RATELIMIT".equals(errorCode)) { reason = "trying too often"; } } } catch (Exception e) { System.out.println("Error parsing JSON response: " + e.getMessage()); } // If the login conditions were met (or the response couldn't be parsed), // invoke the failure callback. finished = true; listener.loginFailed(reason); }
/** * Create a LinkThing from a JSON data String. * * @param obj JSONObject containing data for the Link * @return A LinkThing object * @throws JSONException If the given JSONObject can't be parsed */ public static LinkThing fromJson(JSONObject obj) throws JSONException { LinkThing thing = new LinkThing(); thing.setAuthor(obj.getString("author")); try { // "1329913184.0" -> "13299131840000" String dateStr = obj.getString("created_utc").substring(0, 9) + "0000"; thing.setCreated(new Date(Long.parseLong(dateStr))); } catch (Exception e) { System.out.println("Couldn't set date: " + e.getMessage()); } thing.setDomain(obj.getString("domain")); thing.setId(obj.getString("id")); thing.setName(obj.getString("name")); thing.setNumComments(obj.getInt("num_comments")); thing.setPermalink(obj.getString("permalink")); thing.setSubreddit(obj.getString("subreddit")); thing.setScore(obj.getInt("score")); thing.setThumbnail(obj.getString("thumbnail")); thing.setTitle(HtmlEntityDecoder.decode(obj.getString("title"))); thing.setUrl(obj.getString("url")); // 'Likes' can be true, false or null; map that to 1, -1, and 0 thing.setVote( obj.isNull("likes") ? 0 : obj.getBoolean("likes") ? 1: - 1 ); return thing; }
/** * Create a CommentThing from a JSON data String. * * @param obj JSONObject containing data for the Comment * @return A CommentThing object * @throws JSONException If the given JSONObject can't be parsed */ public static CommentThing fromJson(JSONObject obj) throws JSONException { CommentThing thing = new CommentThing(); thing.setAuthor(obj.optString("author")); thing.setBody(HtmlEntityDecoder.decode(obj.optString("body"))); // Comments have a created date, 'More' items don't if (obj.has("created_utc")) { try { // "1329913184.0" -> "13299131840000" String dateStr = obj.getString("created_utc").substring(0, 9) + "0000"; thing.setCreated(new Date(Long.parseLong(dateStr))); } catch (Exception e) { System.out.println("Couldn't set date: " + e.getMessage()); } } thing.setId(obj.optString("id")); thing.setName(obj.optString("name")); thing.setScore(obj.optInt("ups"), obj.optInt("downs")); // 'Likes' can be true, false or null; map that to 1, -1, and 0 thing.setVote( obj.isNull("likes") ? 0 : obj.getBoolean("likes") ? 1: - 1 ); // Set child IDs. These are used for dynamically fetching more replies // to a comment. JSONArray childrenArray = obj.optJSONArray("children"); if (childrenArray != null) { int len = childrenArray.length(); String[] childIds = new String[len]; for (int i = 0; i < len; i++) { childIds[i] = childrenArray.getString(i); } thing.setChildIds(childIds); } return thing; }
public JSONObject login(String _Username, String _Password) { String BAD = new String(); Long TimeStamp = new Long(System.currentTimeMillis() / 1000L); BAD = USERNAME_KEY + "=" + _Username + "&" + PASSWORD_KEY + "=" + _Password + "&" + TIMESTAMP_KEY + "=" + TimeStamp.toString() + "&" + REQ_TOKEN_KEY + "=" + tokengen(StaticToken, TimeStamp).toString(); return ExecReq(BAD, BASE_URL + LOGIN_PATH); }
public JSONObject GetScore(String Name, String Username, String Token) { Long TimeStamp = new Long(System.currentTimeMillis() / 1000L); String Request = USERNAME_KEY + "=" + Username + "&" + TIMESTAMP_KEY + "=" + TimeStamp.toString() + "&" + REQ_TOKEN_KEY + "=" + tokengen(Token, TimeStamp).toString() + "&" + "friend_usernames" + "=[\"" + Name + "\"]"; return ExecReq(Request, BASE_URL + "bq/bests"); }
public JSONObject ManageFriend(String Name, String Username, int action, String Token) { Long TimeStamp = new Long(System.currentTimeMillis() / 1000L); String Action = new String(); switch (action) { case 0: // add Action = "add"; break; case 1: // delete Action = "delete"; break; case 2: // block Action = "block"; break; case 3: // unblock Action = "unblock"; break; case 4:// display Action = "display"; break; } String Request = USERNAME_KEY + "=" + Username + "&" + TIMESTAMP_KEY + "=" + TimeStamp.toString() + "&" + REQ_TOKEN_KEY + "=" + tokengen(Token, TimeStamp).toString() + "&" + "action" + "=" + Action + "&" + "friend" + "=" + Name; return ExecReq(Request, BASE_URL + "ph/friend"); }
public JSONObject RegisterRequest(int age, String email, String password, String bithday) { Long TimeStamp = new Long(System.currentTimeMillis() / 1000L); String SendStr = "age=" + age + "×tamp=" + TimeStamp + "&req_token=" + tokengen(StaticToken, TimeStamp).toString() + "&email=" + email + "&birthday=" + bithday + "&password=" + password + ""; return ExecReq(SendStr, BASE_URL + "bq/register"); }
public JSONObject solvecaptcha(String email, String authtoken, String Solution, String id) { Long TimeStamp = new Long(System.currentTimeMillis()); String SendStr = "captcha_solution=" + Solution + "&captcha_id=" + id + "&username=" + email + "×tamp=" + TimeStamp + "&req_token=" + tokengen(authtoken, TimeStamp).toString(); return ExecReq(SendStr, BASE_URL + "bq/solve_captcha"); }
public JSONObject setusername(String email, String authtoken, String username) { Long TimeStamp = new Long(System.currentTimeMillis() / 1000L); String SendStr = "selected_username=" + username + "×tamp=" + TimeStamp + "&req_token=" + tokengen(authtoken, TimeStamp).toString() + "&username=" + email; return ExecReq(SendStr, BASE_URL + "bq/register_username"); }
public SendVideoSnap(JSONObject args, UiApplication app, ViewSnap viewSnap) { _viewSnap = viewSnap; monApp = app; Current = args; API = new SnapChatApiFx(); friendselector = new FriendSelector(Current, monApp); }
Friends(UiApplication monApps, JSONObject Current) { int direction = Display.DIRECTION_NORTH; Ui.getUiEngineInstance().setAcceptableDirections(direction); _monApps = monApps; _Current = Current; this.setTitle(" CrapSnap - Manage Friends"); Bitmap back = EncodedImage.getEncodedImageResource("Back.jpg").getBitmap(); this.setBackground(BackgroundFactory.createBitmapBackground(back)); populate(); }
public SendSnap(JSONObject args, UiApplication app, ViewSnap viewSnap) { _viewSnap = viewSnap; monApp = app; Current = args; API = new SnapChatApiFx(); friendselector = new FriendSelector(Current, monApp); }
/** * Returns the next XML meta token. This is used for skipping over <!...> * and <?...?> structures. * @return Syntax characters (<code>< > / = ! ?</code>) are returned as * Character, and strings and names are returned as Boolean. We don't care * what the values actually are. * @throws JSONException If a string is not properly closed or if the XML * is badly structured. */ public Object nextMeta() throws JSONException { char c; char q; do { c = next(); } while (isWhitespace(c)); switch (c) { case 0: throw syntaxError("Misshaped meta tag."); case '<': return XML.LT; case '>': return XML.GT; case '/': return XML.SLASH; case '=': return XML.EQ; case '!': return XML.BANG; case '?': return XML.QUEST; case '"': case '\'': q = c; for (;;) { c = next(); if (c == 0) { throw syntaxError("Unterminated string."); } if (c == q) { //#if CLDC!="1.0" //# return Boolean.TRUE; //#else return JSONObject.TRUE; //#endif } } default: for (;;) { c = next(); if (isWhitespace(c)) { //#if CLDC!="1.0" //# return Boolean.TRUE; //#else return JSONObject.TRUE; //#endif } switch (c) { case 0: case '<': case '>': case '/': case '=': case '!': case '?': case '"': case '\'': back(); //#if CLDC!="1.0" //# return Boolean.TRUE; //#else return JSONObject.TRUE; //#endif } } } }
FriendSelector(JSONObject Current, UiApplication app) { int direction = Display.DIRECTION_NORTH; Ui.getUiEngineInstance().setAcceptableDirections(direction); this.setTitle(" CrapSnap - Select Receiver..."); Bitmap back = EncodedImage.getEncodedImageResource("Back.jpg") .getBitmap(); this.setBackground(BackgroundFactory.createBitmapBackground(back)); monApp = app; Send.setChangeListener(new FieldChangeListener() { public void fieldChanged(Field field, int context) { exitbol = false; if (CheckBox.getChecked() == true) { storybol = true; } quit(); } }); String[] names; try { JSONArray friends = Current.getJSONArray("friends"); names = new String[friends.length()]; for (int i = 0; i < friends.length(); i++) { JSONObject friend = friends.getJSONObject(i); names[i] = friend.getString("name"); } Comparator strComparator = new Comparator() { public int compare(Object o1, Object o2) { return o1.toString().compareTo(o2.toString()); } }; Arrays.sort(names, strComparator); for (int i = 0; i < names.length; i++) { ListManager.add(new FriendSelectorObject(names[i])); ListManager.add(new SeparatorField()); } } catch (JSONException e) { e.printStackTrace(); } this.addMenuItem(AddMenuItem); this.addMenuItem(CancelMenuItem); BtnManager.add(Send); MainManager.add(ListManager); HorizontalFieldManager StoryManager = new HorizontalFieldManager(); CheckBox.setFont(CheckBox.getFont().derive(Font.BOLD, 9, Ui.UNITS_pt)); StoryManager.add(new LabelField(" ")); StoryManager.add(CheckBox); MainManager.add(StoryManager); MainManager.add(BtnManager); this.add(MainManager); }
StoryViewers(JSONArray MyStory){ this.setTitle("Who has viewed my story ?"); Bitmap back = EncodedImage.getEncodedImageResource("Back.jpg").getBitmap(); this.setBackground(BackgroundFactory.createBitmapBackground(back)); for (int i = 0; i < MyStory.length(); i++){ JSONObject Storycore; try { Storycore = MyStory.getJSONObject(i).getJSONObject("story"); byte[] img = getImage( Storycore.getString("thumbnail_url"), Storycore.getString("thumbnail_iv"), Storycore.getString("media_key")); String Caption = Storycore.getString("caption_text_display"); if (Caption.equals("")){ Caption = "Not Named Story."; } JSONObject StoryExtra = MyStory.getJSONObject(i).getJSONObject("story_extras"); int viewcount = StoryExtra.getInt("view_count"); JSONArray StoryNotes = MyStory.getJSONObject(i).getJSONArray("story_notes"); String ViwerString = ""; for (int j = 0; j < StoryNotes.length(); j++ ){ if (ViwerString.equals("")){ ViwerString = StoryNotes.getJSONObject(j).getString("viewer"); } else { ViwerString = ViwerString + ", " + StoryNotes.getJSONObject(j).getString("viewer") ; } } Bitmap bmp = EncodedImage.createEncodedImage(img, 0, img.length).getBitmap(); list.add( new Object[] {bmp,Caption, "Viewed " + viewcount + " time(s)",ViwerString}); } catch (JSONException e) { e.printStackTrace(); } list.setCommand(new Command(new CommandHandler(){ public void execute(ReadOnlyCommandMetadata metadata, Object context) { String viewers = (String) list.get(list.getFocusRow())[3]; Dialog.inform("Viewed by : " + viewers); } })); } }
private static void createNewSession() { String name = newSessionNameTextBox.getText(); String grid_size = newSessionSizeTextBox.getText(); System.out.println("New Session Name: " + newSessionNameTextBox.getText()); closeSessionPopup(); HttpClient httpclient = new DefaultHttpClient(); int port = CalicoDataStore.ServerPort; try { HttpPost httppost = new HttpPost("http://" + CalicoDataStore.ServerHost + ":27015/api/sessions"); String requestParams = ""; requestParams += "name=" + URLEncoder.encode(name, "utf-8"); requestParams += "&rows=" + URLEncoder.encode(grid_size, "utf-8"); requestParams += "&cols=" + URLEncoder.encode(grid_size, "utf-8"); InputStreamEntity inputEntity = new InputStreamEntity(new ByteArrayInputStream(requestParams.getBytes()), -1); inputEntity.setContentType("application/x-www-form-urlencoded"); inputEntity.setChunked(false); httppost.setEntity(inputEntity); // System.out.println("executing request " + httpget.getURI()); // Create a response handler ResponseHandler<String> responseHandler = new BasicResponseHandler(); String responseBody = httpclient.execute(httppost, responseHandler); JSONObject sessionObj = new JSONObject(responseBody); port = sessionObj.getJSONObject("calico_server").getInt("port"); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { // When HttpClient instance is no longer needed, // shut down the connection manager to ensure // immediate deallocation of all system resources httpclient.getConnectionManager().shutdown(); } // reconnect(CalicoDataStore.ServerHost, port); showSessionPopup(); }
/** * Convert a well-formed (but not necessarily valid) XML string into a * JSONObject. Some information may be lost in this transformation * because JSON is a data format and XML is a document format. XML uses * elements, attributes, and content text, while JSON uses unordered * collections of name/value pairs and arrays of values. JSON does not * does not like to distinguish between elements and attributes. * Sequences of similar elements are represented as JSONArrays. Content * text may be placed in a "content" member. Comments, prologs, DTDs, and * <code><[ [ ]]></code> are ignored. * @param string The source string. * @return A JSONObject containing the structured data from the XML string. * @throws JSONException */ public static JSONObject toJSONObject(String string) throws JSONException { JSONObject o = new JSONObject(); XMLTokener x = new XMLTokener(string); while (x.more()) { x.skipPast("<"); parse(x, o, null); } return o; }