Example usage for org.json JSONObject optJSONObject

List of usage examples for org.json JSONObject optJSONObject

Introduction

In this page you can find the example usage for org.json JSONObject optJSONObject.

Prototype

public JSONObject optJSONObject(String key) 

Source Link

Document

Get an optional JSONObject associated with a key.

Usage

From source file:at.alladin.rmbt.android.util.CheckSettingsTask.java

/**
* 
*//*from   w w w .  j av a2 s. c  o  m*/
@Override
protected void onPostExecute(final JSONArray resultList) {
    try {
        if (serverConn.hasError())
            hasError = true;
        else if (resultList != null && resultList.length() > 0) {

            JSONObject resultListItem;

            try {
                resultListItem = resultList.getJSONObject(0);

                /* UUID */

                final String uuid = resultListItem.optString("uuid", "");
                if (uuid != null && uuid.length() != 0)
                    ConfigHelper.setUUID(activity.getApplicationContext(), uuid);

                /* urls */

                final ConcurrentMap<String, String> volatileSettings = ConfigHelper.getVolatileSettings();

                final JSONObject urls = resultListItem.optJSONObject("urls");
                if (urls != null) {
                    final Iterator<String> keys = urls.keys();

                    while (keys.hasNext()) {
                        final String key = keys.next();
                        final String value = urls.optString(key, null);
                        if (value != null) {
                            volatileSettings.put("url_" + key, value);
                            if ("statistics".equals(key)) {
                                ConfigHelper.setCachedStatisticsUrl(value, activity);
                            } else if ("control_ipv4_only".equals(key)) {
                                ConfigHelper.setCachedControlServerNameIpv4(value, activity);
                            } else if ("control_ipv6_only".equals(key)) {
                                ConfigHelper.setCachedControlServerNameIpv6(value, activity);
                            } else if ("url_ipv4_check".equals(key)) {
                                ConfigHelper.setCachedIpv4CheckUrl(value, activity);
                            } else if ("url_ipv6_check".equals(key)) {
                                ConfigHelper.setCachedIpv6CheckUrl(value, activity);
                            }
                        }
                    }
                }

                /* qos names */
                final JSONArray qosNames = resultListItem.optJSONArray("qostesttype_desc");
                if (qosNames != null) {
                    final Map<String, String> qosNamesMap = new HashMap<String, String>();
                    for (int i = 0; i < qosNames.length(); i++) {
                        JSONObject json = qosNames.getJSONObject(i);
                        qosNamesMap.put(json.optString("test_type"), json.optString("name"));
                    }
                    ConfigHelper.setCachedQoSNames(qosNamesMap, activity);
                }

                /* map server */

                final JSONObject mapServer = resultListItem.optJSONObject("map_server");
                if (mapServer != null) {
                    final String host = mapServer.optString("host");
                    final int port = mapServer.optInt("port");
                    final boolean ssl = mapServer.optBoolean("ssl");
                    if (host != null && port > 0)
                        ConfigHelper.setMapServer(host, port, ssl);
                }

                /* control server version */
                final JSONObject versions = resultListItem.optJSONObject("versions");
                if (versions != null) {
                    if (versions.has("control_server_version")) {
                        ConfigHelper.setControlServerVersion(activity,
                                versions.optString("control_server_version"));
                    }
                }

                // ///////////////////////////////////////////////////////
                // HISTORY / FILTER

                final JSONObject historyObject = resultListItem.getJSONObject("history");

                final JSONArray deviceArray = historyObject.getJSONArray("devices");
                final JSONArray networkArray = historyObject.getJSONArray("networks");

                final String historyDevices[] = new String[deviceArray.length()];

                for (int i = 0; i < deviceArray.length(); i++)
                    historyDevices[i] = deviceArray.getString(i);

                final String historyNetworks[] = new String[networkArray.length()];

                for (int i = 0; i < networkArray.length(); i++)
                    historyNetworks[i] = networkArray.getString(i);

                // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////
                // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////

                activity.setSettings(historyDevices, historyNetworks);

                activity.setHistoryDirty(true);

            } catch (final JSONException e) {
                e.printStackTrace();
            }

        } else
            Log.i(DEBUG_TAG, "LEERE LISTE");
    } finally {
        if (endTaskListener != null)
            endTaskListener.taskEnded(resultList);
    }
}

From source file:org.catnut.fragment.ProfileFragment.java

