List of usage examples for org.json JSONArray optJSONObject
public JSONObject optJSONObject(int index)
From source file:com.percolatestudio.cordova.fileupload.PSFileUpload.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 *///from w w w . ja v a 2 s.com 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 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, "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); 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 PSFileUploadResult result = new PSFileUploadResult(); PSFileProgressResult progress = new PSFileProgressResult(); //------------------ 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); conn.setRequestProperty("Content-Type", mimeType); // Set the cookies on the response String cookie = CookieManager.getInstance().getCookie(target); if (cookie != null) { conn.setRequestProperty("Cookie", cookie); } // Handle the other headers if (headers != null) { addHeadersToRequest(conn, headers); } // Get a input stream of the file on the phone OpenForReadResult readResult = resourceApi.openForRead(sourceUri); if (readResult.length >= 0) { fixedLength = (int) readResult.length; 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.currentOutputStream = sendStream; } //We don't want to change encoding, we just want this to write for all Unicode. // 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); } sendStream.flush(); } finally { safeClose(readResult.inputStream); safeClose(sendStream); } context.currentOutputStream = 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.currentInputStream = inStream; } 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 { context.currentInputStream = 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); 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); 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); 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:com.cloudstudio.BarcodeScanner.java
/** * Executes the request./*from w w w. j a va 2 s. co m*/ * * This method is called from the WebView thread. To do a non-trivial amount of work, use: * cordova.getThreadPool().execute(runnable); * * To run on the UI thread, use: * cordova.getActivity().runOnUiThread(runnable); * * @param action The action to execute. * @param args The exec() arguments. * @param callbackContext The callback context used when calling back into JavaScript. * @return Whether the action was valid. * * @sa https://github.com/apache/cordova-android/blob/master/framework/src/org/apache/cordova/CordovaPlugin.java */ @Override public boolean execute(String action, JSONArray args, CallbackContext callbackContext) { this.callbackContext = callbackContext; if (action.equals(ENCODE)) { JSONObject obj = args.optJSONObject(0); if (obj != null) { String type = obj.optString(TYPE); String data = obj.optString(DATA); // If the type is null then force the type to text if (type == null) { type = TEXT_TYPE; } if (data == null) { callbackContext.error("User did not specify data to encode"); return true; } encode(type, data); } else { callbackContext.error("User did not specify data to encode"); return true; } } else if (action.equals(SCAN)) { scan(); } else { return false; } return true; }
From source file:com.phonegap.plugin.ChildBrowser.java
/** * Executes the request and returns PluginResult. * * @param action The action to execute. * @param args JSONArry of arguments for the plugin. * @param callbackId The callback id used when calling back into JavaScript. * @return A PluginResult object with a status and message. *//* ww w. j av a 2s.com*/ public PluginResult execute(String action, JSONArray args, String callbackId) { PluginResult.Status status = PluginResult.Status.OK; String result = ""; try { if (action.equals("showWebPage")) { this.browserCallbackId = callbackId; // If the ChildBrowser is already open then throw an error if (dialog != null && dialog.isShowing()) { return new PluginResult(PluginResult.Status.ERROR, "ChildBrowser is already open"); } result = this.showWebPage(args.getString(0), args.optJSONObject(1)); if (result.length() > 0) { status = PluginResult.Status.ERROR; return new PluginResult(status, result); } else { PluginResult pluginResult = new PluginResult(status, result); pluginResult.setKeepCallback(true); return pluginResult; } } else if (action.equals("close")) { closeDialog(); JSONObject obj = new JSONObject(); obj.put("type", CLOSE_EVENT); PluginResult pluginResult = new PluginResult(status, obj); pluginResult.setKeepCallback(false); return pluginResult; } else if (action.equals("openExternal")) { result = this.openExternal(args.getString(0), args.optBoolean(1)); if (result.length() > 0) { status = PluginResult.Status.ERROR; } } else { status = PluginResult.Status.INVALID_ACTION; } return new PluginResult(status, result); } catch (JSONException e) { return new PluginResult(PluginResult.Status.JSON_EXCEPTION); } }
From source file:com.phonegap.FileTransfer.java
@Override public PluginResult execute(String action, JSONArray args, String callbackId) { String file = null;/*from w w w .ja v a 2s . c o m*/ String server = null; try { file = args.getString(0); server = args.getString(1); } catch (JSONException e) { Log.d(LOG_TAG, "Missing filename or server name"); return new PluginResult(PluginResult.Status.JSON_EXCEPTION, "Missing filename or server name"); } // Setup the options String fileKey = null; String fileName = null; String mimeType = null; fileKey = getArgument(args, 2, "file"); fileName = getArgument(args, 3, "image.jpg"); mimeType = getArgument(args, 4, "image/jpeg"); try { JSONObject params = args.optJSONObject(5); boolean trustEveryone = args.optBoolean(6); if (action.equals("upload")) { FileUploadResult r = upload(file, server, fileKey, fileName, mimeType, params, trustEveryone); Log.d(LOG_TAG, "****** About to return a result from upload"); return new PluginResult(PluginResult.Status.OK, r.toJSONObject()); } else { return new PluginResult(PluginResult.Status.INVALID_ACTION); } } catch (FileNotFoundException e) { Log.e(LOG_TAG, e.getMessage(), e); JSONObject error = createFileUploadError(FILE_NOT_FOUND_ERR); return new PluginResult(PluginResult.Status.IO_EXCEPTION, error); } catch (IllegalArgumentException e) { Log.e(LOG_TAG, e.getMessage(), e); JSONObject error = createFileUploadError(INVALID_URL_ERR); return new PluginResult(PluginResult.Status.IO_EXCEPTION, error); } catch (SSLException e) { Log.e(LOG_TAG, e.getMessage(), e); Log.d(LOG_TAG, "Got my ssl exception!!!"); JSONObject error = createFileUploadError(CONNECTION_ERR); return new PluginResult(PluginResult.Status.IO_EXCEPTION, error); } catch (IOException e) { Log.e(LOG_TAG, e.getMessage(), e); JSONObject error = createFileUploadError(CONNECTION_ERR); return new PluginResult(PluginResult.Status.IO_EXCEPTION, error); } catch (JSONException e) { Log.e(LOG_TAG, e.getMessage(), e); return new PluginResult(PluginResult.Status.JSON_EXCEPTION); } }
From source file:com.facebook.share.ShareApi.java
private static void handleImagesOnAction(Bundle parameters) { // In general, graph objects are passed by reference (ID/URL). But if this is an OG Action, // we need to pass the entire values of the contents of the 'image' property, as they // contain important metadata beyond just a URL. String imageStr = parameters.getString("image"); if (imageStr != null) { try {/*from w ww.ja v a 2 s .c o m*/ // Check to see if this is an json array. Will throw if not JSONArray images = new JSONArray(imageStr); for (int i = 0; i < images.length(); ++i) { JSONObject jsonImage = images.optJSONObject(i); if (jsonImage != null) { putImageInBundleWithArrayFormat(parameters, i, jsonImage); } else { // If we don't have jsonImage we probably just have a url String url = images.getString(i); parameters.putString(String.format(Locale.ROOT, "image[%d][url]", i), url); } } parameters.remove("image"); return; } catch (JSONException ex) { // We couldn't parse the string as an array } // If the image is not in an array it might just be an single photo try { JSONObject image = new JSONObject(imageStr); putImageInBundleWithArrayFormat(parameters, 0, image); parameters.remove("image"); } catch (JSONException exception) { // The image was not in array format or a json object and can be safely passed // without modification } } }
From source file:com.polyvi.xface.extension.security.XSecurityExt.java
public boolean execute(String action, final JSONArray args, final CallbackContext callbackContext) throws JSONException { if (action.equals(COMMAND_ENCRYPT)) { threadhelper(new SecurityOp() { @Override/*w w w . j a v a 2 s. c o m*/ public void run() throws Exception { String encryptResult = encrypt(args.getString(0), args.getString(1), args.optJSONObject(2)); callbackContext.success(encryptResult); } }, callbackContext); } else if (action.equals(COMMAND_DECRYPT)) { threadhelper(new SecurityOp() { @Override public void run() throws Exception { String decryptResult = decrypt(args.getString(0), args.getString(1), args.optJSONObject(2)); callbackContext.success(decryptResult); } }, callbackContext); } else if (action.equals(COMMAND_ENCRYPT_FILE)) { threadhelper(new SecurityOp() { @Override public void run() throws Exception { String result = encryptFile(args.getString(0), args.getString(1), args.getString(2)); callbackContext.success(result); } }, callbackContext); } else if (action.equals(COMMAND_DECRYPT_FILE)) { threadhelper(new SecurityOp() { @Override public void run() throws Exception { String result = decryptFile(args.getString(0), args.getString(1), args.getString(2)); callbackContext.success(result); } }, callbackContext); } else if (action.equals(COMMAND_DIGEST)) { threadhelper(new SecurityOp() { @Override public void run() throws Exception { String result = digest(args.getString(0)); callbackContext.success(result); } }, callbackContext); } else { return false; // Invalid action, return false } return true; }
From source file:net.portalblockz.portalbot.serverdata.JSONConfigManager.java
public void serializeRepos() { JSONArray repoArray = configObject.optJSONArray("git-repos"); if (repoArray != null) { for (int i = 0; i < repoArray.length(); i++) { JSONObject repoData = repoArray.optJSONObject(i); if (repoData != null) { String name = repoData.getString("name"); String dispName = repoData.optString("dispName"); dispName = (dispName == null || dispName.length() < 1) ? name : dispName; List<String> repoChannels = new ArrayList<>(); for (int n = 0; n < repoData.getJSONArray("channels").length(); n++) { repoChannels.add(repoData.getJSONArray("channels").getString(n).toLowerCase()); }//from www . ja v a 2s .c o m repoMap.put(name.toLowerCase(), repoChannels); repoDispNames.put(name.toLowerCase(), dispName); } } } }
From source file:com.trellmor.berrytube.BerryTubeIOCallback.java
/** * @see io.socket.IOCallback#on(java.lang.String, io.socket.IOAcknowledge, * java.lang.Object[])//from w w w . jav a 2s .co m */ public void on(String event, IOAcknowledge ack, Object... args) { if (event.compareTo("chatMsg") == 0) { if (args.length >= 1 && args[0] instanceof JSONObject) { JSONObject jsonMsg = (JSONObject) args[0]; try { berryTube.getHandler() .post(berryTube.new ChatMsgTask(new ChatMessage(jsonMsg.getJSONObject("msg")))); } catch (JSONException e) { Log.e(TAG, "chatMsg", e); } } else Log.w(TAG, "chatMsg message is not a JSONObject"); } else if (event.compareTo("setNick") == 0) { if (args.length >= 1 && args[0] instanceof String) { berryTube.getHandler().post(berryTube.new SetNickTask((String) args[0])); } else Log.w(TAG, "setNick message is not a String"); } else if (event.compareTo("loginError") == 0) { if (args.length >= 1 && args[0] instanceof JSONObject) { JSONObject error = (JSONObject) args[0]; berryTube.getHandler() .post(berryTube.new LoginErrorTask(error.optString("message", "Login failed"))); } } else if (event.compareTo("userJoin") == 0) { if (args.length >= 1 && args[0] instanceof JSONObject) { JSONObject user = (JSONObject) args[0]; try { berryTube.getHandler().post(berryTube.new UserJoinPartTask(new ChatUser(user), BerryTube.UserJoinPartTask.ACTION_JOIN)); } catch (JSONException e) { Log.e(TAG, "userJoin", e); } } else Log.w(TAG, "userJoin message is not a JSONObject"); } else if (event.compareTo("newChatList") == 0) { berryTube.getHandler().post(berryTube.new UserResetTask()); if (args.length >= 1 && args[0] instanceof JSONArray) { JSONArray users = (JSONArray) args[0]; for (int i = 0; i < users.length(); i++) { JSONObject user = users.optJSONObject(i); if (user != null) { try { berryTube.getHandler().post(berryTube.new UserJoinPartTask(new ChatUser(user), BerryTube.UserJoinPartTask.ACTION_JOIN)); } catch (JSONException e) { Log.e(TAG, "newChatList", e); } } } } else Log.w(TAG, "newChatList message is not a JSONArray"); } else if (event.compareTo("userPart") == 0) { if (args.length >= 1 && args[0] instanceof JSONObject) { JSONObject user = (JSONObject) args[0]; try { berryTube.getHandler().post(berryTube.new UserJoinPartTask(new ChatUser(user), BerryTube.UserJoinPartTask.ACTION_PART)); } catch (JSONException e) { Log.e(TAG, "userPart", e); } } else Log.w(TAG, "userPart message is not a JSONObject"); } else if (event.compareTo("drinkCount") == 0) { if (args.length >= 1 && args[0] instanceof JSONObject) { JSONObject drinks = (JSONObject) args[0]; berryTube.getHandler().post(berryTube.new DrinkCountTask(drinks.optInt("drinks"))); } } else if (event.compareTo("kicked") == 0) { berryTube.getHandler().post(berryTube.new KickedTask()); } else if (event.compareTo("newPoll") == 0) { if (args.length >= 1 && args[0] instanceof JSONObject) { JSONObject poll = (JSONObject) args[0]; ChatMessage msg; // Send chat message for new poll try { msg = new ChatMessage(poll.getString("creator"), poll.getString("title"), ChatMessage.EMOTE_POLL, 0, 0, false, 1); berryTube.getHandler().post(berryTube.new ChatMsgTask(msg)); } catch (JSONException e) { Log.e(TAG, "newPoll", e); } // Create new poll try { berryTube.getHandler().post(berryTube.new NewPollTask(new Poll(poll))); } catch (JSONException e) { Log.e(TAG, "newPoll", e); } } } else if (event.compareTo("updatePoll") == 0) { if (args.length >= 1 && args[0] instanceof JSONObject) { JSONObject poll = (JSONObject) args[0]; try { JSONArray votes = poll.getJSONArray("votes"); int[] voteArray = new int[votes.length()]; for (int i = 0; i < votes.length(); i++) { voteArray[i] = votes.optInt(i, -1); } berryTube.getHandler().post(berryTube.new UpdatePollTask(voteArray)); } catch (JSONException e) { Log.e(TAG, "updatePoll", e); } } } else if (event.compareTo("clearPoll") == 0) { berryTube.getHandler().post(berryTube.new ClearPollTask()); } else if (event.compareTo("forceVideoChange") == 0 || event.compareTo("hbVideoDetail") == 0) { if (args.length >= 1 && args[0] instanceof JSONObject) { JSONObject videoMsg = (JSONObject) args[0]; try { JSONObject video = videoMsg.getJSONObject("video"); String name = URLDecoder.decode(video.getString("videotitle"), "UTF-8"); String id = video.getString("videoid"); String type = video.getString("videotype"); berryTube.getHandler().post(berryTube.new NewVideoTask(name, id, type)); } catch (JSONException | UnsupportedEncodingException e) { Log.w(TAG, e); } } } }
From source file:com.sina.weibo.sdk_lib.openapi.models.Favorite.java
public static Favorite parse(JSONObject jsonObject) { if (null == jsonObject) { return null; }/*from w ww .j a v a2 s .c om*/ Favorite favorite = new Favorite(); favorite.status = Status.parse(jsonObject.optJSONObject("status")); favorite.favorited_time = jsonObject.optString("favorited_time"); JSONArray jsonArray = jsonObject.optJSONArray("tags"); if (jsonArray != null && jsonArray.length() > 0) { int length = jsonArray.length(); favorite.tags = new ArrayList<Tag>(length); for (int ix = 0; ix < length; ix++) { favorite.tags.add(Tag.parse(jsonArray.optJSONObject(ix))); } } return favorite; }
From source file:com.eutectoid.dosomething.picker.GraphObjectCursor.java
public void addGraphObjects(JSONArray graphObjects) { for (int i = 0; i < graphObjects.length(); ++i) { this.graphObjects.add(graphObjects.optJSONObject(i)); }/*from ww w . j av a 2s . com*/ }