List of usage examples for org.json JSONTokener JSONTokener
public JSONTokener(String s)
From source file:com.tune.reporting.base.service.TuneServiceResponse.java
/** * Get a String object representing this response. * * @return String//w w w . j av a 2s.c o m */ public String toString() { int statusCode = this.getStatusCode(); int responseSize = this.getResponseSize(); Object data = this.getData(); String dataStr = (null != data) ? data.toString() : "Null"; String errors = this.getErrors(); String errorsStr = (null != errors) ? errors.toString() : "Null"; int httpCode = this.getHttpCode(); Map<String, List<String>> httpHeaders = this.getHeaders(); String httpHeadersStr = null; if ((null != httpHeaders) && !httpHeaders.isEmpty()) { Iterator<Map.Entry<String, List<String>>> it = httpHeaders.entrySet().iterator(); httpHeadersStr = ""; while (it.hasNext()) { Map.Entry<String, List<String>> pairs = it.next(); String headerName = pairs.getKey(); List<String> headerValues = pairs.getValue(); httpHeadersStr += String.format("\n\t '%s':", headerName); for (String headerValue : headerValues) { httpHeadersStr += String.format("\n\t\t '%s':", headerValue); } } } else { httpHeadersStr = "Null"; } String responsePrettyPrint = ""; try { JSONTokener tokener = new JSONTokener(this.getRaw()); JSONObject finalResult = new JSONObject(tokener); responsePrettyPrint = finalResult.toString(4); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } // convert it to JSON object return String.format("\nrequest_url:\t\t '%s'" + "\nhttp_code:\t\t '%d'" + "\nhttpHeaders:\t\t '%s'" + "\nraw_response:\n%s\n", this.requestUrl, httpCode, httpHeadersStr, responsePrettyPrint); }
From source file:uk.ac.imperial.presage2.web.SimulationServlet.java
/** * REST CREATE simulation/*from ww w. j a v a 2 s.c o m*/ */ @Override protected synchronized void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { logRequest(req); try { // parse posted simulation json object JSONObject request = new JSONObject(new JSONTokener(req.getReader())); // validate data String name = request.getString("name"); String classname = request.getString("classname"); String state = request.getString("state"); int finishTime = request.getInt("finishTime"); PersistentSimulation sim = sto.createSimulation(name, classname, state, finishTime); resp.setStatus(201); if (!state.equalsIgnoreCase("GROUP")) { // add finishTime as a parameter sim.addParameter("finishTime", Integer.toString(finishTime)); } if (request.has("parameters")) { JSONObject parameters = request.getJSONObject("parameters"); for (@SuppressWarnings("unchecked") Iterator<String> iterator = parameters.keys(); iterator.hasNext();) { String key = (String) iterator.next(); sim.addParameter(key, parameters.getString(key)); } } // set simulation parent if (request.has("parent")) { try { long parentId = request.getLong("parent"); PersistentSimulation parent = sto.getSimulationById(parentId); if (parent != null) sim.setParentSimulation(parent); } catch (JSONException e) { // ignore non number parent. } } // clear sim cache this.cachedSimulations = null; // return created simulation object JSONObject response = new JSONObject(); response.put("success", true); response.put("message", "Created simulation"); response.put("data", simulationToJSON(sim)); resp.getWriter().write(response.toString()); } catch (JSONException e) { // bad request resp.setStatus(400); logger.warn("Couldn't create new simulation", e); } }
From source file:uk.ac.imperial.presage2.web.SimulationServlet.java
/** * REST UPDATE simulation//from ww w . j ava 2s .co m */ @Override protected synchronized void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { logRequest(req); String path = req.getPathInfo(); Matcher matcher = ID_REGEX.matcher(path); if (matcher.matches()) { long simId = Integer.parseInt(matcher.group(1)); try { // get data sent to us JSONObject input = new JSONObject(new JSONTokener(req.getReader())); // validate fields if (Integer.parseInt(input.get("id").toString()) != simId || input.getString("state").length() < 1 || input.getInt("currentTime") < 0 || input.getInt("finishTime") < 0) { resp.setStatus(400); return; } PersistentSimulation sim = sto.getSimulationById(simId); String state = input.getString("state"); if (!(sim.getState().equals(state))) { sim.setState(state); } int currentTime = input.getInt("currentTime"); if (!(sim.getCurrentTime() == currentTime)) { sim.setCurrentTime(currentTime); } int finishTime = input.getInt("finishTime"); if (!(sim.getFinishTime() == finishTime)) { sim.setCurrentTime(finishTime); } JSONObject parameters = input.getJSONObject("parameters"); for (@SuppressWarnings("unchecked") Iterator<String> iterator = parameters.keys(); iterator.hasNext();) { String key = (String) iterator.next(); sim.addParameter(key, parameters.getString(key)); } // parent simulation try { long parentId = input.getLong("parent"); PersistentSimulation parent = sim.getParentSimulation(); if (parentId == 0 && parent != null) { sim.setParentSimulation(null); } else if (parentId > 0 && parent.getID() != parentId) { parent = sto.getSimulationById(parentId); if (parent != null) { sim.setParentSimulation(parent); } } } catch (JSONException e) { } JSONObject response = new JSONObject(); response.put("success", true); response.put("data", simulationToJSON(sim)); resp.getWriter().write(response.toString()); // clear sim cache this.cachedSimulations = null; } catch (JSONException e) { resp.setStatus(400); } } else { resp.setStatus(400); } }
From source file:com.dubsar_dictionary.Dubsar.model.Model.java
/** * Fetch data synchronously from the server. *///from w w w . j ava2 s .c om public void load() { try { /* simple HTTP mock for testing */ mData = getMock(); if (mData == null) mData = fetchData(); JSONTokener tokener = new JSONTokener(mData); parseData(tokener.nextValue()); } /* JSONException, ClientProtocolException and IOException * For now (and perhaps indefinitely), we handle them all alike. */ catch (Exception e) { mError = true; mErrorMessage = e.getMessage(); Log.wtf(TAG, e); } mComplete = true; }
From source file:com.gmail.tylerfilla.axon.ui.activity.HelpFOSSActivity.java
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Inflate and set content view setContentView(R.layout.activity_help_foss); // Find stuff Toolbar appBar = (Toolbar) findViewById(R.id.activity_help_foss_app_bar); RecyclerView list = (RecyclerView) findViewById(R.id.activity_help_foss_list); // Configure app bar setSupportActionBar(appBar);//w ww . j av a 2s .co m // Display up button in app bar getSupportActionBar().setDisplayHomeAsUpEnabled(true); // Apply dark tint to navigation icon // noinspection ConstantConditions Drawable navigationIcon = DrawableCompat.wrap(appBar.getNavigationIcon()); DrawableCompat.setTint(navigationIcon, 0x8b000000); appBar.setNavigationIcon(navigationIcon); // Configure list list.setAdapter(new ListAdapter()); list.setLayoutManager(new LinearLayoutManager(this)); // Create list for licensed FOSS components fossComponents = new ArrayList<>(); try { // Read components file into a buffer StringWriter componentFileBuffer = new StringWriter(); IOUtils.copy(getAssets().open("foss/components.json"), componentFileBuffer, Charset.defaultCharset()); // Parse component array JSONArray componentArray = (JSONArray) new JSONTokener(componentFileBuffer.toString()).nextValue(); // Iterate over components for (int i = 0; i < componentArray.length(); i++) { JSONObject component = componentArray.getJSONObject(i); // Add component to list fossComponents.add(new FOSSComponent(component.getString("name"), component.getString("licenseName"), component.getString("licenseTextURL"))); } } catch (IOException e) { e.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); } }
From source file:com.cloudant.mazha.ClientTestUtils.java
public static List<String> getRemoteRevisionIDs(CouchClient couchClient, URI uri) throws Exception { HttpRequests requests = couchClient.getHttpClient(); InputStream in = requests.get(uri); JSONObject jsonObject = new JSONObject(new JSONTokener(IOUtils.toString(in))); JSONArray revsInfo = jsonObject.getJSONArray("_revs_info"); List<String> revisions = new ArrayList<String>(revsInfo.length()); for (int i = 0; i < revsInfo.length(); i++) { revisions.add(revsInfo.getJSONObject(i).getString("rev")); }//from w w w .j a v a 2s. c o m return revisions; }
From source file:org.gluu.com.ox_push2.u2f.v2.SoftwareDevice.java
public TokenResponse enroll(String jsonRequest, OxPush2Request oxPush2Request, Boolean isDeny) throws JSONException, IOException, U2FException { JSONObject request = (JSONObject) new JSONTokener(jsonRequest).nextValue(); if (request.has("registerRequests")) { JSONArray registerRequestArray = request.getJSONArray("registerRequests"); if (registerRequestArray.length() == 0) { throw new U2FException("Failed to get registration request!"); }/*from www . ja va 2 s .c om*/ request = (JSONObject) registerRequestArray.get(0); } if (!request.getString(JSON_PROPERTY_VERSION).equals(SUPPORTED_U2F_VERSION)) { throw new U2FException("Unsupported U2F_V2 version!"); } // Init device UUID service DeviceUuidManager deviceUuidFactory = new DeviceUuidManager(); deviceUuidFactory.init(context); String version = request.getString(JSON_PROPERTY_VERSION); String appParam = request.getString(JSON_PROPERTY_APP_ID); String challenge = request.getString(JSON_PROPERTY_SERVER_CHALLENGE); String origin = oxPush2Request.getIssuer(); EnrollmentResponse enrollmentResponse = u2fKey .register(new EnrollmentRequest(version, appParam, challenge, oxPush2Request)); if (BuildConfig.DEBUG) Log.d(TAG, "Enrollment response: " + enrollmentResponse); JSONObject clientData = new JSONObject(); if (isDeny) { clientData.put(JSON_PROPERTY_REQUEST_TYPE, REGISTER_CANCEL_TYPE); } else { clientData.put(JSON_PROPERTY_REQUEST_TYPE, REQUEST_TYPE_REGISTER); } clientData.put(JSON_PROPERTY_SERVER_CHALLENGE, challenge); clientData.put(JSON_PROPERTY_SERVER_ORIGIN, origin); String clientDataString = clientData.toString(); byte[] resp = rawMessageCodec.encodeRegisterResponse(enrollmentResponse); String deviceType = getDeviceType(); String versionName = getVersionName(); DeviceData deviceData = new DeviceData(); deviceData.setUuid(DeviceUuidManager.getDeviceUuid(context).toString()); deviceData.setPushToken(PushNotificationManager.getRegistrationId(context)); deviceData.setType(deviceType); deviceData.setPlatform("android"); deviceData.setName(Build.MODEL); deviceData.setOsName(versionName); deviceData.setOsVersion(Build.VERSION.RELEASE); String deviceDataString = new Gson().toJson(deviceData); JSONObject response = new JSONObject(); response.put("registrationData", Utils.base64UrlEncode(resp)); response.put("clientData", Utils.base64UrlEncode(clientDataString.getBytes(Charset.forName("ASCII")))); response.put("deviceData", Utils.base64UrlEncode(deviceDataString.getBytes(Charset.forName("ASCII")))); TokenResponse tokenResponse = new TokenResponse(); tokenResponse.setResponse(response.toString()); tokenResponse.setChallenge(new String(challenge)); tokenResponse.setKeyHandle(new String(enrollmentResponse.getKeyHandle())); return tokenResponse; }
From source file:com.zotoh.core.util.JSONUte.java
/** * @param json/*from w w w. j av a2 s. c o m*/ * @return * @throws JSONException */ public static JSONObject read(InputStream json) throws JSONException { return new JSONObject(new JSONTokener(json)); }
From source file:com.zotoh.core.util.JSONUte.java
/** * @param json//w w w . j ava 2 s .c o m * @return * @throws JSONException */ public static JSONObject read(File json) throws JSONException { InputStream inp = null; try { inp = readStream(json); return new JSONObject(new JSONTokener(inp)); } catch (IOException e) { throw new JSONException(e); } finally { close(inp); } }
From source file:com.zotoh.core.util.JSONUte.java
/** * @param json//from www .j a v a2 s . com * @return * @throws JSONException */ public static JSONObject read(String json) throws JSONException { return new JSONObject(new JSONTokener(json)); }