@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
    // ??*_*?view?
    String query = CatnutUtils.buildQuery(PROJECTION, User.screen_name + "=" + CatnutUtils.quote(mScreenName),
            User.TABLE, null, null, null);
    new AsyncQueryHandler(getActivity().getContentResolver()) {
        @Override//  w  ww. ja  v  a  2s  .c  o  m
        protected void onQueryComplete(int token, Object cookie, Cursor cursor) {
            if (cursor.moveToNext()) {
                injectProfile(cursor);
            } else {
                // fall back to load from network...
                mApp.getRequestQueue().add(new CatnutRequest(getActivity(), UserAPI.profile(mScreenName),
                        new UserProcessor.UserProfileProcessor(), new Response.Listener<JSONObject>() {
                            @Override
                            public void onResponse(JSONObject response) {
                                injectProfile(response);
                            }
                        }, new Response.ErrorListener() {
                            @Override
                            public void onErrorResponse(VolleyError error) {
                                Toast.makeText(getActivity(), getString(R.string.user_not_found),
                                        Toast.LENGTH_SHORT).show();
                            }
                        }));
            }
            cursor.close();
        }
    }.startQuery(0, null, CatnutProvider.parse(User.MULTIPLE), null, query, null, null);
    // ??
    if (mApp.getPreferences().getBoolean(getString(R.string.pref_show_latest_tweet), true)) {
        String queryLatestTweet = CatnutUtils.buildQuery(new String[] { Status.columnText,
                //                     Status.thumbnail_pic,
                Status.bmiddle_pic, Status.comments_count, Status.reposts_count, Status.retweeted_status,
                Status.attitudes_count, Status.source, Status.created_at, },
                new StringBuilder("uid=(select _id from ").append(User.TABLE).append(" where ")
                        .append(User.screen_name).append("=").append(CatnutUtils.quote(mScreenName)).append(")")
                        .append(" and ").append(Status.TYPE).append(" in(").append(Status.HOME).append(",")
                        .append(Status.RETWEET).append(",").append(Status.OTHERS).append(")").toString(),
                Status.TABLE, null, BaseColumns._ID + " desc", "1");
        new AsyncQueryHandler(getActivity().getContentResolver()) {
            @Override
            protected void onQueryComplete(int token, Object cookie, Cursor cursor) {
                if (cursor.moveToNext()) {
                    mTweetLayout.setOnClickListener(tweetsOnclickListener);
                    ViewStub viewStub = (ViewStub) mTweetLayout.findViewById(R.id.latest_tweet);
                    View tweet = viewStub.inflate();
                    mRetweetLayout = tweet.findViewById(R.id.retweet);
                    tweet.findViewById(R.id.timeline).setVisibility(View.GONE);
                    tweet.findViewById(R.id.verified).setVisibility(View.GONE);
                    tweet.findViewById(R.id.tweet_overflow).setVisibility(View.GONE);
                    CatnutUtils.setText(tweet, R.id.nick, getString(R.string.latest_statues))
                            .setTextColor(getResources().getColor(R.color.actionbar_background));
                    String tweetText = cursor.getString(cursor.getColumnIndex(Status.columnText));
                    TweetImageSpan tweetImageSpan = new TweetImageSpan(getActivity());
                    TweetTextView text = (TweetTextView) CatnutUtils.setText(tweet, R.id.text,
                            tweetImageSpan.getImageSpan(tweetText));
                    CatnutUtils.vividTweet(text, null);
                    CatnutUtils.setTypeface(text, mTypeface);
                    text.setLineSpacing(0, mLineSpacing);

                    String thumbsUrl = cursor.getString(cursor.getColumnIndex(Status.bmiddle_pic));
                    if (!TextUtils.isEmpty(thumbsUrl)) {
                        View thumbs = tweet.findViewById(R.id.thumbs);
                        Picasso.with(getActivity()).load(thumbsUrl).placeholder(R.drawable.error)
                                .error(R.drawable.error).into((ImageView) thumbs);
                        thumbs.setVisibility(View.VISIBLE);
                    }

                    int replyCount = cursor.getInt(cursor.getColumnIndex(Status.comments_count));
                    CatnutUtils.setText(tweet, R.id.reply_count, CatnutUtils.approximate(replyCount));
                    int retweetCount = cursor.getInt(cursor.getColumnIndex(Status.reposts_count));
                    CatnutUtils.setText(tweet, R.id.reteet_count, CatnutUtils.approximate(retweetCount));
                    int favoriteCount = cursor.getInt(cursor.getColumnIndex(Status.attitudes_count));
                    CatnutUtils.setText(tweet, R.id.like_count, CatnutUtils.approximate(favoriteCount));
                    String source = cursor.getString(cursor.getColumnIndex(Status.source));
                    CatnutUtils.setText(tweet, R.id.source, Html.fromHtml(source).toString());
                    String create_at = cursor.getString(cursor.getColumnIndex(Status.created_at));
                    CatnutUtils
                            .setText(tweet, R.id.create_at,
                                    DateUtils.getRelativeTimeSpanString(DateTime.getTimeMills(create_at)))
                            .setVisibility(View.VISIBLE);
                    // retweet
                    final String jsonString = cursor.getString(cursor.getColumnIndex(Status.retweeted_status));
                    try {
                        JSONObject jsonObject = new JSONObject(jsonString);
                        TweetTextView retweet = (TweetTextView) mRetweetLayout.findViewById(R.id.retweet_text);
                        retweet.setText(jsonObject.optString(Status.text));
                        CatnutUtils.vividTweet(retweet, tweetImageSpan);
                        CatnutUtils.setTypeface(retweet, mTypeface);
                        retweet.setLineSpacing(0, mLineSpacing);
                        long mills = DateTime.getTimeMills(jsonObject.optString(Status.created_at));
                        TextView tv = (TextView) mRetweetLayout.findViewById(R.id.retweet_create_at);
                        tv.setText(DateUtils.getRelativeTimeSpanString(mills));
                        TextView retweetUserScreenName = (TextView) mRetweetLayout
                                .findViewById(R.id.retweet_nick);
                        JSONObject user = jsonObject.optJSONObject(User.SINGLE);
                        if (user == null) {
                            retweetUserScreenName.setText(getString(R.string.unknown_user));
                        } else {
                            retweetUserScreenName.setText(user.optString(User.screen_name));
                            mRetweetLayout.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    Intent intent = new Intent(getActivity(), TweetActivity.class);
                                    intent.putExtra(Constants.JSON, jsonString);
                                    startActivity(intent);
                                }
                            });
                        }
                    } catch (Exception e) {
                        mRetweetLayout.setVisibility(View.GONE);
                    }
                }
                cursor.close();
            }
        }.startQuery(0, null, CatnutProvider.parse(Status.MULTIPLE), null, queryLatestTweet, null, null);
    }
}

