List of usage examples for org.json JSONTokener JSONTokener
public JSONTokener(String s)
From source file:edu.usf.cutr.gtfs_realtime.bullrunner.GtfsRealtimeProviderImpl.java
private Pair downloadVehicleDetails() throws IOException, JSONException { URLConnection connection = null; try {/*w w w . jav a2 s . co m*/ connection = _url.openConnection(); } catch (Exception ex) { _log.error("Error in opening feeds url", ex); } connection.setConnectTimeout(10000); // connectTimeout is time out in miliseconds connection.setReadTimeout(10000); java.io.InputStream in = connection.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(in, "UTF-8")); StringBuilder builder = new StringBuilder(); String inputLine; JSONArray stopIDsArray; JSONArray vehicleArray; try { while ((inputLine = reader.readLine()) != null) builder.append(inputLine).append("\n"); JSONObject object = (JSONObject) new JSONTokener(builder.toString()).nextValue(); String data = object.getString("PredictionData"); JSONObject child2_obj = new JSONObject(data); responseTimeStamp = child2_obj.getString("TimeStamp"); stopIDsArray = child2_obj.getJSONArray("StopPredictions"); vehicleArray = child2_obj.getJSONArray("VehicleLocationData"); } catch (java.net.SocketTimeoutException ex) { _log.error("Error readline, server dosn't close the connection.", ex); stopIDsArray = null; vehicleArray = null; } return new Pair(stopIDsArray, vehicleArray); }
From source file:de.wikilab.android.friendica01.TwAjax.java
public Object getJsonResult() { if (!success) return null; try {/*ww w. jav a 2 s . c o m*/ JSONTokener jt = new JSONTokener(myResult); return jt.nextValue(); } catch (JSONException ex) { //server returned malformed data return null; } }
From source file:com.mi.xserv.Xserv.java
private void manageMessage(String event) { JSONObject json = null;//from w ww. jav a 2s . c o m try { json = new JSONObject(event); } catch (JSONException ignored) { } if (json != null) { int op = 0; try { op = json.getInt("op"); } catch (JSONException ignored) { } if (op == 0) { // messages onReceiveMessages(json); } else if (op > 0) { // operations try { String data = json.getString("data"); byte[] b = Base64.decode(data, Base64.DEFAULT); json.put("data", new String(b, "UTF-8")); // string } catch (JSONException | UnsupportedEncodingException ignored) { } JSONObject json_data = null; try { String data = json.getString("data"); Object type = new JSONTokener(data).nextValue(); if (type instanceof JSONObject) { json_data = new JSONObject(data); json.put("data", json_data); } else if (type instanceof JSONArray) { json.put("data", new JSONArray(data)); } } catch (JSONException ignored) { } try { json.put("name", stringifyOp(op)); } catch (JSONException ignored) { } int rc = 0; String uuid = ""; String topic = ""; String descr = ""; try { rc = json.getInt("rc"); uuid = json.getString("uuid"); topic = json.getString("topic"); descr = json.getString("descr"); } catch (JSONException ignored) { } if (op == OP_HANDSHAKE) { // handshake if (rc == RC_OK) { if (json_data != null) { setUserData(json_data); isConnected = true; onOpenConnection(); } else { mCallbacks.clear(); onErrorConnection(new Exception(descr)); } } else { mCallbacks.clear(); onErrorConnection(new Exception(descr)); } } else { // classic operations if (op == OP_SUBSCRIBE && isPrivateTopic(topic) && rc == RC_OK) { if (json_data != null) { setUserData(json_data); } } if (mCallbacks.get(uuid) != null) { mCallbacks.get(uuid).onCompletion(json); mCallbacks.remove(uuid); } else { OnReceiveOperations(json); } } } } }
From source file:com.smedic.tubtub.JsonAsyncTask.java
/** * Checks if JSON data is correctly formatted * @param string/*from ww w . jav a2 s. c om*/ * @return */ private int checkJson(String string) { try { Object json = new JSONTokener(string).nextValue(); if (json instanceof JSONObject) { return JSON_OBJECT; } else if (json instanceof JSONArray) { return JSON_ARRAY; } else { return JSON_ERROR; } } catch (JSONException e) { e.printStackTrace(); return JSON_ERROR; } }
From source file:com.daon.identityx.samplefidoapp.SplashActivity.java
/*** * From the discovery data, create the list of AAIDs * * @param discoveryData the discovery data * @return a list of AAIDs/*from w w w. j a v a 2s . c o m*/ */ protected List<String> getAaidsFromDiscoveryData(String discoveryData) { List<String> aaidList = new ArrayList<>(); if (discoveryData != null) { try { JSONObject discoveryDataJsonObj = new JSONObject(new JSONTokener(discoveryData)); JSONArray availableAuthenticators = discoveryDataJsonObj.getJSONArray("availableAuthenticators"); for (int i = 0; i < availableAuthenticators.length(); i++) { JSONObject authenticator = availableAuthenticators.getJSONObject(i); aaidList.add(authenticator.getString("aaid")); } return aaidList; } catch (Exception e) { Log.e(LogUtils.TAG, "Invalid discovery data format returned by the client."); } } return aaidList; }
From source file:com.codeskraps.lolo.misc.Utils.java
public static LOLO getLolo() throws UnsupportedEncodingException, ClientProtocolException, IOException, IllegalArgumentException, NullPointerException, JSONException { long startTime = System.currentTimeMillis(); if (BuildConfig.DEBUG) Log.d(TAG, "download begining"); if (BuildConfig.DEBUG) Log.d(TAG, "download url:" + Constants.LOLO_URL); HttpParams httpParameters = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(httpParameters, 5000); HttpConnectionParams.setSoTimeout(httpParameters, 10000); HttpClient client = new DefaultHttpClient(httpParameters); HttpGet request = new HttpGet(Constants.LOLO_URL); HttpResponse response = client.execute(request); BufferedReader reader = new BufferedReader( new InputStreamReader(response.getEntity().getContent(), "UTF-8")); String json = reader.readLine(); Log.d(TAG, "json: " + json); reader.close();//w w w. j a v a 2s .c o m JSONTokener tokener = new JSONTokener(json); JSONObject finalResult = new JSONObject(tokener); LOLO lolo = finalResult.getBoolean("open") ? LOLO.ON : LOLO.OFF; if (BuildConfig.DEBUG) Log.d(TAG, "lolo: " + lolo); if (BuildConfig.DEBUG) Log.d(TAG, "download ready in " + ((System.currentTimeMillis() - startTime) / 1000) + " sec"); return lolo; }
From source file:com.example.jumpnote.android.jsonrpc.JsonRpcJavaClient.java
public void callBatch(final List<JsonRpcClient.Call> calls, final JsonRpcClient.BatchCallback callback) { HttpPost httpPost = new HttpPost(mRpcUrl); JSONObject requestJson = new JSONObject(); JSONArray callsJson = new JSONArray(); try {/*from w w w . ja va2s .co m*/ for (int i = 0; i < calls.size(); i++) { JsonRpcClient.Call call = calls.get(i); JSONObject callJson = new JSONObject(); callJson.put("method", call.getMethodName()); if (call.getParams() != null) { JSONObject callParams = (JSONObject) call.getParams(); @SuppressWarnings("unchecked") Iterator<String> keysIterator = callParams.keys(); String key; while (keysIterator.hasNext()) { key = keysIterator.next(); callJson.put(key, callParams.get(key)); } } callsJson.put(i, callJson); } requestJson.put("calls", callsJson); httpPost.setEntity(new StringEntity(requestJson.toString(), "UTF-8")); if (Log.isLoggable(TAG, Log.VERBOSE)) { Log.v(TAG, "POST request: " + requestJson.toString()); } } catch (JSONException e) { // throw e; } catch (UnsupportedEncodingException e) { // throw e; } try { HttpResponse httpResponse = mHttpClient.execute(httpPost); final int responseStatusCode = httpResponse.getStatusLine().getStatusCode(); if (200 <= responseStatusCode && responseStatusCode < 300) { BufferedReader reader = new BufferedReader( new InputStreamReader(httpResponse.getEntity().getContent(), "UTF-8"), 8 * 1024); StringBuilder sb = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { sb.append(line).append("\n"); } if (Log.isLoggable(TAG, Log.VERBOSE)) { Log.v(TAG, "POST response: " + sb.toString()); } JSONTokener tokener = new JSONTokener(sb.toString()); JSONObject responseJson = new JSONObject(tokener); JSONArray resultsJson = responseJson.getJSONArray("results"); Object[] resultData = new Object[calls.size()]; for (int i = 0; i < calls.size(); i++) { JSONObject result = resultsJson.getJSONObject(i); if (result.has("error")) { callback.onError(i, new JsonRpcException((int) result.getInt("error"), calls.get(i).getMethodName(), result.getString("message"), null)); resultData[i] = null; } else { resultData[i] = result.get("data"); } } callback.onData(resultData); } else { callback.onError(-1, new JsonRpcException(-1, "Received HTTP status code other than HTTP 2xx: " + httpResponse.getStatusLine().getReasonPhrase())); } } catch (IOException e) { Log.e("JsonRpcJavaClient", e.getMessage()); e.printStackTrace(); } catch (JSONException e) { Log.e("JsonRpcJavaClient", "Error parsing server JSON response: " + e.getMessage()); e.printStackTrace(); } }
From source file:com.grameenfoundation.ictchallenge.controllers.OAuthAuthenticationServlet.java
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); try (PrintWriter out = response.getWriter()) { /* TODO output your page here. You may use following sample code. */ //assign the necessary initparameters to variables clientId = this.getInitParameter("clientId"); clientSecret = this.getInitParameter("clientSecret"); redirectUri = this.getInitParameter("redirectUri"); environment = this.getInitParameter("environment"); try {/* w w w.j a v a2 s . c o m*/ //build authentication url authUrl = environment + "/services/oauth2/authorize?response_type=code&client_id=" + clientId + "&redirect_uri=" + URLEncoder.encode(redirectUri, "UTF-8"); } catch (UnsupportedEncodingException e) { throw new ServletException(e); } //build url to get access token tokenUrl = environment + "/services/oauth2/token"; String accessToken = (String) request.getSession().getAttribute(ACCESS_TOKEN); //test if access token is null if (accessToken == null) { String instanceUrl = null; //get authorization for the first time if (request.getRequestURI().endsWith("oauth")) { // we need to send the user to authorize response.sendRedirect(authUrl); return; } //else call back url is activated else { System.out.println("Auth successful - got callback"); String code = request.getParameter("code"); // Create an instance of HttpClient. CloseableHttpClient httpclient = HttpClients.createDefault(); try { // Create an instance of HttpPost. HttpPost httpost = new HttpPost(tokenUrl); // Adding all form parameters in a List of type NameValuePair List<NameValuePair> nvps = new ArrayList<NameValuePair>(); nvps.add(new BasicNameValuePair("code", code)); nvps.add(new BasicNameValuePair("grant_type", "authorization_code")); nvps.add(new BasicNameValuePair("client_id", clientId)); nvps.add(new BasicNameValuePair("client_secret", clientSecret)); nvps.add(new BasicNameValuePair("redirect_uri", redirectUri)); httpost.setEntity(new UrlEncodedFormEntity(nvps, Consts.UTF_8)); // Execute the request. CloseableHttpResponse closeableresponse = httpclient.execute(httpost); System.out.println("Response Status line :" + closeableresponse.getStatusLine()); try { // Do the needful with entity. HttpEntity entity = closeableresponse.getEntity(); InputStream rstream = entity.getContent(); //get authentication response in JSON format JSONObject authResponse = new JSONObject(new JSONTokener(rstream)); //get access token and instance url to push subsequent requests accessToken = authResponse.getString("access_token"); instanceUrl = authResponse.getString("instance_url"); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { // Closing the response closeableresponse.close(); } } finally { httpclient.close(); } } // Set a session attribute so that other servlets can get the access token request.getSession().setAttribute(ACCESS_TOKEN, accessToken); // get the instance URL from the OAuth response into session request.getSession().setAttribute(INSTANCE_URL, instanceUrl); } response.sendRedirect(request.getContextPath() + "/ConnectedAppREST"); } }
From source file:g7.bluesky.launcher3.InstallShortcutReceiver.java
private static PendingInstallShortcutInfo decode(String encoded, Context context) { try {/* w w w .jav a 2s.c o m*/ JSONObject object = (JSONObject) new JSONTokener(encoded).nextValue(); Intent launcherIntent = Intent.parseUri(object.getString(LAUNCH_INTENT_KEY), 0); if (object.optBoolean(APP_SHORTCUT_TYPE_KEY)) { // The is an internal launcher target shortcut. UserHandleCompat user = UserManagerCompat.getInstance(context) .getUserForSerialNumber(object.getLong(USER_HANDLE_KEY)); if (user == null) { return null; } LauncherActivityInfoCompat info = LauncherAppsCompat.getInstance(context) .resolveActivity(launcherIntent, user); return info == null ? null : new PendingInstallShortcutInfo(info, context); } Intent data = new Intent(); data.putExtra(Intent.EXTRA_SHORTCUT_INTENT, launcherIntent); data.putExtra(Intent.EXTRA_SHORTCUT_NAME, object.getString(NAME_KEY)); String iconBase64 = object.optString(ICON_KEY); String iconResourceName = object.optString(ICON_RESOURCE_NAME_KEY); String iconResourcePackageName = object.optString(ICON_RESOURCE_PACKAGE_NAME_KEY); if (iconBase64 != null && !iconBase64.isEmpty()) { byte[] iconArray = Base64.decode(iconBase64, Base64.DEFAULT); Bitmap b = BitmapFactory.decodeByteArray(iconArray, 0, iconArray.length); data.putExtra(Intent.EXTRA_SHORTCUT_ICON, b); } else if (iconResourceName != null && !iconResourceName.isEmpty()) { Intent.ShortcutIconResource iconResource = new Intent.ShortcutIconResource(); iconResource.resourceName = iconResourceName; iconResource.packageName = iconResourcePackageName; data.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, iconResource); } return new PendingInstallShortcutInfo(data, context); } catch (JSONException e) { Log.d(TAG, "Exception reading shortcut to add: " + e); } catch (URISyntaxException e) { Log.d(TAG, "Exception reading shortcut to add: " + e); } return null; }
From source file:com.tune.reporting.base.service.TuneServiceResponse.java
/** * Get raw representing only the "data" response from TUNE Service API. * * @return String//w w w .ja va 2s . c om */ public String toStringRaw() { String responseRawPrint = ""; try { //tokenize the ugly JSON string JSONTokener tokener = new JSONTokener(this.getRaw()); // convert it to JSON object JSONObject finalResult = new JSONObject(tokener); // To string method prints it with specified indentation. responseRawPrint = finalResult.toString(4); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } // convert it to JSON object return responseRawPrint; }