List of usage examples for org.json JSONException JSONException
public JSONException(Throwable t)
From source file:com.richinfo.wifihelper.common.net.JsonHttpResponseHandler.java
protected void handleSuccessJsonMessage(int statusCode, Object jsonResponse) { if (jsonResponse instanceof JSONObject) { onSuccess(statusCode, (JSONObject) jsonResponse); } else if (jsonResponse instanceof JSONArray) { onSuccess(statusCode, (JSONArray) jsonResponse); } else {//from w w w . j av a 2 s. co m onFailure(new JSONException("Unexpected type " + jsonResponse.getClass().getName()), (JSONObject) null); } }
From source file:io.riddles.lightriders.game.state.LightridersStateDeserializer.java
@Override public LightridersState traverse(String statesString) throws JSONException { LightridersState state = null;// w ww . java 2 s. com Object states = new JSONObject(statesString); if (states instanceof JSONArray) { JSONArray statesJson = (JSONArray) states; for (int i = 0; i < statesJson.length(); i++) { JSONObject stateJson = statesJson.getJSONObject(i); state = visitState(stateJson, state); } } else if (states instanceof JSONObject) { JSONObject stateJson = (JSONObject) states; state = visitState(stateJson, null); } else { throw new JSONException("Input string is not array and not object"); } return state; }
From source file:com.github.jberkel.pay.me.model.Purchase.java
/** * @param itemType the item type for this purchase, cannot be null. * @param jsonPurchaseInfo the JSON representation of this purchase * @param signature the signature// w ww . ja v a2s . c om * @throws JSONException if the purchase cannot be parsed or is invalid. */ public Purchase(ItemType itemType, String jsonPurchaseInfo, String signature) throws JSONException { if (itemType == null) throw new IllegalArgumentException("itemType cannot be null"); mItemType = itemType; final JSONObject json = new JSONObject(jsonPurchaseInfo); mOrderId = json.optString(ORDER_ID); mPackageName = json.optString(PACKAGE_NAME); mSku = json.optString(PRODUCT_ID); mPurchaseTime = json.optLong(PURCHASE_TIME); mPurchaseState = json.optInt(PURCHASE_STATE); mDeveloperPayload = json.optString(DEVELOPER_PAYLOAD); mToken = json.optString(TOKEN, json.optString(PURCHASE_TOKEN)); mOriginalJson = jsonPurchaseInfo; mSignature = signature; mState = State.fromCode(mPurchaseState); if (TextUtils.isEmpty(mSku)) { throw new JSONException("SKU is empty"); } }
From source file:com.rapid.actions.Webservice.java
@Override public JSONObject doAction(RapidRequest rapidRequest, JSONObject jsonAction) throws Exception { _logger.trace("Webservice action : " + jsonAction); // get the application Application application = rapidRequest.getApplication(); // get the page Page page = rapidRequest.getPage();/*from w w w . j a v a 2 s.c o m*/ // get the webservice action call sequence int sequence = jsonAction.optInt("sequence", 1); // placeholder for the object we're about to return JSONObject jsonData = null; // only proceed if there is a request and application and page if (_request != null && application != null && page != null) { // get any json inputs JSONArray jsonInputs = jsonAction.optJSONArray("inputs"); // placeholder for the action cache ActionCache actionCache = rapidRequest.getRapidServlet().getActionCache(); // if an action cache was found if (actionCache != null) { // log that we found action cache _logger.debug("Webservice action cache found"); // attempt to fetch data from the cache jsonData = actionCache.get(application.getId(), getId(), jsonInputs.toString()); } // if there is either no cache or we got no data if (jsonData == null) { // get the body into a string String body = _request.getBody().trim(); // remove prolog if present if (body.indexOf("\"?>") > 0) body = body.substring(body.indexOf("\"?>") + 3).trim(); // check number of parameters int pCount = Strings.occurrences(body, "?"); // throw error if incorrect if (pCount != jsonInputs.length()) throw new Exception("Request has " + pCount + " parameter" + (pCount == 1 ? "" : "s") + ", " + jsonInputs.length() + " provided"); // retain the current position int pos = body.indexOf("?"); // keep track of the index of the ? int index = 0; // if there are any question marks if (pos > 0 && jsonInputs.length() > index) { // loop, but check condition at the end do { // get the input JSONObject input = jsonInputs.getJSONObject(index); // url escape the value String value = XML.escape(input.optString("value")); // replace the ? with the input value body = body.substring(0, pos) + value + body.substring(pos + 1); // look for the next question mark pos = body.indexOf("?", pos + 1); // inc the index for the next round index++; // stop looping if no more ? } while (pos > 0); } // retrieve the action String action = _request.getAction(); // create a placeholder for the request url URL url = null; // get the request url String requestURL = _request.getUrl(); // if we got one if (requestURL != null) { // if the given request url starts with http use it as is, otherwise use the soa servlet if (_request.getUrl().startsWith("http")) { // trim it requestURL = requestURL.trim(); // insert any parameters requestURL = application .insertParameters(rapidRequest.getRapidServlet().getServletContext(), requestURL); // use the url url = new URL(requestURL); } else { // get our request HttpServletRequest httpRequest = rapidRequest.getRequest(); // make a url for the soa servlet url = new URL(httpRequest.getScheme(), httpRequest.getServerName(), httpRequest.getServerPort(), httpRequest.getContextPath() + "/soa"); // check whether we have any id / version seperators String[] actionParts = action.split("/"); // add this app and version if none if (actionParts.length < 2) action = application.getId() + "/" + application.getVersion() + "/" + action; } // establish the connection HttpURLConnection connection = (HttpURLConnection) url.openConnection(); // if we are requesting from ourself if (url.getPath().startsWith(rapidRequest.getRequest().getContextPath())) { // get our session id String sessionId = rapidRequest.getRequest().getSession().getId(); // add it to the call for internal authentication connection.setRequestProperty("Cookie", "JSESSIONID=" + sessionId); } // set the content type and action header accordingly if ("SOAP".equals(_request.getType())) { connection.setRequestProperty("Content-Type", "text/xml"); connection.setRequestProperty("SOAPAction", action); } else if ("JSON".equals(_request.getType())) { connection.setRequestProperty("Content-Type", "application/json"); if (action.length() > 0) connection.setRequestProperty("Action", action); } else if ("XML".equals(_request.getType())) { connection.setRequestProperty("Content-Type", "text/xml"); if (action.length() > 0) connection.setRequestProperty("Action", action); } // if a body has been specified if (body.length() > 0) { // Triggers POST. connection.setDoOutput(true); // get the output stream from the connection into which we write the request OutputStream output = connection.getOutputStream(); // write the processed body string into the request output stream output.write(body.getBytes("UTF8")); } // check the response code int responseCode = connection.getResponseCode(); // read input stream if all ok, otherwise something meaningful should be in error stream if (responseCode == 200) { // get the input stream InputStream response = connection.getInputStream(); // prepare an soaData object SOAData soaData = null; // read the response accordingly if ("JSON".equals(_request.getType())) { SOAJSONReader jsonReader = new SOAJSONReader(); String jsonResponse = Strings.getString(response); soaData = jsonReader.read(jsonResponse); } else { SOAXMLReader xmlReader = new SOAXMLReader(_request.getRoot()); soaData = xmlReader.read(response); } SOADataWriter jsonWriter = new SOARapidWriter(soaData); String jsonString = jsonWriter.write(); jsonData = new JSONObject(jsonString); if (actionCache != null) actionCache.put(application.getId(), getId(), jsonInputs.toString(), jsonData); response.close(); } else { InputStream response = connection.getErrorStream(); String errorMessage = null; if ("SOAP".equals(_request.getType())) { String responseXML = Strings.getString(response); errorMessage = XML.getElementValue(responseXML, "faultcode"); } if (errorMessage == null) { BufferedReader rd = new BufferedReader(new InputStreamReader(response)); errorMessage = rd.readLine(); rd.close(); } // log the error _logger.error(errorMessage); // only if there is no application cache show the error, otherwise it sends an empty response if (actionCache == null) { throw new JSONException( " response code " + responseCode + " from server : " + errorMessage); } else { _logger.debug("Error not shown to user due to cache : " + errorMessage); } } connection.disconnect(); } // request url != null } // jsonData == null } // got app and page // if the jsonData is still null make an empty one if (jsonData == null) jsonData = new JSONObject(); // add the sequence jsonData.put("sequence", sequence); // return the object return jsonData; }
From source file:xanthanov.droid.funrun.PlaceSearcher.java
public List<GooglePlace> getNearbyPlaces(String search, LatLng currentLocation, int radiusMeters) throws UnknownHostException, GmapException, JSONException, MalformedURLException, java.io.UnsupportedEncodingException { URL url = null;//from www. j a v a 2 s.c om HttpURLConnection conn = null; String urlString = null; CharSequence queryStr = stringToQuery.get(search); if (queryStr == null) {//If we didn't get a fixed category, must have been passed a custom search string, so search by name. queryStr = "name=" + java.net.URLEncoder.encode(search.toString(), "UTF-8"); System.out.println("Custom query string: " + queryStr); } try { urlString = mapsApiUrl + "?" + buildLocationString(currentLocation) + "&radius=" + radiusMeters + "&" + queryStr + "&sensor=true" + "&key=" + apiKey; url = new URL(urlString); conn = (HttpURLConnection) url.openConnection(); return parseJsonResult(new BufferedReader(new InputStreamReader(conn.getInputStream()))); } catch (MalformedURLException e) { throw new MalformedURLException( "Invalid URL: " + urlString + "\nPlease check your internet connection and try again."); } catch (UnknownHostException e) { throw new UnknownHostException( "Unable to connect to Google Maps.\nPlease check your internet connection and try again."); } catch (JSONException e) { throw new JSONException( "Failure parsing place info retreived from Google Maps.\nPlease try again later."); } catch (IOException e) { throw new JSONException( "Error downloading info from Google Maps.\nPlease check your internet connection and try again."); } catch (GmapException e) { throw new GmapException(e.getMessage() + "\nPlease check your internet connection and try again."); } finally { if (conn != null) conn.disconnect(); } }
From source file:com.imaginary.home.cloud.device.Light.java
static void mapLight(@Nonnull ControllerRelay relay, @Nonnull JSONObject json, @Nonnull Map<String, Object> state) throws JSONException { mapPoweredDevice(relay, json, state); state.put("deviceType", "light"); if (json.has("color")) { JSONObject color = json.getJSONObject("color"); ColorMode colorMode = null;/*ww w. ja va2 s .c om*/ float[] components = null; if (color.has("colorMode") && !color.isNull("colorMode")) { try { colorMode = ColorMode.valueOf(color.getString("colorMode")); } catch (IllegalArgumentException e) { throw new JSONException("Invalid color mode: " + color.getString("colorMode")); } } if (color.has("components") && !color.isNull("components")) { JSONArray arr = color.getJSONArray("components"); components = new float[arr.length()]; for (int i = 0; i < arr.length(); i++) { components[i] = (float) arr.getDouble(i); } } if (colorMode != null || components != null) { state.put("colorMode", colorMode); state.put("colorValues", components); } } if (json.has("brightness") && !json.isNull("brightness")) { state.put("brightness", (float) json.getDouble("brightness")); } if (json.has("supportsColorChanges")) { state.put("colorChangeSupported", !json.isNull("supportsColorChanges") && json.getBoolean("supportsColorChanges")); } if (json.has("supportsBrightnessChanges")) { state.put("dimmable", !json.isNull("supportsBrightnessChanges") && json.getBoolean("supportsBrightnessChanges")); } if (json.has("colorModes")) { JSONArray arr = json.getJSONArray("colorModes"); ColorMode[] modes = new ColorMode[arr.length()]; for (int i = 0; i < arr.length(); i++) { try { modes[i] = ColorMode.valueOf(arr.getString(i)); } catch (IllegalArgumentException e) { throw new JSONException("Invalid color mode: " + arr.getString(i)); } } state.put("colorModesSupported", modes); } }
From source file:com.bmwcarit.barefoot.roadmap.Road.java
/** * Creates a {@link Route} object from its JSON representation. * * @param json JSON representation of the {@link Route}. * @param map {@link RoadMap} object as the reference of {@link RoadPoint}s and {@link Road}s. * @return {@link Road} object./*from w w w.ja v a 2s . co m*/ * @throws JSONException thrown on JSON extraction or parsing error. */ public static Road fromJSON(JSONObject json, RoadMap map) throws JSONException { long baseid = json.getLong("road"); Road road = map .get(Heading.valueOf(json.getString("heading")) == Heading.forward ? baseid * 2 : baseid * 2 + 1); if (road == null) { throw new JSONException("road id " + json.getLong("road") + " not found"); } return road; }
From source file:com.example.android.camera2basic.AgeGender.java
@Override protected String doInBackground(Object... paths) { System.out.println("Performing Visual Recognition..."); // params comes from the execute() call: params[0] is the url. com.ibm.watson.developer_cloud.visual_recognition.v3.VisualRecognition service = new com.ibm.watson.developer_cloud.visual_recognition.v3.VisualRecognition( com.ibm.watson.developer_cloud.visual_recognition.v3.VisualRecognition.VERSION_DATE_2016_05_20); service.setApiKey("26a259b7f5dc0f5c8c1cc933d8722b0e66aed5df"); File actualImageFile = new File((String) paths[0]); // Library link : https://github.com/zetbaitsu/Compressor Bitmap compressedBitmap = Compressor.getDefault(mContext).compressToBitmap(actualImageFile); DirectoryPath = (String) paths[1]; File compressedImage = bitmapToFile(compressedBitmap); System.out.println("The size of image for Age-Gender (in kB) : " + (compressedImage.length() / 1024)); // TODO Image size may be still greater than 1 MB ! System.out.println("Detect faces"); VisualRecognitionOptions options = new VisualRecognitionOptions.Builder().images(compressedImage).build(); DetectedFaces result = service.detectFaces(options).execute(); System.out.println(result);//from w w w . j ava 2s. co m try { JSONObject obj = new JSONObject(result.toString()); JSONObject resultarray1 = obj.getJSONArray("images").getJSONObject(0); minAge = resultarray1.getJSONArray("faces").getJSONObject(0).getJSONObject("age").getInt("min"); maxAge = resultarray1.getJSONArray("faces").getJSONObject(0).getJSONObject("age").getInt("max"); gender = resultarray1.getJSONArray("faces").getJSONObject(0).getJSONObject("gender") .getString("gender"); System.out.println("Age Gender : " + minAge + ' ' + maxAge + ' ' + gender); if (minAge == 0 && maxAge == 0 && gender == "") { throw new JSONException("Age,Gender not found"); } // new TextToSpeechTask().execute(classes,DirectoryPath); } catch (JSONException e) { System.out.println("Nothing Detected in Age Gender"); } countDownLatch.countDown(); System.out.println("Latch counted down in AgeGender"); return result.toString(); }
From source file:com.loopj.android.http.handler.JsonHttpResponseHandler.java
@Override public final void onSuccess(final int statusCode, final Header[] headers, final byte[] responseBytes) { if (statusCode != HttpStatus.SC_NO_CONTENT) { Runnable parser = new Runnable() { @Override//from w w w. j a v a 2s. c om public void run() { try { final Object jsonResponse = parseResponse(responseBytes); postRunnable(new Runnable() { @Override public void run() { if (jsonResponse instanceof JSONObject) { onSuccess(statusCode, headers, (JSONObject) jsonResponse); } else if (jsonResponse instanceof JSONArray) { onSuccess(statusCode, headers, (JSONArray) jsonResponse); } else if (jsonResponse instanceof String) { onFailure(statusCode, headers, (String) jsonResponse, new JSONException("Response cannot be parsed as JSON data")); } else { onFailure(statusCode, headers, new JSONException( "Unexpected response type " + jsonResponse.getClass().getName()), (JSONObject) null); } } }); } catch (final JSONException ex) { postRunnable(new Runnable() { @Override public void run() { onFailure(statusCode, headers, ex, (JSONObject) null); } }); } } }; if (!getUseSynchronousMode()) new Thread(parser).start(); else // In synchronous mode everything should be run on one thread parser.run(); } else { onSuccess(statusCode, headers, new JSONObject()); } }
From source file:com.loopj.android.http.handler.JsonHttpResponseHandler.java
@Override public final void onFailure(final int statusCode, final Header[] headers, final byte[] responseBytes, final Throwable throwable) { if (responseBytes != null) { Runnable parser = new Runnable() { @Override/*from w w w.j a v a2 s .c om*/ public void run() { try { final Object jsonResponse = parseResponse(responseBytes); postRunnable(new Runnable() { @Override public void run() { if (jsonResponse instanceof JSONObject) { onFailure(statusCode, headers, throwable, (JSONObject) jsonResponse); } else if (jsonResponse instanceof JSONArray) { onFailure(statusCode, headers, throwable, (JSONArray) jsonResponse); } else if (jsonResponse instanceof String) { onFailure(statusCode, headers, (String) jsonResponse, throwable); } else { onFailure(statusCode, headers, new JSONException( "Unexpected response type " + jsonResponse.getClass().getName()), (JSONObject) null); } } }); } catch (final JSONException ex) { postRunnable(new Runnable() { @Override public void run() { onFailure(statusCode, headers, ex, (JSONObject) null); } }); } } }; if (!getUseSynchronousMode()) new Thread(parser).start(); else // In synchronous mode everything should be run on one thread parser.run(); } else { Log.v(LOG_TAG, "response body is null, calling onFailure(Throwable, JSONObject)"); onFailure(statusCode, headers, throwable, (JSONObject) null); } }