private JSONArray enrichProperties(String operatorClass, JSONArray properties) throws JSONException { JSONArray result = new JSONArray(); for (int i = 0; i < properties.length(); i++) { JSONObject propJ = properties.getJSONObject(i); String propName = WordUtils.capitalize(propJ.getString("name")); String getPrefix = (propJ.getString("type").equals("boolean") || propJ.getString("type").equals("java.lang.Boolean")) ? "is" : "get"; String setPrefix = "set"; OperatorClassInfo oci = getOperatorClassWithGetterSetter( operatorClass, setPrefix + propName, getPrefix + propName); if (oci == null) { result.put(propJ); continue; } MethodInfo setterInfo = oci.setMethods.get(setPrefix + propName); MethodInfo getterInfo = oci.getMethods.get(getPrefix + propName); if ((getterInfo != null && getterInfo.omitFromUI) || (setterInfo != null && setterInfo.omitFromUI)) { continue; } if (setterInfo != null) { addTagsToProperties(setterInfo, propJ); } else if (getterInfo != null) { addTagsToProperties(getterInfo, propJ); } result.put(propJ); } return result; }
public String toJSONString() { return "{" + JSONObject.quote(this.aString) + ":" + JSONObject.doubleToString(this.aNumber) + "}"; }
/*package*/ static PagableResponseList<UserList> createPagableUserListList( HttpResponse res, Configuration conf) throws TwitterException { try { if (conf.isJSONStoreEnabled()) { TwitterObjectFactory.clearThreadLocalMap(); } JSONObject json = res.asJSONObject(); JSONArray list = json.getJSONArray("lists"); int size = list.length(); PagableResponseList<UserList> users = new PagableResponseListImpl<UserList>(size, json, res); for (int i = 0; i < size; i++) { JSONObject userListJson = list.getJSONObject(i); UserList userList = new UserListJSONImpl(userListJson); users.add(userList); if (conf.isJSONStoreEnabled()) { TwitterObjectFactory.registerJSONObject(userList, userListJson); } } if (conf.isJSONStoreEnabled()) { TwitterObjectFactory.registerJSONObject(users, json); } return users; } catch (JSONException jsone) { throw new TwitterException(jsone); } }
/** Creates a CookieList from an empty string. */ @Test public void emptyStringCookieList() { String cookieStr = ""; String expectedCookieStr = ""; JSONObject jsonObject = CookieList.toJSONObject(cookieStr); assertTrue(jsonObject.length() == 0); }
private void getTrafficSpots() { controller.showProgressBar(); String uploadWebsite = "http://" + controller.selectedCity.URL + "/php/trafficstatus.cache?dummy=ert43"; String[] ArrayOfData = null; StreamConnection c = null; InputStream s = null; StringBuffer b = new StringBuffer(); String url = uploadWebsite; System.out.print(url); try { c = (StreamConnection) Connector.open(url); s = c.openDataInputStream(); int ch; int k = 0; while ((ch = s.read()) != -1) { System.out.print((char) ch); b.append((char) ch); } // System.out.println("b"+b); try { JSONObject ff1 = new JSONObject(b.toString()); String data1 = ff1.getString("locations"); JSONArray jsonArray1 = new JSONArray(data1); Vector TrafficStatus = new Vector(); for (int i = 0; i < jsonArray1.length(); i++) { System.out.println(jsonArray1.getJSONArray(i).getString(3)); double aDoubleLat = Double.parseDouble(jsonArray1.getJSONArray(i).getString(1)); double aDoubleLon = Double.parseDouble(jsonArray1.getJSONArray(i).getString(2)); System.out.println(aDoubleLat + " " + aDoubleLon); TrafficStatus.addElement( new LocationPointer( jsonArray1.getJSONArray(i).getString(3), (float) aDoubleLon, (float) aDoubleLat, 1, true)); } controller.setCurrentScreen(controller.TrafficSpots(TrafficStatus)); } catch (Exception E) { controller.setCurrentScreen(traf); new Thread() { public void run() { controller.showAlert("Error in network connection.", Alert.FOREVER, AlertType.INFO); } }.start(); } } catch (Exception e) { controller.setCurrentScreen(traf); new Thread() { public void run() { controller.showAlert("Error in network connection.", Alert.FOREVER, AlertType.INFO); } }.start(); } }
/** CookieList from a JSONObject with valid key and null value */ @Test public void convertCookieListWithNullValueToString() { JSONObject jsonObject = new JSONObject(); jsonObject.put("key", JSONObject.NULL); String cookieToStr = CookieList.toString(jsonObject); assertTrue("toString() should be empty", "".equals(cookieToStr)); }
private static JSONValue toJSON(SerValue serValue) { if (serValue.isString()) { return new JSONString(serValue.asString()); } else if (serValue.isReal()) { return new JSONNumber(serValue.asReal()); } else if (serValue.isArray()) { SerArray serArray = serValue.asArray(); JSONArray jsonArray = new JSONArray(); for (int i = 0; i != serArray.size(); ++i) { jsonArray.set(i, toJSON(serArray.get(i))); } return jsonArray; } else if (serValue.isObject()) { SerObject serObject = serValue.asObject(); JSONObject jsonObject = new JSONObject(); for (String key : serObject.keySet()) { jsonObject.put(key, toJSON(serObject.get(key))); } return jsonObject; } else { throw new IllegalArgumentException(); } }
/** * Construct a JSONObject from a ResourceBundle. * * @param baseName The ResourceBundle base name. * @param locale The Locale to load the ResourceBundle for. * @throws JSONException If any JSONExceptions are detected. */ public JSONObject(String baseName, Locale locale) throws JSONException { this(); ResourceBundle bundle = ResourceBundle.getBundle(baseName, locale, Thread.currentThread().getContextClassLoader()); // Iterate through the keys in the bundle. Enumeration keys = bundle.getKeys(); while (keys.hasMoreElements()) { Object key = keys.nextElement(); if (key instanceof String) { // Go through the path, ensuring that there is a nested JSONObject for each // segment except the last. Add the value using the last segment's name into // the deepest nested JSONObject. String[] path = ((String) key).split("\\."); int last = path.length - 1; JSONObject target = this; for (int i = 0; i < last; i += 1) { String segment = path[i]; JSONObject nextTarget = target.optJSONObject(segment); if (nextTarget == null) { nextTarget = new JSONObject(); target.put(segment, nextTarget); } target = nextTarget; } target.put(path[last], bundle.getString((String) key)); } } }
@Test public void testEmptyObject() { String json = "{}"; JSONObject o = parseJSON(json); assert o.getValue("noValue") == null; }
/** * Encodes {@code value}. * * @param value a {@link JSONObject}, {@link JSONArray}, String, Boolean, Integer, Long, Double or * null. May not be {@link Double#isNaN() NaNs} or {@link Double#isInfinite() infinities}. * @return this stringer. */ public JSONStringer value(Object value) throws JSONException { if (stack.isEmpty()) { throw new JSONException("Nesting problem"); } if (value instanceof JSONArray) { ((JSONArray) value).writeTo(this); return this; } else if (value instanceof JSONObject) { ((JSONObject) value).writeTo(this); return this; } beforeValue(); if (value == null || value instanceof Boolean || value == JSONObject.NULL) { out.append(value); } else if (value instanceof Number) { out.append(JSONObject.numberToString((Number) value)); } else { string(value.toString()); } return this; }
/** * Blacklisting apps. * * @param code - Operation code. * @param data - Data required(Application data). */ public void blacklistApps(String code, String data) { ArrayList<DeviceAppInfo> apps = appList.getInstalledApps(); JSONArray appList = new JSONArray(); String identity = null; try { JSONObject resultApp = new JSONObject(data); if (!resultApp.isNull(resources.getString(R.string.intent_extra_data))) { resultApp = (JSONObject) resultApp.get(resources.getString(R.string.intent_extra_data)); } identity = (String) resultApp.get(resources.getString(R.string.intent_extra_identity)); } catch (JSONException e) { Log.e(TAG, "Invalid JSON format." + e); } for (DeviceAppInfo app : apps) { JSONObject result = new JSONObject(); try { result.put(resources.getString(R.string.intent_extra_name), app.getAppname()); result.put(resources.getString(R.string.intent_extra_package), app.getPackagename()); if (identity.trim().equals(app.getPackagename())) { result.put(resources.getString(R.string.intent_extra_not_violated), false); result.put(resources.getString(R.string.intent_extra_package), app.getPackagename()); } else { result.put(resources.getString(R.string.intent_extra_not_violated), true); } } catch (JSONException e) { Log.e(TAG, "Invalid JSON format." + e); } appList.put(result); } resultBuilder.build(code, appList); }
/** * Make a prettyprinted JSON text of this JSONArray. Warning: This method assumes that the data * structure is acyclical. * * @param indentFactor The number of spaces to add to each level of indentation. * @param indent The indention of the top level. * @return a printable, displayable, transmittable representation of the array. * @throws JSONException */ String toString(int indentFactor, int indent) throws JSONException { int len = length(); if (len == 0) { return "[]"; } int i; StringBuffer sb = new StringBuffer("["); if (len == 1) { sb.append(JSONObject.valueToString(this.myArrayList.get(0), indentFactor, indent)); } else { int newindent = indent + indentFactor; sb.append('\n'); for (i = 0; i < len; i += 1) { if (i > 0) { sb.append(",\n"); } for (int j = 0; j < newindent; j += 1) { sb.append(' '); } sb.append(JSONObject.valueToString(this.myArrayList.get(i), indentFactor, newindent)); } sb.append('\n'); for (i = 0; i < indent; i += 1) { sb.append(' '); } } sb.append(']'); return sb.toString(); }
/** * Serializa el bean en formato JSON * * @param json objeto donde se escribirá el bean en formato JSON * @throws es.tid.serial.json.JSONException Cuando se produce un error en la serialización del * bean */ public void toJSON(JSONObject json) throws JSONException { JSONObject jObject; json.put("propertyUri", this.getPropertyUri()); json.put("value", this.getValue()); JSONArray jArray; JSONArray jObjectArray; }
/** * Write the contents of the JSONArray as JSON text to a writer. For compactness, no whitespace is * added. * * <p>Warning: This method assumes that the data structure is acyclical. * * @param writer Writer * @param indentFactor The number of spaces to add to each level of indentation. * @param indent The indention of the top level. * @return The writer. * @throws JSONException Error */ Writer write(Writer writer, int indentFactor, int indent) throws JSONException { try { boolean commanate = false; int length = this.length(); writer.write('['); if (length == 1) { JSONObject.writeValue(writer, this.myArrayList.get(0), indentFactor, indent); } else if (length != 0) { final int newindent = indent + indentFactor; for (int i = 0; i < length; i += 1) { if (commanate) { writer.write(','); } if (indentFactor > 0) { writer.write('\n'); } JSONObject.indent(writer, newindent); JSONObject.writeValue(writer, this.myArrayList.get(i), indentFactor, newindent); commanate = true; } if (indentFactor > 0) { writer.write('\n'); } JSONObject.indent(writer, indent); } writer.write(']'); return writer; } catch (IOException e) { throw new JSONException(e); } }
private void specificView(ViewContext ctx, JSONObject data, boolean showBullets) throws JSONException { ctx.respond( "#module %s #plain module -- %s", data.getString("name"), data.getString("description")); final String[] examples = data.getStringArray("examples"); if (examples == null || examples.length == 0) { ctx.respond("No examples available"); } else { ctx.respond("Examples:"); for (String example : examples) { final MessageBuilder builder = ctx.buildResponse(); builder.add(showBullets ? MessageBuilder.BULLET + " " : " "); for (String piece : example.split(" ")) { if (piece.length() > 1 && piece.startsWith(".")) { builder.add("#command %s ", new Object[] {piece}); } else if (piece.length() > 2 && piece.startsWith("_") && piece.endsWith("_")) { builder.add("#argument %s ", new Object[] {piece.substring(1, piece.length() - 1)}); } else { builder.add("%s ", new Object[] {piece}); } } builder.send(); } } }
/** * Wipe the device. * * @param code - Operation code. * @param data - Data required by the operation(PIN). */ public void wipeDevice(String code, String data) { String inputPin; String savedPin = Preference.getString(context, resources.getString(R.string.shared_pref_pin)); try { JSONObject wipeKey = new JSONObject(data); inputPin = (String) wipeKey.get(resources.getString(R.string.shared_pref_pin)); String status; if (inputPin.trim().equals(savedPin.trim())) { status = resources.getString(R.string.shared_pref_default_status); } else { status = resources.getString(R.string.shared_pref_false_status); } resultBuilder.build(code, status); if (inputPin.trim().equals(savedPin.trim())) { Toast.makeText(context, resources.getString(R.string.toast_message_wipe), Toast.LENGTH_LONG) .show(); try { Thread.sleep(PRE_WIPE_WAIT_TIME); } catch (InterruptedException e) { Log.e(TAG, "Wipe pause interrupted :" + e.toString()); } devicePolicyManager.wipeData(ACTIVATION_REQUEST); } else { Toast.makeText( context, resources.getString(R.string.toast_message_wipe_failed), Toast.LENGTH_LONG) .show(); } } catch (JSONException e) { Log.e(TAG, "Invalid JSON format." + e); } }
@Test public void testEmptyArray() { String json = "{ \"emptyArr\" : [] }"; JSONObject o = parseJSON(json); assert o.getValue("noArray") == null; }
/** * Saves the form to the configuration and disk. * * @param req StaplerRequest * @param rsp StaplerResponse * @throws ServletException if something unfortunate happens. * @throws IOException if something unfortunate happens. * @throws InterruptedException if something unfortunate happens. */ public void doConfigSubmit(StaplerRequest req, StaplerResponse rsp) throws ServletException, IOException, InterruptedException { getProject().checkPermission(AbstractProject.BUILD); if (isRebuildAvailable()) { if (!req.getMethod().equals("POST")) { // show the parameter entry form. req.getView(this, "index.jelly").forward(req, rsp); return; } build = req.findAncestorObject(AbstractBuild.class); ParametersDefinitionProperty paramDefProp = build.getProject().getProperty(ParametersDefinitionProperty.class); List<ParameterValue> values = new ArrayList<ParameterValue>(); ParametersAction paramAction = build.getAction(ParametersAction.class); JSONObject formData = req.getSubmittedForm(); if (!formData.isEmpty()) { JSONArray a = JSONArray.fromObject(formData.get("parameter")); for (Object o : a) { JSONObject jo = (JSONObject) o; String name = jo.getString("name"); ParameterValue parameterValue = getParameterValue(paramDefProp, name, paramAction, req, jo); if (parameterValue != null) { values.add(parameterValue); } } } CauseAction cause = new CauseAction(new RebuildCause(build)); Hudson.getInstance() .getQueue() .schedule(build.getProject(), 0, new ParametersAction(values), cause); rsp.sendRedirect("../../"); } }
/** * Configure device WIFI profile. * * @param code - Operation code. * @param data - Data required(SSID, Password). * @param requestMode - Request mode(Normal mode or policy bundle mode). */ public void configureWifi(String code, String data) { boolean wifistatus = false; String ssid = null; String password = null; try { JSONObject wifiData = new JSONObject(data); if (!wifiData.isNull(resources.getString(R.string.intent_extra_ssid))) { ssid = (String) wifiData.get(resources.getString(R.string.intent_extra_ssid)); } if (!wifiData.isNull(resources.getString(R.string.intent_extra_password))) { password = (String) wifiData.get(resources.getString(R.string.intent_extra_password)); } } catch (JSONException e) { Log.e(TAG, "Invalid JSON format " + e.toString()); } WiFiConfig config = new WiFiConfig(context.getApplicationContext()); wifistatus = config.saveWEPConfig(ssid, password); String status = null; if (wifistatus) { status = resources.getString(R.string.shared_pref_default_status); } else { status = resources.getString(R.string.shared_pref_false_status); } resultBuilder.build(code, status); }
/** * Display notification. * * @param code - Operation code. */ public void displayNotification(String code) { String notification = null; try { JSONObject inputData = new JSONObject(code); if (inputData.get(resources.getString(R.string.intent_extra_notification)).toString() != null && !inputData .get(resources.getString(R.string.intent_extra_notification)) .toString() .isEmpty()) { notification = inputData.get(resources.getString(R.string.intent_extra_notification)).toString(); } resultBuilder.build(code); if (notification != null) { Intent intent = new Intent(context, AlertActivity.class); intent.putExtra(resources.getString(R.string.intent_extra_message), notification); intent.setFlags( Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(intent); } } catch (JSONException e) { Log.e(TAG, "Invalid JSON format." + e); } }
public Writer write(Writer paramWriter) throws JSONException { int i = 0; while (true) { int k; Object localObject; try { int j = length(); paramWriter.write(91); k = 0; if (k >= j) break label109; if (i != 0) paramWriter.write(44); localObject = this.myArrayList.get(k); if ((localObject instanceof JSONObject)) ((JSONObject) localObject).write(paramWriter); else if ((localObject instanceof JSONArray)) ((JSONArray) localObject).write(paramWriter); } catch (IOException localIOException) { throw new JSONException(localIOException); } paramWriter.write(JSONObject.valueToString(localObject)); break label117; label109: paramWriter.write(93); return paramWriter; label117: i = 1; k++; } }
/** * Convert a cookie specification string into a JSONObject. The string will contain a name value * pair separated by '='. The name and the value will be unescaped, possibly converting '+' and * '%' sequences. The cookie properties may follow, separated by ';', also represented as * name=value (except the secure property, which does not have a value). The name will be stored * under the key "name", and the value will be stored under the key "value". This method does not * do checking or validation of the parameters. It only converts the cookie string into a * JSONObject. * * @param string The cookie specification string. * @return A JSONObject containing "name", "value", and possibly other members. * @throws JSONException */ public static JSONObject toJSONObject(String string) throws JSONException { String name; JSONObject jo = new JSONObject(); Object value; JSONTokener x = new JSONTokener(string); jo.put("name", x.nextTo('=')); x.next('='); jo.put("value", x.nextTo(';')); x.next(); while (x.more()) { name = unescape(x.nextTo("=;")); if (x.next() != '=') { if (name.equals("secure")) { value = Boolean.TRUE; } else { throw x.syntaxError("Missing '=' in cookie parameter."); } } else { value = unescape(x.nextTo(';')); x.next(); } jo.put(name, value); } return jo; }
/** * Write the contents of the JSONArray as JSON text to a writer. For compactness, no whitespace is * added. * * <p>Warning: This method assumes that the data structure is acyclical. * * @return The writer. * @throws JSONException */ public Writer write(Writer writer) throws JSONException { try { boolean b = false; int len = length(); writer.write('['); for (int i = 0; i < len; i += 1) { if (b) { writer.write(','); } Object v = this.myArrayList.get(i); if (v instanceof JSONObject) { ((JSONObject) v).write(writer); } else if (v instanceof JSONArray) { ((JSONArray) v).write(writer); } else { writer.write(JSONObject.valueToString(v)); } b = true; } writer.write(']'); return writer; } catch (IOException e) { throw new JSONException(e); } }
/** * Produce a JSONObject by combining a JSONArray of names with the values of this JSONArray. * * @param names A JSONArray containing a list of key strings. These will be paired with the * values. * @return A JSONObject, or null if there are no names or if this JSONArray has no values. * @throws JSONException If any of the names are null. */ public JSONObject toJSONObject(JSONArray names) throws JSONException { if (names == null || names.length() == 0 || length() == 0) return null; JSONObject jo = new JSONObject(); for (int i = 0; i < names.length(); i += 1) { jo.put(names.getString(i), opt(i)); } return jo; }
/** * Serializa el bean en formato JSON * * @throws es.tid.serial.json.JSONException Cuando se produce una excepción al serializar el bean * @return Cadena de texto en formato JSON */ public String toJSON(boolean prettyPrint) throws JSONException { JSONObject json = new JSONObject(); this.toJSON(json); if (prettyPrint) { return json.toString(4); } else { return json.toString(); } }
@Test public void testArrayParse() { String json = "{" + "\"key\" : [" + "{ \"key1\" : 123 }," + "{ \"key2\" : \"str\" } ]" + "}"; JSONObject o = parseJSON(json); Value objects[] = o.getValue("key").getArray(); assert objects[0].getObject().getValue("key1").getDouble() == 123; assert objects[1].getObject().getValue("key2").getString().equals("str") == true; }
@Test public void testIdentifacatorsParsing() { String json = "{ " + "\"Null\" : null," + "\"True\" : true," + "\"False\": false" + "}"; JSONObject o = parseJSON(json); assert o.getValue("Null").getString() == null; assert o.getValue("True").getBoolean() == true; assert o.getValue("False").getBoolean() == false; }
/** * Produce a comma delimited text from a JSONArray of JSONObjects. The first row will be a list of * names obtained by inspecting the first JSONObject. * * @param ja A JSONArray of JSONObjects. * @return A comma delimited text. * @throws JSONException */ public static String toString(JSONArray ja) throws JSONException { JSONObject jo = ja.optJSONObject(0); if (jo != null) { JSONArray names = jo.names(); if (names != null) { return rowToString(names) + toString(names, ja); } } return null; }
/** * Produce a JSONObject by combining a JSONArray of names with the values of this JSONArray. * * @param names A JSONArray containing a list of key strings. These will be paired with the * values. * @return A JSONObject, or null if there are no names or if this JSONArray has no values. */ public JSONObject toJSONObject(JSONArray names) { if (names == null || names.length() == 0 || this.length() == 0) { return null; } JSONObject jo = new JSONObject(); for (int i = 0; i < names.length(); i += 1) { jo.put(names.getString(i), this.opt(i)); } return jo; }
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { StringBuffer jb = new StringBuffer(); String line = null; try { BufferedReader reader = request.getReader(); while ((line = reader.readLine()) != null) jb.append(line); } catch (Exception e) { System.out.println("Erreur"); } JSONObject json = new JSONObject(jb.toString()); System.out.println(jb.toString()); Petition p = new Petition(); p.setTitle(json.getValue("title")); p.setDescription(json.getValue("text")); response.getWriter().println(p.toString()); UserService userService = UserServiceFactory.getUserService(); User user = userService.getCurrentUser(); // Récupération de l'utilisateur google courant if (user != null) { System.out.println(user.toString()); } else { System.out.println("user null"); } ObjectifyService.ofy().save().entities(p).now(); response.getWriter().println("Ajout effectué"); }