From source file:com.facebook.internal.LikeActionController.java

private static LikeActionController deserializeFromJson(String controllerJsonString) {
    LikeActionController controller;/*from  w  ww . j a  v a2s.c  o m*/

    try {
        JSONObject controllerJson = new JSONObject(controllerJsonString);
        int version = controllerJson.optInt(JSON_INT_VERSION_KEY, -1);
        if (version != LIKE_ACTION_CONTROLLER_VERSION) {
            // Don't attempt to deserialize a controller that might be serialized differently than expected.
            return null;
        }

        controller = new LikeActionController(Session.getActiveSession(),
                controllerJson.getString(JSON_STRING_OBJECT_ID_KEY));

        // Make sure to default to null and not empty string, to keep the logic elsewhere functioning properly.
        controller.likeCountStringWithLike = controllerJson.optString(JSON_STRING_LIKE_COUNT_WITH_LIKE_KEY,
                null);
        controller.likeCountStringWithoutLike = controllerJson
                .optString(JSON_STRING_LIKE_COUNT_WITHOUT_LIKE_KEY, null);
        controller.socialSentenceWithLike = controllerJson.optString(JSON_STRING_SOCIAL_SENTENCE_WITH_LIKE_KEY,
                null);
        controller.socialSentenceWithoutLike = controllerJson
                .optString(JSON_STRING_SOCIAL_SENTENCE_WITHOUT_LIKE_KEY, null);
        controller.isObjectLiked = controllerJson.optBoolean(JSON_BOOL_IS_OBJECT_LIKED_KEY);
        controller.unlikeToken = controllerJson.optString(JSON_STRING_UNLIKE_TOKEN_KEY, null);
        String pendingCallIdString = controllerJson.optString(JSON_STRING_PENDING_CALL_ID_KEY, null);
        if (!Utility.isNullOrEmpty(pendingCallIdString)) {
            controller.pendingCallId = UUID.fromString(pendingCallIdString);
        }

        JSONObject analyticsJSON = controllerJson.optJSONObject(JSON_BUNDLE_PENDING_CALL_ANALYTICS_BUNDLE);
        if (analyticsJSON != null) {
            controller.pendingCallAnalyticsBundle = BundleJSONConverter.convertToBundle(analyticsJSON);
        }
    } catch (JSONException e) {
        Log.e(TAG, "Unable to deserialize controller from JSON", e);
        controller = null;
    }

    return controller;
}

