@SuppressWarnings({"unchecked", "unused"}) public final JSONObject innerMap() throws ParseException { final JSONObject json = new JSONObject(); String key; Object value; key = objectKey(); jj_consume_token(EQUALS); value = value(); json.put(key, value); key = null; value = null; label_1: while (true) { switch (jj_nt.kind) { case SLASH:; break; default: jj_la1[1] = jj_gen; break label_1; } jj_consume_token(SLASH); jj_consume_token(COMMA); key = objectKey(); jj_consume_token(EQUALS); value = value(); json.put(key, value); key = null; value = null; } { if (true) return json; } throw new Error("Missing return statement in function"); }
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; }
/** * Write the contents of the JSONObject 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 commanate = false; final Iterator keys = this.keys(); writer.write('{'); while (keys.hasNext()) { if (commanate) { writer.write(','); } final Object key = keys.next(); writer.write(JSONObject.quote(key.toString())); writer.write(':'); final Object value = this.map.get(key); if (value instanceof JSONObject) { ((JSONObject) value).write(writer); } else if (value instanceof JSONArray) { ((JSONArray) value).write(writer); } else { writer.write(JSONObject.valueToString(value)); } commanate = true; } writer.write('}'); return writer; } catch (final IOException exception) { throw new JSONException(exception); } }
/** method to update data in caching layer object from JSON * */ public boolean updateFromJSON(JSONObject jsonObj) { try { JSONArray hasArcsArray = jsonObj.optJSONArray("hasArcs"); if (hasArcsArray != null) { ArrayList<Arc> aListOfHasArcs = new ArrayList<Arc>(hasArcsArray.length()); for (int i = 0; i < hasArcsArray.length(); i++) { int id = hasArcsArray.optInt(i); if (ArcManager.getInstance().get(id) != null) { aListOfHasArcs.add(ArcManager.getInstance().get(id)); } } setHasArcs(aListOfHasArcs); } if (!jsonObj.isNull("hasPropertySet")) { int hasPropertySetId = jsonObj.optInt("hasPropertySet"); PropertySet value = PropertySetManager.getInstance().get(hasPropertySetId); if (value != null) { setHasPropertySet(value); } } if (!jsonObj.isNull("hasDomainNodes")) { int hasDomainNodesId = jsonObj.optInt("hasDomainNodes"); NodeList value = NodeListManager.getInstance().get(hasDomainNodesId); if (value != null) { setHasDomainNodes(value); } } } catch (Exception e) { logWriter.error("Failure updating from JSON", e); return false; } return true; }
/** @throws Exception */ public void delete() throws Exception { Connection delConnection = null; String sName = (String) oInput.get("archetype"); if (!SourceVersion.isName(sName)) throw new Exception("name " + sName + " is not a valid java identifier"); PreparedStatement oStmt = null; try { delConnection = OpenShiftDerbySource.getConnection(); oStmt = delConnection.prepareStatement("DELETE FROM " + sName + " WHERE id" + sName + " = ?"); oStmt.setString(1, (String) oInput.get("id" + sName)); int nRows = oStmt.executeUpdate(); if (nRows == 0) throw new Exception("no rows deleted"); } finally { if (delConnection != null) try { delConnection.close(); } catch (SQLException logOrIgnore) { } if (oStmt != null) try { oStmt.close(); } catch (SQLException logOrIgnore) { } } }
/** * Make a JSON text of an Object value. If the object has an value.toJSONString() method, then * that method will be used to produce the JSON text. The method is required to produce a strictly * conforming text. If the object does not contain a toJSONString method (which is the most common * case), then a text will be produced by other means. If the value is an array or Collection, * then a JSONArray will be made from it and its toJSONString method will be called. If the value * is a MAP, then a JSONObject will be made from it and its toJSONString method will be called. * Otherwise, the value's toString method will be called, and the result will be quoted. * * <p>Warning: This method assumes that the data structure is acyclical. * * @param value The value to be serialized. * @return a printable, displayable, transmittable representation of the object, beginning with * <code>{</code> <small>(left brace)</small> and ending with <code>}</code> * <small>(right brace)</small>. * @throws JSONException If the value is or contains an invalid number. */ public static String valueToString(Object value) throws JSONException { if ((value == null) || value.equals(null)) { return "null"; } if (value instanceof JSONString) { Object object; try { object = ((JSONString) value).toJSONString(); } catch (final Exception e) { throw new JSONException(e); } if (object instanceof String) { return (String) object; } throw new JSONException("Bad value from toJSONString: " + object); } if (value instanceof Number) { return JSONObject.numberToString((Number) value); } if ((value instanceof Boolean) || (value instanceof JSONObject) || (value instanceof JSONArray)) { return value.toString(); } if (value instanceof Map) { return new JSONObject((Map) value).toString(); } if (value instanceof Collection) { return new JSONArray((Collection) value).toString(); } if (value.getClass().isArray()) { return new JSONArray(value).toString(); } return JSONObject.quote(value.toString()); }
/** * 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(); final ResourceBundle bundle = ResourceBundle.getBundle(baseName, locale, Thread.currentThread().getContextClassLoader()); // Iterate through the keys in the bundle. final Enumeration keys = bundle.getKeys(); while (keys.hasMoreElements()) { final 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. final String[] path = ((String) key).split("\\."); final int last = path.length - 1; JSONObject target = this; for (int i = 0; i < last; i += 1) { final 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)); } } }
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(); } }
@SuppressWarnings({"unused", "unchecked"}) public final JSONObject object() throws ParseException { final JSONObject json = new JSONObject(); String key; Object value; key = objectKey(); jj_consume_token(EQUALS); value = value(); json.put(key, value); key = null; value = null; label_2: while (true) { if (jj_2_1(2)) {; } else { break label_2; } jj_consume_token(COMMA); key = objectKey(); jj_consume_token(EQUALS); value = value(); json.put(key, value); key = null; value = null; } { if (true) return json; } throw new Error("Missing return statement in function"); }
public static JSONObject createInfoAlert(String message) { try { JSONObject ret = new JSONObject(); ret.put("type", "info"); ret.put("message", message); return ret; } catch (JSONException e) { return null; } }
private void addTagsToProperties(MethodInfo mi, JSONObject propJ) throws JSONException { // create description object. description tag enables the visual tools to display description of // keys/values // of a map property, items of a list, properties within a complex type. JSONObject descriptionObj = new JSONObject(); if (mi.comment != null) { descriptionObj.put("$", mi.comment); } for (Map.Entry<String, String> descEntry : mi.descriptions.entrySet()) { descriptionObj.put(descEntry.getKey(), descEntry.getValue()); } if (descriptionObj.length() > 0) { propJ.put("descriptions", descriptionObj); } // create useSchema object. useSchema tag is added to enable visual tools to be able to render a // text field // as a dropdown with choices populated from the schema attached to the port. JSONObject useSchemaObj = new JSONObject(); for (Map.Entry<String, String> useSchemaEntry : mi.useSchemas.entrySet()) { useSchemaObj.put(useSchemaEntry.getKey(), useSchemaEntry.getValue()); } if (useSchemaObj.length() > 0) { propJ.put("useSchema", useSchemaObj); } }
public static JSONObject buildErrorJson(String errorMsg) { JSONObject ret = new JSONObject(); try { JSONObject error = new JSONObject(); error.put("message", errorMsg); error.put("type", "error"); ret.put("announce", error); } catch (JSONException e) { return null; } return ret; }
public void trapException(String output) throws CrowdFlowerException { try { JSONObject error = new JSONObject(output); if (error.has("error")) { throw new CrowdFlowerException(error.get("error").toString()); } } catch (JSONException e) { // ignore } }
/** * Sends command to retrieve phones list. * * @return is command successful. */ @SuppressWarnings("unchecked") private boolean getPhoneList() { JSONObject obj = new JSONObject(); try { obj.put("class", "phones"); obj.put("function", "getlist"); return send(obj); } catch (Exception e) { logger.error("Error retrieving phones"); return false; } }
@PUT @Path("/edit/{id}") @Consumes(MediaType.APPLICATION_JSON) public void editNote(String inputData, @PathParam("id") int id) { JSONObject inputJSON = new JSONObject(inputData); if ((inputJSON.has("sessionID")) && UsersController.checkLogin(inputJSON.getString("sessionID"))) { Note newNote = resolveNoteData(inputJSON); if (inputJSON.has("noteID")) inputJSON.remove("noteID"); // na wszelki wypadek - ID podano hibernate.controllers.NotesController notesController = new hibernate.controllers.NotesController(); if (newNote != null) notesController.updateNote(newNote, id); } }
/** * Get an array of field names from a JSONObject. * * @return An array of field names, or null if there are no names. */ public static String[] getNames(JSONObject jo) { final int length = jo.length(); if (length == 0) { return null; } final Iterator iterator = jo.keys(); final String[] names = new String[length]; int i = 0; while (iterator.hasNext()) { names[i] = (String) iterator.next(); i += 1; } return names; }
@PUT @Path("/edit") @Consumes(MediaType.APPLICATION_JSON) public void editNote(String inputData) { JSONObject inputJSON = new JSONObject(inputData); if ((inputJSON.has("sessionID")) && UsersController.checkLogin(inputJSON.getString("sessionID"))) { if (inputJSON.has("noteID")) { int id = Integer.parseInt(inputJSON.getString("noteID")); editNote(inputData, id); } // w przeciwnym wypadku nic nie robi } }
/** * Get an array of field names from a JSONObject. * * @return An array of field names, or null if there are no names. */ public static String[] getNames(JSONObject jo) { int length = jo.length(); if (length == 0) { return null; } Iterator i = jo.keys(); String[] names = new String[length]; int j = 0; while (i.hasNext()) { names[j] = (String) i.next(); j += 1; } return names; }
/** Handles new incoming object. */ private void handle(JSONObject incomingObject) { if (!incomingObject.containsKey("class")) return; try { String classField = (String) incomingObject.get("class"); if (classField.equals("loginko")) { showError(null, null, "Unauthorized. Cannot login: "******"errorstring")); logger.error("Error login: "******"errorstring")); destroy(); return; } else if (classField.equals("login_id_ok")) { SipAccountIDImpl accountID = (SipAccountIDImpl) sipProvider.getAccountID(); boolean useSipCredentials = accountID.isClistOptionUseSipCredentials(); String password; if (useSipCredentials) { password = SipActivator.getProtocolProviderFactory().loadPassword(accountID); } else { password = accountID.getClistOptionPassword(); } if (!authorize((String) incomingObject.get("sessionid"), password)) logger.error("Error login authorization!"); return; } else if (classField.equals("login_pass_ok")) { if (!sendCapas((JSONArray) incomingObject.get("capalist"))) logger.error("Error send capas!"); return; } else if (classField.equals("login_capas_ok")) { if (!sendFeatures( (String) incomingObject.get("astid"), (String) incomingObject.get("xivo_userid"))) logger.error("Problem send features get!"); return; } else if (classField.equals("features")) { if (!getPhoneList()) logger.error("Problem send get phones!"); return; } else if (classField.equals("phones")) { phonesRecieved(incomingObject); return; } else if (classField.equals("disconn")) { destroy(); return; } else { if (logger.isTraceEnabled()) logger.trace("unhandled classField: " + incomingObject); return; } } catch (Throwable t) { logger.error("Error handling incoming object", t); } }
/** * Sends password command. * * @param sessionId the session id from previous command. * @param password the password to authorize. * @return is command successful. */ @SuppressWarnings("unchecked") private boolean authorize(String sessionId, String password) { if (connection == null || sessionId == null || password == null) return false; JSONObject obj = new JSONObject(); try { obj.put("class", "login_pass"); obj.put("hashedpassword", Sha1Crypto.encode(sessionId + ":" + password)); return send(obj); } catch (Exception e) { logger.error("Error login with password", e); return false; } }
/** * Send needed command for features. * * @param astid param from previous command. * @param xivoUserId param from previous command. * @return is command successful. */ @SuppressWarnings("unchecked") private boolean sendFeatures(String astid, String xivoUserId) { if (connection == null || astid == null || xivoUserId == null) return false; JSONObject obj = new JSONObject(); try { obj.put("class", "featuresget"); obj.put("userid", astid + "/" + xivoUserId); return send(obj); } catch (Exception e) { logger.error("Error send features get command", e); return false; } }
@POST @Path("/create") @Consumes(MediaType.APPLICATION_JSON) public void createNote(String inputData) { JSONObject inputJSON = new JSONObject(inputData); if ((inputJSON.has("sessionID")) && UsersController.checkLogin(inputJSON.getString("sessionID"))) { if (inputJSON.has("noteID")) inputJSON.remove("noteID"); // na wszelki wypadek - chcemy generowaƦ ID automatycznie Note newNote = resolveNoteData(inputJSON); hibernate.controllers.NotesController notesController = new hibernate.controllers.NotesController(); if (newNote != null) notesController.addNote(newNote); } }
/** * Get the JSONObject value associated with a key. * * @param key A key string. * @return A JSONObject which is the value. * @throws JSONException if the key is not found or if the value is not a JSONObject. */ public JSONObject getJSONObject(String key) throws JSONException { final Object object = this.get(key); if (object instanceof JSONObject) { return (JSONObject) object; } throw new JSONException("JSONObject[" + JSONObject.quote(key) + "] is not a JSONObject."); }
/** * Write the contents of the JSONObject 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; Iterator keys = keys(); writer.write('{'); while (keys.hasNext()) { if (b) { writer.write(','); } Object k = keys.next(); writer.write(quote(k.toString())); writer.write(':'); Object v = this.map.get(k); if (v instanceof JSONObject) { ((JSONObject) v).write(writer); } else if (v instanceof JSONArray) { ((JSONArray) v).write(writer); } else { writer.write(valueToString(v)); } b = true; } writer.write('}'); return writer; } catch (IOException e) { throw new JSONException(e); } }
/** * @param rs the result set from the meta data * @return the SQL that can be used to do an update * @throws Exception */ private String doUpdate(ResultSet rs) throws Exception { int nColNo = 0; String sName = (String) oInput.get("archetype"); String sSQL = "UPDATE " + sName + " SET "; while (rs.next()) { String sColName = rs.getString(1); if (nColNo++ > 0) { sSQL += ", "; } sSQL += sColName + " = ?"; aBindVars.add((String) oInput.get(sColName)); } sSQL += " WHERE id" + sName + " = ?"; aBindVars.add(oInput.get("id" + sName).toString()); return sSQL; }
private void printObj(JSONObject jObj, PrintWriter writer) { try { // System.out.println(jObj.toString(3)); writer.print(jObj.toString(3)); } catch (JSONException e) { System.out.println("could to to string json object"); } }
/** * Returns control when task is complete. * * @param json * @param logger */ private String waitForDeploymentCompletion(JSON json, OctopusApi api, Log logger) { final long WAIT_TIME = 5000; final double WAIT_RANDOM_SCALER = 100.0; JSONObject jsonObj = (JSONObject) json; String id = jsonObj.getString("TaskId"); Task task = null; String lastState = "Unknown"; try { task = api.getTask(id); } catch (IOException ex) { logger.error("Error getting task: " + ex.getMessage()); return null; } logger.info("Task info:"); logger.info("\tId: " + task.getId()); logger.info("\tName: " + task.getName()); logger.info("\tDesc: " + task.getDescription()); logger.info("\tState: " + task.getState()); logger.info("\n\nStarting wait..."); boolean completed = task.getIsCompleted(); while (!completed) { try { task = api.getTask(id); } catch (IOException ex) { logger.error("Error getting task: " + ex.getMessage()); return null; } completed = task.getIsCompleted(); lastState = task.getState(); logger.info("Task state: " + lastState); if (completed) { break; } try { Thread.sleep(WAIT_TIME + (long) (Math.random() * WAIT_RANDOM_SCALER)); } catch (InterruptedException ex) { logger.info("Wait interrupted!"); logger.info(ex.getMessage()); completed = true; // bail out of wait loop } } logger.info("Wait complete!"); return lastState; }
/** * Performs a test by sending HTTP Gets to the URL, and records the number of bytes returned. Each * test results are documented and displayed in standard out with the following information: * * <p>URL - The source URL of the test REQ CNT - How many times this test has run START - The * start time of the last test run STOP - The stop time of the last test run THREAD - The thread * id handling this test case RESULT - The result of the test. Either the number of bytes returned * or an error message. */ private void doTest() { String result = ""; this.reqCount++; // Connect and run test steps Date startTime = new Date(); try { ClientResource client = new ClientResource(this.myURL); // place order JSONObject json = new JSONObject(); json.put("payment", "quarter"); json.put("action", "place-order"); client.post(new JsonRepresentation(json), MediaType.APPLICATION_JSON); // Get Gumball Count Representation result_string = client.get(); JSONObject json_count = new JSONObject(result_string.getText()); result = Integer.toString((int) json_count.get("count")); } catch (Exception e) { result = e.toString(); } finally { Date stopTime = new Date(); // Print Report of Result: System.out.println( "======================================\n" + "URL => " + this.myURL + "\n" + "REQ CNT => " + this.reqCount + "\n" + "START => " + startTime + "\n" + "STOP => " + stopTime + "\n" + "THREAD => " + Thread.currentThread().getName() + "\n" + "RESULT => " + result + "\n"); } }
public JSONObject asJSONTreeAux(ConcurrentHashMap<DomainConcept, DomainConcept> written) { JSONObject jsonObj = new JSONObject(); try { jsonObj.put("class", "ClassModel"); jsonObj.put("id", id); if (written.contains(this)) { return jsonObj; } written.put(this, this); if (getHasArcs() != null) { JSONArray jsonHasArcs = new JSONArray(); for (Arc row : getHasArcs()) { jsonHasArcs.put(row.asJSONTreeAux(written)); } jsonObj.put("hasArcs", jsonHasArcs); } if (getHasPropertySet() != null) { jsonObj.put("hasPropertySet", getHasPropertySet().asJSONTreeAux(written)); } jsonObj.put("id", getId()); if (getHasDomainNodes() != null) { jsonObj.put("hasDomainNodes", getHasDomainNodes().asJSONTreeAux(written)); } written.remove(this); } catch (Exception e1) { logWriter.error("Error in marshalling to JSON ", e1); } return jsonObj; }
/** * Construct a JSONObject from a subset of another JSONObject. An array of strings is used to * identify the keys that should be copied. Missing keys are ignored. * * @param jo A JSONObject. * @param names An array of strings. * @throws JSONException * @exception JSONException If a value is a non-finite number or if a name is duplicated. */ public JSONObject(JSONObject jo, String[] names) { this(); for (final String name : names) { try { this.putOnce(name, jo.opt(name)); } catch (final Exception ignore) { } } }