List of usage examples for org.json JSONException getMessage
public String getMessage()
From source file:com.example.guan.webrtc_android_7.common.WebSocketClient.java
/** * ?????????//from w w w. j a v a 2 s . c o m * * @param message */ public void send(String message) { checkIfCalledOnValidThread(); switch (state) { case NEW: case CONNECTED: // Store outgoing messages and send them after websocket client // is registered. //good Log.d(TAG, "WS ACC: " + message); wsSendQueue.add(message); return; case ERROR: case CLOSED: Log.e(TAG, "WebSocket send() in error or closed state : " + message); return; case REGISTERED: JSONObject json = new JSONObject(); try { json.put("cmd", "send"); json.put("msg", message); message = json.toString(); Log.d(TAG, "C->WSS: " + message); ws.sendTextMessage(message); } catch (JSONException e) { reportError(roomID, "WebSocket send JSON error: " + e.getMessage()); } break; } }
From source file:org.apache.cordova.filetransfer.FileTransfer.java
/** * Uploads the specified file to the server URL provided using an HTTP multipart request. * @param source Full path of the file on the file system * @param target URL of the server to receive the file * @param args JSON Array of args * @param callbackContext callback id for optional progress reports * * args[2] fileKey Name of file request parameter * args[3] fileName File name to be used on server * args[4] mimeType Describes file content type * args[5] params key:value pairs of user-defined parameters * @return FileUploadResult containing result of upload request *//* w ww. ja v a 2s. c o m*/ private void upload(final String source, final String target, JSONArray args, CallbackContext callbackContext) throws JSONException { Log.d(LOG_TAG, "upload " + source + " to " + target); // Setup the options final String fileKey = getArgument(args, 2, "file"); final String fileName = getArgument(args, 3, "image.jpg"); final String mimeType = getArgument(args, 4, "image/jpeg"); final JSONObject params = args.optJSONObject(5) == null ? new JSONObject() : args.optJSONObject(5); final boolean trustEveryone = args.optBoolean(6); // Always use chunked mode unless set to false as per API final boolean chunkedMode = args.optBoolean(7) || args.isNull(7); // Look for headers on the params map for backwards compatibility with older Cordova versions. final JSONObject headers = args.optJSONObject(8) == null ? params.optJSONObject("headers") : args.optJSONObject(8); final String objectId = args.getString(9); final String httpMethod = getArgument(args, 10, "POST"); final CordovaResourceApi resourceApi = webView.getResourceApi(); Log.d(LOG_TAG, "fileKey: " + fileKey); Log.d(LOG_TAG, "fileName: " + fileName); Log.d(LOG_TAG, "mimeType: " + mimeType); Log.d(LOG_TAG, "params: " + params); Log.d(LOG_TAG, "trustEveryone: " + trustEveryone); Log.d(LOG_TAG, "chunkedMode: " + chunkedMode); Log.d(LOG_TAG, "headers: " + headers); Log.d(LOG_TAG, "objectId: " + objectId); Log.d(LOG_TAG, "httpMethod: " + httpMethod); final Uri targetUri = resourceApi.remapUri(Uri.parse(target)); // Accept a path or a URI for the source. Uri tmpSrc = Uri.parse(source); final Uri sourceUri = resourceApi .remapUri(tmpSrc.getScheme() != null ? tmpSrc : Uri.fromFile(new File(source))); int uriType = CordovaResourceApi.getUriType(targetUri); final boolean useHttps = uriType == CordovaResourceApi.URI_TYPE_HTTPS; if (uriType != CordovaResourceApi.URI_TYPE_HTTP && !useHttps) { JSONObject error = createFileTransferError(INVALID_URL_ERR, source, target, null, 0, null); Log.e(LOG_TAG, "Unsupported URI: " + targetUri); callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.IO_EXCEPTION, error)); return; } final RequestContext context = new RequestContext(source, target, callbackContext); synchronized (activeRequests) { activeRequests.put(objectId, context); } cordova.getThreadPool().execute(new Runnable() { public void run() { if (context.aborted) { return; } HttpURLConnection conn = null; HostnameVerifier oldHostnameVerifier = null; SSLSocketFactory oldSocketFactory = null; int totalBytes = 0; int fixedLength = -1; try { // Create return object FileUploadResult result = new FileUploadResult(); FileProgressResult progress = new FileProgressResult(); //------------------ CLIENT REQUEST // Open a HTTP connection to the URL based on protocol conn = resourceApi.createHttpConnection(targetUri); if (useHttps && trustEveryone) { // Setup the HTTPS connection class to trust everyone HttpsURLConnection https = (HttpsURLConnection) conn; oldSocketFactory = trustAllHosts(https); // Save the current hostnameVerifier oldHostnameVerifier = https.getHostnameVerifier(); // Setup the connection not to verify hostnames https.setHostnameVerifier(DO_NOT_VERIFY); } // Allow Inputs conn.setDoInput(true); // Allow Outputs conn.setDoOutput(true); // Don't use a cached copy. conn.setUseCaches(false); // Use a post method. conn.setRequestMethod(httpMethod); // if we specified a Content-Type header, don't do multipart form upload boolean multipartFormUpload = (headers == null) || !headers.has("Content-Type"); if (multipartFormUpload) { conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY); } // Set the cookies on the response String cookie = getCookies(target); if (cookie != null) { conn.setRequestProperty("Cookie", cookie); } // Handle the other headers if (headers != null) { addHeadersToRequest(conn, headers); } /* * Store the non-file portions of the multipart data as a string, so that we can add it * to the contentSize, since it is part of the body of the HTTP request. */ StringBuilder beforeData = new StringBuilder(); try { for (Iterator<?> iter = params.keys(); iter.hasNext();) { Object key = iter.next(); if (!String.valueOf(key).equals("headers")) { beforeData.append(LINE_START).append(BOUNDARY).append(LINE_END); beforeData.append("Content-Disposition: form-data; name=\"").append(key.toString()) .append('"'); beforeData.append(LINE_END).append(LINE_END); beforeData.append(params.getString(key.toString())); beforeData.append(LINE_END); } } } catch (JSONException e) { Log.e(LOG_TAG, e.getMessage(), e); } beforeData.append(LINE_START).append(BOUNDARY).append(LINE_END); beforeData.append("Content-Disposition: form-data; name=\"").append(fileKey).append("\";"); beforeData.append(" filename=\"").append(fileName).append('"').append(LINE_END); beforeData.append("Content-Type: ").append(mimeType).append(LINE_END).append(LINE_END); byte[] beforeDataBytes = beforeData.toString().getBytes("UTF-8"); byte[] tailParamsBytes = (LINE_END + LINE_START + BOUNDARY + LINE_START + LINE_END) .getBytes("UTF-8"); // Get a input stream of the file on the phone OpenForReadResult readResult = resourceApi.openForRead(sourceUri); int stringLength = beforeDataBytes.length + tailParamsBytes.length; if (readResult.length >= 0) { fixedLength = (int) readResult.length; if (multipartFormUpload) fixedLength += stringLength; progress.setLengthComputable(true); progress.setTotal(fixedLength); } Log.d(LOG_TAG, "Content Length: " + fixedLength); // setFixedLengthStreamingMode causes and OutOfMemoryException on pre-Froyo devices. // http://code.google.com/p/android/issues/detail?id=3164 // It also causes OOM if HTTPS is used, even on newer devices. boolean useChunkedMode = chunkedMode && (Build.VERSION.SDK_INT < Build.VERSION_CODES.FROYO || useHttps); useChunkedMode = useChunkedMode || (fixedLength == -1); if (useChunkedMode) { conn.setChunkedStreamingMode(MAX_BUFFER_SIZE); // Although setChunkedStreamingMode sets this header, setting it explicitly here works // around an OutOfMemoryException when using https. conn.setRequestProperty("Transfer-Encoding", "chunked"); } else { conn.setFixedLengthStreamingMode(fixedLength); } conn.connect(); OutputStream sendStream = null; try { sendStream = conn.getOutputStream(); synchronized (context) { if (context.aborted) { return; } context.connection = conn; } if (multipartFormUpload) { //We don't want to change encoding, we just want this to write for all Unicode. sendStream.write(beforeDataBytes); totalBytes += beforeDataBytes.length; } // create a buffer of maximum size int bytesAvailable = readResult.inputStream.available(); int bufferSize = Math.min(bytesAvailable, MAX_BUFFER_SIZE); byte[] buffer = new byte[bufferSize]; // read file and write it into form... int bytesRead = readResult.inputStream.read(buffer, 0, bufferSize); long prevBytesRead = 0; while (bytesRead > 0) { result.setBytesSent(totalBytes); sendStream.write(buffer, 0, bytesRead); totalBytes += bytesRead; if (totalBytes > prevBytesRead + 102400) { prevBytesRead = totalBytes; Log.d(LOG_TAG, "Uploaded " + totalBytes + " of " + fixedLength + " bytes"); } bytesAvailable = readResult.inputStream.available(); bufferSize = Math.min(bytesAvailable, MAX_BUFFER_SIZE); bytesRead = readResult.inputStream.read(buffer, 0, bufferSize); // Send a progress event. progress.setLoaded(totalBytes); PluginResult progressResult = new PluginResult(PluginResult.Status.OK, progress.toJSONObject()); progressResult.setKeepCallback(true); context.sendPluginResult(progressResult); } if (multipartFormUpload) { // send multipart form data necessary after file data... sendStream.write(tailParamsBytes); totalBytes += tailParamsBytes.length; } sendStream.flush(); } finally { safeClose(readResult.inputStream); safeClose(sendStream); } synchronized (context) { context.connection = null; } Log.d(LOG_TAG, "Sent " + totalBytes + " of " + fixedLength); //------------------ read the SERVER RESPONSE String responseString; int responseCode = conn.getResponseCode(); Log.d(LOG_TAG, "response code: " + responseCode); Log.d(LOG_TAG, "response headers: " + conn.getHeaderFields()); TrackingInputStream inStream = null; try { inStream = getInputStream(conn); synchronized (context) { if (context.aborted) { return; } context.connection = conn; } ByteArrayOutputStream out = new ByteArrayOutputStream( Math.max(1024, conn.getContentLength())); byte[] buffer = new byte[1024]; int bytesRead = 0; // write bytes to file while ((bytesRead = inStream.read(buffer)) > 0) { out.write(buffer, 0, bytesRead); } responseString = out.toString("UTF-8"); } finally { synchronized (context) { context.connection = null; } safeClose(inStream); } Log.d(LOG_TAG, "got response from server"); Log.d(LOG_TAG, responseString.substring(0, Math.min(256, responseString.length()))); // send request and retrieve response result.setResponseCode(responseCode); result.setResponse(responseString); context.sendPluginResult(new PluginResult(PluginResult.Status.OK, result.toJSONObject())); } catch (FileNotFoundException e) { JSONObject error = createFileTransferError(FILE_NOT_FOUND_ERR, source, target, conn, e); Log.e(LOG_TAG, error.toString(), e); context.sendPluginResult(new PluginResult(PluginResult.Status.IO_EXCEPTION, error)); } catch (IOException e) { JSONObject error = createFileTransferError(CONNECTION_ERR, source, target, conn, e); Log.e(LOG_TAG, error.toString(), e); Log.e(LOG_TAG, "Failed after uploading " + totalBytes + " of " + fixedLength + " bytes."); context.sendPluginResult(new PluginResult(PluginResult.Status.IO_EXCEPTION, error)); } catch (JSONException e) { Log.e(LOG_TAG, e.getMessage(), e); context.sendPluginResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION)); } catch (Throwable t) { // Shouldn't happen, but will JSONObject error = createFileTransferError(CONNECTION_ERR, source, target, conn, t); Log.e(LOG_TAG, error.toString(), t); context.sendPluginResult(new PluginResult(PluginResult.Status.IO_EXCEPTION, error)); } finally { synchronized (activeRequests) { activeRequests.remove(objectId); } if (conn != null) { // Revert back to the proper verifier and socket factories // Revert back to the proper verifier and socket factories if (trustEveryone && useHttps) { HttpsURLConnection https = (HttpsURLConnection) conn; https.setHostnameVerifier(oldHostnameVerifier); https.setSSLSocketFactory(oldSocketFactory); } } } } }); }
From source file:org.apache.cordova.filetransfer.FileTransfer.java
/** * Create an error object based on the passed in errorCode * @param errorCode the error/*from w w w .j a v a 2 s .com*/ * @return JSONObject containing the error */ private static JSONObject createFileTransferError(int errorCode, String source, String target, String body, Integer httpStatus, Throwable throwable) { JSONObject error = null; try { error = new JSONObject(); error.put("code", errorCode); error.put("source", source); error.put("target", target); if (body != null) { error.put("body", body); } if (httpStatus != null) { error.put("http_status", httpStatus); } if (throwable != null) { String msg = throwable.getMessage(); if (msg == null || "".equals(msg)) { msg = throwable.toString(); } error.put("exception", msg); } } catch (JSONException e) { Log.e(LOG_TAG, e.getMessage(), e); } return error; }
From source file:com.df.dfcarchecker.CarCheck.CarCheckBasicInfoFragment.java
private void letsEnterModifyMode() { try {/*from w ww . j a v a2s.c om*/ JSONObject features = new JSONObject(jsonData).getJSONObject("features"); options = features.getJSONObject("options"); procedures = features.getJSONObject("procedures"); String brandString = options.getString("manufacturer") + " " + options.getString("series") + " " + options.getString("model"); mCarSettings.setBrandString(brandString); mCarSettings.setDisplacement(options.getString("displacement")); mCarSettings.setCategory(options.getString("category")); Country country = vehicleModel.getCountryById(Integer.toString(options.getInt("countryId"))); Brand brand = country.getBrandById(Integer.toString(options.getInt("brandId"))); Manufacturer manufacturer = brand.getProductionById(Integer.toString(options.getInt("manufacturerId"))); Series series = manufacturer.getSerialById(Integer.toString(options.getInt("seriesId"))); Model model = series.getModelById(Integer.toString(options.getInt("modelId"))); mCarSettings.setCountry(country); mCarSettings.setBrand(brand); mCarSettings.setManufacturer(manufacturer); mCarSettings.setSeries(series); mCarSettings.setModel(model); mCarSettings.setCarSettings(options.toString()); // mCarSettings.setCategory(options.getString("category")); mCarSettings.setFigure("1"); setCarSettings(model.getName()); this.getActivity().runOnUiThread(new Runnable() { public void run() { //stuff that updates ui contentLayout.setVisibility(View.VISIBLE); tableLayout.setVisibility(View.VISIBLE); CarCheckFrameFragment.showContent(); CarCheckIntegratedFragment.showContent(); // UI updateUi(); } }); this.getActivity().runOnUiThread(new Runnable() { @Override public void run() { try { // vin setEditText(rootView, R.id.bi_vin_edit, options.getString("vin")); enableView(false, rootView, R.id.bi_vin_edit); showView(false, rootView, R.id.bi_vin_button); showView(false, rootView, R.id.bi_brand_ok_button); setEditWeight(rootView, R.id.bi_vin_edit, 4f); setEditWeight(rootView, R.id.bi_brand_edit, 3f); // setSpinnerSelectionWithString(rootView, R.id.ci_regArea_spinner, procedures.getString("regArea")); setEditText(rootView, R.id.ci_licenseModel_edit, procedures.getString("licenseModel")); setSpinnerSelectionWithString(rootView, R.id.ci_vehicleType_spinner, procedures.getString("vehicleType")); setSpinnerSelectionWithString(rootView, R.id.ci_useCharacter_spinner, procedures.getString("useCharacter")); setEditText(rootView, R.id.bi_mileage_edit, procedures.getString("mileage")); setSpinnerSelectionWithString(rootView, R.id.ci_exteriorColor_spinner, procedures.getString("exteriorColor")); setSpinnerSelectionWithString(rootView, R.id.ci_regYear_spinner, procedures.getString("regDate").substring(0, 4)); setSpinnerSelectionWithString(rootView, R.id.ci_regMonth_spinner, procedures.getString("regDate").substring(6, 7)); setSpinnerSelectionWithString(rootView, R.id.ci_builtYear_spinner, procedures.getString("builtDate").substring(0, 4)); setSpinnerSelectionWithString(rootView, R.id.ci_builtMonth_spinner, procedures.getString("builtDate").substring(6, 7)); setSpinnerSelectionWithString(rootView, R.id.ct_invoice_spinner, procedures.getString("invoice")); setEditText(rootView, R.id.ct_invoice_edit, procedures.getString("invoicePrice")); setSpinnerSelectionWithString(rootView, R.id.ct_surtax_spinner, procedures.getString("surtax")); setSpinnerSelectionWithString(rootView, R.id.ci_transferCount_spinner, procedures.getString("transferCount")); // ?0? if (!procedures.getString("transferCount").equals("0")) { setSpinnerSelectionWithString(rootView, R.id.ci_transferLastYear_spinner, procedures.getString("transferLastDate").substring(0, 4)); setSpinnerSelectionWithString(rootView, R.id.ci_transferLastMonth_spinner, procedures.getString("transferLastDate").substring(6, 7)); } setEditText(rootView, R.id.ct_licencePhotoMatch_edit, procedures.getString("licensePhotoMatch")); setSpinnerSelectionWithString(rootView, R.id.ct_insurance_spinner, procedures.getString("insurance")); // ??? if (!procedures.getString("insurance").equals("")) { setSpinnerSelectionWithString(rootView, R.id.ct_insuranceRegion_spinner, procedures.getString("insuranceRegion")); setEditText(rootView, R.id.ct_insuranceAmount_edit, procedures.getString("insuranceAmount")); setSpinnerSelectionWithString(rootView, R.id.ct_insuranceCompany_spinner, procedures.getString("insuranceCompany")); setSpinnerSelectionWithString(rootView, R.id.ct_insuranceExpiryYear_spinner, procedures.getString("insuranceExpiryDate").substring(0, 4)); setSpinnerSelectionWithString(rootView, R.id.ct_insuranceExpiryMonth_spinner, procedures.getString("insuranceExpiryDate").substring(6, 7)); } setSpinnerSelectionWithString(rootView, R.id.ct_importProcedures_spinner, procedures.getString("importProcedures")); setSpinnerSelectionWithString(rootView, R.id.ct_spareTire_spinner, procedures.getString("spareTire")); setSpinnerSelectionWithString(rootView, R.id.ct_spareKey_spinner, procedures.getString("spareKey")); setEditText(rootView, R.id.ci_ownerName_edit, procedures.getString("ownerName")); setEditText(rootView, R.id.ci_ownerIdNumber_edit, procedures.getString("ownerIdNumber")); setEditText(rootView, R.id.ci_ownerPhone_edit, procedures.getString("ownerPhone")); setSpinnerSelectionWithString(rootView, R.id.ct_annualInspectionYear_spinner, procedures.getString("annualInspection").substring(0, 4)); setSpinnerSelectionWithString(rootView, R.id.ct_annualInspectionMonth_spinner, procedures.getString("annualInspection").substring(6, 7)); if (procedures.getString("compulsoryInsurance").equals("")) { setSpinnerSelectionWithString(rootView, R.id.ct_compulsoryInsurance_spinner, ""); } else { setSpinnerSelectionWithString(rootView, R.id.ct_compulsoryInsuranceYear_spinner, procedures.getString("compulsoryInsurance").substring(0, 4)); setSpinnerSelectionWithString(rootView, R.id.ct_compulsoryInsuranceMonth_spinner, procedures.getString("compulsoryInsurance").substring(6, 7)); } mProgressDialog.dismiss(); } catch (JSONException e) { } } }); } catch (Exception e) { Log.d(Common.TAG, e.getMessage()); } }
From source file:com.breel.wearables.shadowclock.graphics.ShapeShadow.java
public void parseJSON(String jsonFile) { if (jsonFile != null) { // Load all the JSONs with the numbers information try {/* w w w . j a va 2 s.c o m*/ JSONObject obj = new JSONObject(loadJSONFromAsset(jsonFile)); Log.d(TAG, "SHAPE SHADOW JSON FILE " + jsonFile + ": LOADED"); id = obj.getString("id"); JSONArray jsonPathData; JSONArray jsonShadowData; if (!id.equals("5")) { jsonPathData = obj.getJSONArray("path"); jsonShadowData = obj.getJSONArray("shadow"); Log.d(TAG, "JSON PATH DATA LENGTH: " + jsonPathData.length() + ""); Log.d(TAG, "JSON SHADOW DATA LENGTH: " + jsonShadowData.length() + ""); shapePath.reset(); for (int i = 0; i < jsonPathData.length(); i++) { try { JSONObject elem = jsonPathData.getJSONObject(i); String type = elem.getString("type"); JSONArray data = elem.getJSONArray("data"); if (type.equals("move")) { shapePath.moveTo((float) data.getInt(0), (float) data.getInt(1)); } else if (type.equals("line")) { shapePath.lineTo((float) data.getInt(0), (float) data.getInt(1)); } else if (type.equals("bezier")) { shapePath.cubicTo((float) data.getInt(0), (float) data.getInt(1), (float) data.getInt(2), (float) data.getInt(3), (float) data.getInt(4), (float) data.getInt(5)); } } catch (JSONException e) { Log.d(TAG, "JSON ELEM EXCEPTION" + e.getMessage() + ""); } } shapePath.close(); Random r = new Random(); r.nextGaussian(); JSONArray holesContainer = obj.getJSONArray("holes"); Path holePath = new Path(); for (int i = 0; i < holesContainer.length(); i++) { JSONObject jsonInside = holesContainer.getJSONObject(i); JSONArray hole = jsonInside.getJSONArray("data"); holePath.reset(); for (int j = 0; j < hole.length(); j++) { try { JSONObject elem = hole.getJSONObject(j); String type = elem.getString("type"); JSONArray data = elem.getJSONArray("data"); if (type.equals("move")) { holePath.moveTo((float) data.getInt(0), (float) data.getInt(1)); } else if (type.equals("line")) { holePath.lineTo((float) data.getInt(0), (float) data.getInt(1)); } else if (type.equals("bezier")) { holePath.cubicTo((float) data.getInt(0), (float) data.getInt(1), (float) data.getInt(2), (float) data.getInt(3), (float) data.getInt(4), (float) data.getInt(5)); } } catch (JSONException e) { Log.d(TAG, "JSON HOLE EXCEPTION" + e.getMessage() + ""); } } holePath.close(); shapePath.op(holePath, Path.Op.DIFFERENCE); } pathTransform.reset(); pathTransform.setScale(scale + 0.04f, scale + 0.04f); shapePath.transform(pathTransform); boundsPath.transform(pathTransform); pathTransform.setTranslate(positionX - 0.3f, positionY - 0.3f); shapePath.transform(pathTransform); boundsPath.transform(pathTransform); int shadowTmpX; int shadowTmpY; shadowPaths.clear(); vertexArray.clear(); for (int i = 0; i < jsonShadowData.length(); i += 2) { shadowTmpX = jsonShadowData.getInt(i); shadowTmpY = jsonShadowData.getInt(i + 1); addVertex(shadowTmpX, shadowTmpY); } } else { jsonPathData = obj.getJSONArray("path"); jsonShadowData = obj.getJSONArray("shadow"); Log.d(TAG, "JSON PATH DATA LENGTH: " + jsonPathData.length() + ""); Log.d(TAG, "JSON SHADOW DATA LENGTH: " + jsonShadowData.length() + ""); shapePath.reset(); for (int i = 0; i < jsonPathData.length(); i++) { JSONArray cords = jsonPathData.getJSONArray(i); Path chunk = new Path(); chunk.reset(); for (int j = 0; j < cords.length(); j++) { try { JSONObject elem = cords.getJSONObject(j); String type = elem.getString("type"); JSONArray data = elem.getJSONArray("data"); if (type.equals("move")) { chunk.moveTo((float) data.getInt(0), (float) data.getInt(1)); } else if (type.equals("line")) { chunk.lineTo((float) data.getInt(0), (float) data.getInt(1)); } else if (type.equals("bezier")) { chunk.cubicTo((float) data.getInt(0), (float) data.getInt(1), (float) data.getInt(2), (float) data.getInt(3), (float) data.getInt(4), (float) data.getInt(5)); } } catch (JSONException e) { Log.d(TAG, "JSON 5 NUMBER ELEM EXCEPTION" + e.getMessage() + ""); } } chunk.close(); shapePath.op(chunk, Path.Op.UNION); } pathTransform.reset(); pathTransform.setScale(scale, scale); shapePath.transform(pathTransform); boundsPath.transform(pathTransform); pathTransform.setTranslate(positionX, positionY); shapePath.transform(pathTransform); boundsPath.transform(pathTransform); shadowPaths.clear(); vertexArray.clear(); int shadowTmpX; int shadowTmpY; for (int i = 0; i < jsonShadowData.length(); i++) { JSONArray coords = jsonShadowData.getJSONArray(i); for (int j = 0; j < coords.length(); j += 2) { shadowTmpX = coords.getInt(j); shadowTmpY = coords.getInt(j + 1); addVertex((float) shadowTmpX, (float) shadowTmpY); } } } } catch (JSONException e) { Log.d(TAG, "JSON ROOT EXCEPTION" + e.getMessage() + ""); } } }
From source file:com.ota.updates.json.VersionJSONParser.java
/** * Parse the Versions array within the selected JSON string *///w w w .j a v a 2 s . c om public boolean parse() { try { JSONObject jObj = new JSONObject(mJSONString); JSONObject romObj = jObj.getJSONObject(NAME_ROM); JSONArray versionsArray = romObj.getJSONArray(NAME_VERSIONS); VersionSQLiteHelper helper = new VersionSQLiteHelper(mContext); for (int i = 0; i < versionsArray.length(); i++) { JSONObject arrayObj = versionsArray.getJSONObject(i); JSONObject versionObj = arrayObj.getJSONObject(NAME_VERSION); VersionItem versionItem = new VersionItem(); versionItem.setId(versionObj.getInt(NAME_ID)); versionItem.setDownloads(versionObj.getInt(NAME_DOWNLOADS)); versionItem.setFullName(versionObj.getString(NAME_FULL_NAME)); versionItem.setSlug(versionObj.getString(NAME_SLUG)); versionItem.setAndroidVersion(versionObj.getString(NAME_ANDROID_VERSION)); versionItem.setChangelog(versionObj.getString(NAME_CHANGELOG)); versionItem.setCreatedAt(versionObj.getString(NAME_CREATED_AT)); versionItem.setPublishedAt(versionObj.getString(NAME_PUBLISHED_AT)); versionItem.setVersionNumber(versionObj.getInt(NAME_VERSION_NUMBER)); JSONObject deltaObj = versionObj.optJSONObject(NAME_DELTA_UPLOAD); if (deltaObj != null) { versionItem.setDeltaUploadId(deltaObj.getInt(NAME_ID)); new UploadJSONParser(mContext, deltaObj.toString()).parse(); } else { versionItem.setDeltaUploadId(-1); } JSONObject fullObj = versionObj.getJSONObject(NAME_FULL_UPLOAD); versionItem.setFullUploadId(fullObj.getInt(NAME_ID)); new UploadJSONParser(mContext, fullObj.toString()).parse(); helper.addVersion(versionItem); } } catch (JSONException e) { Log.e(TAG, e.getMessage()); return false; } return true; }
From source file:com.google.identitytoolkit.GitkitClient.java
/** * Gets all user info of this web site. Underlying requests are paginated and send on demand with * given size./*from w w w. jav a2 s . co m*/ * * @param resultsPerRequest pagination size * @return lazy iterator over all user accounts. */ public Iterator<GitkitUser> getAllUsers(final Integer resultsPerRequest) { return new DownloadIterator<GitkitUser>() { private String nextPageToken = null; @Override protected Iterator<GitkitUser> getNextResults() { try { JSONObject response = rpcHelper.downloadAccount(nextPageToken, resultsPerRequest); nextPageToken = response.has("nextPageToken") ? response.getString("nextPageToken") : null; if (response.has("users")) { return jsonToList(response.getJSONArray("users")).iterator(); } } catch (JSONException e) { logger.warning(e.getMessage()); } catch (GitkitServerException e) { logger.warning(e.getMessage()); } catch (GitkitClientException e) { logger.warning(e.getMessage()); } return ImmutableSet.<GitkitUser>of().iterator(); } }; }
From source file:com.google.identitytoolkit.GitkitClient.java
/** * Gets out-of-band response. Used by oob endpoint for ResetPassword and ChangeEmail operation. * The web site needs to send user an email containing the oobUrl in the response. The user needs * to click the oobUrl to finish the operation. * * @param req http request for the oob endpoint * @param gitkitToken Gitkit token of authenticated user, required for ChangeEmail operation * @return the oob response./*from ww w. j ava 2 s . co m*/ * @throws GitkitServerException */ public OobResponse getOobResponse(HttpServletRequest req, String gitkitToken) throws GitkitServerException { try { String action = req.getParameter("action"); if ("resetPassword".equals(action)) { String oobLink = buildOobLink(req, buildPasswordResetRequest(req), action); return new OobResponse(req.getParameter("email"), null, oobLink, OobAction.RESET_PASSWORD); } else if ("changeEmail".equals(action)) { if (gitkitToken == null) { return new OobResponse("login is required"); } else { String oobLink = buildOobLink(req, buildChangeEmailRequest(req, gitkitToken), action); return new OobResponse(req.getParameter("oldEmail"), req.getParameter("newEmail"), oobLink, OobAction.CHANGE_EMAIL); } } else { return new OobResponse("unknown request"); } } catch (JSONException e) { throw new GitkitServerException(e); } catch (GitkitClientException e) { return new OobResponse(e.getMessage()); } }
From source file:org.wso2.carbon.dataservices.core.description.query.QueryFactory.java
private static void addJSONMappingResultRecord(JSONObject obj, OMElement parentEl) throws DataServiceFault { Object item;//from w w w. j a v a 2 s .c om for (String name : JSONObject.getNames(obj)) { try { item = obj.get(name); } catch (JSONException e) { throw new DataServiceFault(e, "Unexpected JSON parsing error: " + e.getMessage()); } if (name.startsWith("@")) { processJSONMappingCallQuery(name.substring(1), item, parentEl); } else { processJSONMappingResultColumn(name, item, parentEl); } } }
From source file:com.example.android.popularmoviesist2.data.FetchMovieTask.java
private void getMoviesDataFromJson(String moviesJsonStr) throws JSONException { final String JSON_LIST = "results"; final String JSON_POSTER = "poster_path"; final String JSON_TITLE = "original_title"; final String JSON_OVERVIEW = "overview"; final String JSON_VOTE = "vote_average"; final String JSON_RELEASE = "release_date"; final String JSON_ID = "id"; try {//from w ww. java2 s. c o m JSONObject moviesJson = new JSONObject(moviesJsonStr); JSONArray moviesArray = moviesJson.getJSONArray(JSON_LIST); Vector<ContentValues> cVVector = new Vector<ContentValues>(moviesArray.length()); for (int i = 0; i < moviesArray.length(); i++) { JSONObject movie = moviesArray.getJSONObject(i); String overview = movie.getString(JSON_OVERVIEW); String release = movie.getString(JSON_RELEASE); String poster = movie.getString(JSON_POSTER); String id = movie.getString(JSON_ID); String title = movie.getString(JSON_TITLE); String vote = movie.getString(JSON_VOTE); ContentValues movieValues = new ContentValues(); movieValues.put(MovieEntry.COLUMN_ID, id); movieValues.put(MovieEntry.COLUMN_POSTER, poster); movieValues.put(MovieEntry.COLUMN_TITLE, title); movieValues.put(MovieEntry.COLUMN_OVERVIEW, overview); movieValues.put(MovieEntry.COLUMN_VOTE, vote); movieValues.put(MovieEntry.COLUMN_RELEASE, release); cVVector.add(movieValues); } int inserted = 0; //delete database int rowdeleted = mContext.getContentResolver().delete(MovieEntry.CONTENT_URI, null, null); // add to database if (cVVector.size() > 0) { ContentValues[] cvArray = new ContentValues[cVVector.size()]; cVVector.toArray(cvArray); inserted = mContext.getContentResolver().bulkInsert(MovieEntry.CONTENT_URI, cvArray); } } catch (JSONException e) { Log.e(LOG_TAG, e.getMessage(), e); e.printStackTrace(); } }