From source file:fr.cobaltians.cobalt.fragments.CobaltFragment.java

/**
 * This method is called when the JavaScript sends a message to the native side.
 * This method should be overridden in subclasses.
 * @param message : the JSON-message sent by JavaScript.
 * @return true if the message was handled by the native, false otherwise
 * @details some basic operations are already implemented : navigation, logs, toasts, native alerts, web alerts
 * @details this method may be called from a secondary thread.
 *//*from   w  w  w. jav  a  2  s.c o  m*/
// This method must be public !!!
@JavascriptInterface
public boolean onCobaltMessage(String message) {
    try {
        final JSONObject jsonObj = new JSONObject(message);

        // TYPE
        if (jsonObj.has(Cobalt.kJSType)) {
            String type = jsonObj.getString(Cobalt.kJSType);

            //CALLBACK
            if (type.equals(Cobalt.JSTypeCallBack)) {
                String callbackID = jsonObj.getString(Cobalt.kJSCallback);
                JSONObject data = jsonObj.optJSONObject(Cobalt.kJSData);

                return handleCallback(callbackID, data);
            }

            // COBALT IS READY
            else if (type.equals(Cobalt.JSTypeCobaltIsReady)) {
                String versionWeb = jsonObj.optString(Cobalt.kJSVersion, null);
                String versionNative = getResources().getString(R.string.version_name);
                if (versionWeb != null && !versionWeb.equals(versionNative))
                    Log.e(TAG, "Warning : Cobalt version mismatch : Android Cobalt version is " + versionNative
                            + " but Web Cobalt version is " + versionWeb + ". You should fix this. ");
                onCobaltIsReady();
                return true;
            }

            // EVENT
            else if (type.equals(Cobalt.JSTypeEvent)) {
                String event = jsonObj.getString(Cobalt.kJSEvent);
                JSONObject data = jsonObj.optJSONObject(Cobalt.kJSData);
                String callback = jsonObj.optString(Cobalt.kJSCallback, null);

                return handleEvent(event, data, callback);
            }

            // INTENT
            else if (type.equals(Cobalt.JSTypeIntent)) {
                String action = jsonObj.getString(Cobalt.kJSAction);

                // OPEN EXTERNAL URL
                if (action.equals(Cobalt.JSActionIntentOpenExternalUrl)) {
                    JSONObject data = jsonObj.getJSONObject(Cobalt.kJSData);
                    String url = data.getString(Cobalt.kJSUrl);
                    openExternalUrl(url);

                    return true;
                }

                // UNHANDLED INTENT
                else {
                    onUnhandledMessage(jsonObj);
                }
            }

            // LOG
            else if (type.equals(Cobalt.JSTypeLog)) {
                String text = jsonObj.getString(Cobalt.kJSValue);
                Log.d(Cobalt.TAG, "JS LOG: " + text);
                return true;
            }

            // NAVIGATION
            else if (type.equals(Cobalt.JSTypeNavigation)) {
                String action = jsonObj.getString(Cobalt.kJSAction);

                // PUSH
                if (action.equals(Cobalt.JSActionNavigationPush)) {
                    JSONObject data = jsonObj.getJSONObject(Cobalt.kJSData);
                    String page = data.getString(Cobalt.kJSPage);
                    String controller = data.optString(Cobalt.kJSController, null);
                    push(controller, page);
                    return true;
                }

                // POP
                else if (action.equals(Cobalt.JSActionNavigationPop)) {
                    JSONObject data = jsonObj.optJSONObject(Cobalt.kJSData);
                    if (data != null) {
                        String page = data.getString(Cobalt.kJSPage);
                        String controller = data.optString(Cobalt.kJSController, null);
                        pop(controller, page);
                    } else
                        pop();
                    return true;
                }

                // MODAL
                else if (action.equals(Cobalt.JSActionNavigationModal)) {
                    JSONObject data = jsonObj.getJSONObject(Cobalt.kJSData);
                    String page = data.getString(Cobalt.kJSPage);
                    String controller = data.optString(Cobalt.kJSController, null);
                    String callbackId = jsonObj.optString(Cobalt.kJSCallback, null);
                    presentModal(controller, page, callbackId);
                    return true;
                }

                // DISMISS
                else if (action.equals(Cobalt.JSActionNavigationDismiss)) {
                    // TODO: not present in iOS
                    JSONObject data = jsonObj.getJSONObject(Cobalt.kJSData);
                    String controller = data.getString(Cobalt.kJSController);
                    String page = data.getString(Cobalt.kJSPage);
                    dismissModal(controller, page);
                    return true;
                }

                //REPLACE
                else if (action.equals(Cobalt.JSActionNavigationReplace)) {
                    JSONObject data = jsonObj.getJSONObject(Cobalt.kJSData);
                    String controller = data.getString(Cobalt.kJSController);
                    String page = data.getString(Cobalt.kJSPage);
                    boolean animated = data.optBoolean(Cobalt.kJSAnimated);
                    replace(controller, page, animated);
                    return true;
                }

                // UNHANDLED NAVIGATION
                else {
                    onUnhandledMessage(jsonObj);
                }
            }

            // PLUGIN
            else if (type.equals(Cobalt.JSTypePlugin)) {
                mPluginManager.onMessage(mContext, this, jsonObj);
            }

            // UI
            else if (type.equals(Cobalt.JSTypeUI)) {
                String control = jsonObj.getString(Cobalt.kJSUIControl);
                JSONObject data = jsonObj.getJSONObject(Cobalt.kJSData);
                String callback = jsonObj.optString(Cobalt.kJSCallback, null);

                return handleUi(control, data, callback);
            }

            // WEB LAYER
            else if (type.equals(Cobalt.JSTypeWebLayer)) {
                String action = jsonObj.getString(Cobalt.kJSAction);

                // SHOW
                if (action.equals(Cobalt.JSActionWebLayerShow)) {
                    final JSONObject data = jsonObj.getJSONObject(Cobalt.kJSData);

                    mHandler.post(new Runnable() {

                        @Override
                        public void run() {
                            showWebLayer(data);
                        }
                    });

                    return true;
                }

                // UNHANDLED WEB LAYER
                else {
                    onUnhandledMessage(jsonObj);
                }
            }

            // UNHANDLED TYPE
            else {
                onUnhandledMessage(jsonObj);
            }
        }

        // UNHANDLED MESSAGE
        else {
            onUnhandledMessage(jsonObj);
        }
    } catch (JSONException exception) {
        if (Cobalt.DEBUG)
            Log.e(Cobalt.TAG, TAG + " - onCobaltMessage: JSONException");
        exception.printStackTrace();
    } catch (NullPointerException exception) {
        if (Cobalt.DEBUG)
            Log.e(Cobalt.TAG, TAG + " - onCobaltMessage: NullPointerException");
        exception.printStackTrace();
    }

    return false;
}

From source file:fr.cobaltians.cobalt.fragments.CobaltFragment.java

private boolean handleUi(String control, JSONObject data, String callback) {
    try {/*  ww w.  ja  v  a 2s.c  o  m*/
        // PICKER
        switch (control) {
        case Cobalt.JSControlPicker:
            String type = data.getString(Cobalt.kJSType);

            // DATE
            if (type.equals(Cobalt.JSPickerDate)) {
                JSONObject date = data.optJSONObject(Cobalt.kJSDate);

                Calendar calendar = Calendar.getInstance();
                int year = calendar.get(Calendar.YEAR);
                int month = calendar.get(Calendar.MONTH);
                int day = calendar.get(Calendar.DAY_OF_MONTH);

                if (date != null && date.has(Cobalt.kJSYear) && date.has(Cobalt.kJSMonth)
                        && date.has(Cobalt.kJSDay)) {
                    year = date.getInt(Cobalt.kJSYear);
                    month = date.getInt(Cobalt.kJSMonth) - 1;
                    day = date.getInt(Cobalt.kJSDay);
                }

                JSONObject texts = data.optJSONObject(Cobalt.kJSTexts);
                String title = texts.optString(Cobalt.kJSTitle, null);
                //String delete = texts.optString(Cobalt.kJSDelete, null);
                String clear = texts.optString(Cobalt.kJSClear, null);
                String cancel = texts.optString(Cobalt.kJSCancel, null);
                String validate = texts.optString(Cobalt.kJSValidate, null);

                showDatePickerDialog(year, month, day, title, clear, cancel, validate, callback);

                return true;
            }

            break;
        case Cobalt.JSControlAlert:
            showAlertDialog(data, callback);
            return true;
        case Cobalt.JSControlToast:
            String message = data.getString(Cobalt.kJSMessage);
            Toast.makeText(mContext, message, Toast.LENGTH_SHORT).show();
            return true;
        default:
            break;
        }
    } catch (JSONException exception) {
        if (Cobalt.DEBUG)
            Log.e(Cobalt.TAG, TAG + " - handleUi: JSONException");
        exception.printStackTrace();
    }

    // UNHANDLED UI
    try {
        JSONObject jsonObj = new JSONObject();
        jsonObj.put(Cobalt.kJSType, Cobalt.JSTypeUI);
        jsonObj.put(Cobalt.kJSUIControl, control);
        jsonObj.put(Cobalt.kJSData, data);
        jsonObj.put(Cobalt.kJSCallback, callback);
        onUnhandledMessage(jsonObj);
    } catch (JSONException exception) {
        if (Cobalt.DEBUG)
            Log.e(Cobalt.TAG, TAG + " - handleUi: JSONException");
        exception.printStackTrace();
    }

    return false;
}

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
 *//* w ww.j a  v a  2s  .co 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 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.joyfulmongo.db.OpCmdAdd.java

@Override
public void onUpdate(String colname, JSONObject parseObject) {
    JSONArray a = mObj.optJSONArray(AddProps.objects.toString());
    JSONObject each = new JSONObject();
    each.put(CMD_EACH, a);//from  www.  jav  a 2s. com

    JSONObject addToSet = parseObject.optJSONObject(CMD_ADD_TO_SET);
    if (addToSet == null) {
        JSONObject field = new JSONObject();
        field.put(key, each);

        parseObject.remove(key);
        parseObject.put(CMD_ADD_TO_SET, field);
    } else {
        parseObject.remove(key);
        addToSet.put(key, each);
    }
}

From source file:com.sina.weibo.sdk_lib.openapi.models.Comment.java

public static Comment parse(JSONObject jsonObject) {
    if (null == jsonObject) {
        return null;
    }/*from  w w  w  . j a va2  s  .  c om*/

    Comment comment = new Comment();
    comment.created_at = jsonObject.optString("created_at");
    comment.id = jsonObject.optString("id");
    comment.text = jsonObject.optString("text");
    comment.source = jsonObject.optString("source");
    comment.user = User.parse(jsonObject.optJSONObject("user"));
    comment.mid = jsonObject.optString("mid");
    comment.idstr = jsonObject.optString("idstr");
    comment.status = Status.parse(jsonObject.optJSONObject("status"));
    comment.reply_comment = Comment.parse(jsonObject.optJSONObject("reply_comment"));

    return comment;
}

From source file:com.github.rnewson.couchdb.lucene.couchdb.DesignDocument.java

public DesignDocument(final JSONObject json) throws JSONException {
    super(json);//from  w w  w.j  ava 2s.c  o m
    if (!getId().startsWith("_design/")) {
        throw new IllegalArgumentException(json + " is not a design document");
    }
    fulltext = json.optJSONObject("fulltext");
}

From source file:com.citrus.sdk.payment.PaymentBill.java

public static PaymentBill fromJSON(String json) {
    PaymentBill paymentBill = null;/*from  ww w. java  2  s.  c  om*/

    JSONObject billObject = null;
    try {
        billObject = new JSONObject(json);
    } catch (JSONException e) {
        e.printStackTrace();
    }

    if (billObject != null) {
        Amount amount = null;
        String requestSignature = null;
        String merchantTransactionId = null; // TODO: Do the validation of the transaction id length
        String merchantAccessKey = null;
        String returnUrl = null;
        String notifyUrl = null;
        Map<String, String> customParametersMap = null;

        amount = Amount.fromJSONObject(billObject.optJSONObject("amount"));
        requestSignature = billObject.optString("requestSignature");
        merchantTransactionId = billObject.optString("merchantTxnId");
        merchantAccessKey = billObject.optString("merchantAccessKey");
        returnUrl = billObject.optString("returnUrl");
        notifyUrl = billObject.optString("notifyUrl");

        JSONObject customParamsObject = billObject.optJSONObject("customParameters");
        if (customParamsObject != null) {
            customParametersMap = new HashMap<>();
            Iterator<String> iter = customParamsObject.keys();
            while (iter.hasNext()) {
                String key = iter.next();
                String value = customParamsObject.optString(key);

                customParametersMap.put(key, value);
            }
        }

        if (amount != null && requestSignature != null && returnUrl != null && merchantAccessKey != null
                && merchantTransactionId != null) {

            paymentBill = new PaymentBill(amount, requestSignature, merchantTransactionId, merchantAccessKey,
                    returnUrl, notifyUrl, customParametersMap);
        }
    }

    return paymentBill;
}