Example usage for org.json JSONObject optJSONArray

List of usage examples for org.json JSONObject optJSONArray

Introduction

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

Prototype

public JSONArray optJSONArray(String key) 

Source Link

Document

Get an optional JSONArray associated with a key.

Usage

From source file:com.rapid.actions.Webservice.java

public Webservice(RapidHttpServlet rapidServlet, JSONObject jsonAction) throws Exception {
    // set the xml version
    super();/*w w  w. j  a v  a2 s  .  c  o  m*/

    // save all key/values from the json into the properties 
    for (String key : JSONObject.getNames(jsonAction)) {
        // add all json properties to our properties, except for query
        if (!"request".equals(key) && !"root".equals(key) && !"showLoading".equals(key)
                && !"successActions".equals(key) && !"errorActions".equals(key))
            addProperty(key, jsonAction.get(key).toString());
    }

    // try and build the query object
    JSONObject jsonQuery = jsonAction.optJSONObject("request");

    // check we got one
    if (jsonQuery != null) {
        // get the parameters                  
        ArrayList<Parameter> inputs = getParameters(jsonQuery.optJSONArray("inputs"));
        String type = jsonQuery.optString("type");
        String url = jsonQuery.optString("url");
        String action = jsonQuery.optString("action");
        String body = jsonQuery.optString("body");
        String transform = jsonQuery.optString("transform");
        String root = jsonQuery.optString("root");
        ArrayList<Parameter> outputs = getParameters(jsonQuery.optJSONArray("outputs"));
        // make the object
        _request = new Request(inputs, type, url, action, body, transform, root, outputs);
    }

    // look for showLoading
    _showLoading = jsonAction.optBoolean("showLoading");

    // grab any successActions
    JSONArray jsonSuccessActions = jsonAction.optJSONArray("successActions");
    // if we had some
    if (jsonSuccessActions != null) {
        // instantiate our success actions collection
        _successActions = Control.getActions(rapidServlet, jsonSuccessActions);
    }

    // grab any errorActions
    JSONArray jsonErrorActions = jsonAction.optJSONArray("errorActions");
    // if we had some
    if (jsonErrorActions != null) {
        // instantiate our error actions collection
        _errorActions = Control.getActions(rapidServlet, jsonErrorActions);
    }

}

From source file:com.rapid.actions.Webservice.java

@Override
public JSONObject doAction(RapidRequest rapidRequest, JSONObject jsonAction) throws Exception {

    _logger.trace("Webservice action : " + jsonAction);

    // get the application
    Application application = rapidRequest.getApplication();

    // get the page
    Page page = rapidRequest.getPage();//w  ww  . j  a  v  a2s  . c o  m

    // get the webservice action call sequence
    int sequence = jsonAction.optInt("sequence", 1);

    // placeholder for the object we're about to return
    JSONObject jsonData = null;

    // only proceed if there is a request and application and page
    if (_request != null && application != null && page != null) {

        // get any json inputs 
        JSONArray jsonInputs = jsonAction.optJSONArray("inputs");

        // placeholder for the action cache
        ActionCache actionCache = rapidRequest.getRapidServlet().getActionCache();

        // if an action cache was found
        if (actionCache != null) {

            // log that we found action cache
            _logger.debug("Webservice action cache found");

            // attempt to fetch data from the cache
            jsonData = actionCache.get(application.getId(), getId(), jsonInputs.toString());

        }

        // if there is either no cache or we got no data
        if (jsonData == null) {

            // get the body into a string
            String body = _request.getBody().trim();
            // remove prolog if present
            if (body.indexOf("\"?>") > 0)
                body = body.substring(body.indexOf("\"?>") + 3).trim();
            // check number of parameters
            int pCount = Strings.occurrences(body, "?");
            // throw error if incorrect
            if (pCount != jsonInputs.length())
                throw new Exception("Request has " + pCount + " parameter" + (pCount == 1 ? "" : "s") + ", "
                        + jsonInputs.length() + " provided");
            // retain the current position
            int pos = body.indexOf("?");
            // keep track of the index of the ?
            int index = 0;
            // if there are any question marks
            if (pos > 0 && jsonInputs.length() > index) {
                // loop, but check condition at the end
                do {
                    // get the input
                    JSONObject input = jsonInputs.getJSONObject(index);
                    // url escape the value
                    String value = XML.escape(input.optString("value"));
                    // replace the ? with the input value
                    body = body.substring(0, pos) + value + body.substring(pos + 1);
                    // look for the next question mark
                    pos = body.indexOf("?", pos + 1);
                    // inc the index for the next round
                    index++;
                    // stop looping if no more ?
                } while (pos > 0);
            }

            // retrieve the action
            String action = _request.getAction();
            // create a placeholder for the request url
            URL url = null;
            // get the request url
            String requestURL = _request.getUrl();

            // if we got one
            if (requestURL != null) {

                // if the given request url starts with http use it as is, otherwise use the soa servlet
                if (_request.getUrl().startsWith("http")) {
                    // trim it
                    requestURL = requestURL.trim();
                    // insert any parameters
                    requestURL = application
                            .insertParameters(rapidRequest.getRapidServlet().getServletContext(), requestURL);
                    // use the url 
                    url = new URL(requestURL);
                } else {
                    // get our request
                    HttpServletRequest httpRequest = rapidRequest.getRequest();
                    // make a url for the soa servlet
                    url = new URL(httpRequest.getScheme(), httpRequest.getServerName(),
                            httpRequest.getServerPort(), httpRequest.getContextPath() + "/soa");
                    // check whether we have any id / version seperators
                    String[] actionParts = action.split("/");
                    // add this app and version if none
                    if (actionParts.length < 2)
                        action = application.getId() + "/" + application.getVersion() + "/" + action;
                }

                // establish the connection
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();

                // if we are requesting from ourself
                if (url.getPath().startsWith(rapidRequest.getRequest().getContextPath())) {
                    // get our session id
                    String sessionId = rapidRequest.getRequest().getSession().getId();
                    // add it to the call for internal authentication
                    connection.setRequestProperty("Cookie", "JSESSIONID=" + sessionId);
                }

                // set the content type and action header accordingly
                if ("SOAP".equals(_request.getType())) {
                    connection.setRequestProperty("Content-Type", "text/xml");
                    connection.setRequestProperty("SOAPAction", action);
                } else if ("JSON".equals(_request.getType())) {
                    connection.setRequestProperty("Content-Type", "application/json");
                    if (action.length() > 0)
                        connection.setRequestProperty("Action", action);
                } else if ("XML".equals(_request.getType())) {
                    connection.setRequestProperty("Content-Type", "text/xml");
                    if (action.length() > 0)
                        connection.setRequestProperty("Action", action);
                }

                // if a body has been specified
                if (body.length() > 0) {

                    // Triggers POST.
                    connection.setDoOutput(true);

                    // get the output stream from the connection into which we write the request
                    OutputStream output = connection.getOutputStream();

                    // write the processed body string into the request output stream
                    output.write(body.getBytes("UTF8"));
                }

                // check the response code
                int responseCode = connection.getResponseCode();

                // read input stream if all ok, otherwise something meaningful should be in error stream
                if (responseCode == 200) {

                    // get the input stream
                    InputStream response = connection.getInputStream();
                    // prepare an soaData object
                    SOAData soaData = null;

                    // read the response accordingly
                    if ("JSON".equals(_request.getType())) {
                        SOAJSONReader jsonReader = new SOAJSONReader();
                        String jsonResponse = Strings.getString(response);
                        soaData = jsonReader.read(jsonResponse);
                    } else {
                        SOAXMLReader xmlReader = new SOAXMLReader(_request.getRoot());
                        soaData = xmlReader.read(response);
                    }

                    SOADataWriter jsonWriter = new SOARapidWriter(soaData);

                    String jsonString = jsonWriter.write();

                    jsonData = new JSONObject(jsonString);

                    if (actionCache != null)
                        actionCache.put(application.getId(), getId(), jsonInputs.toString(), jsonData);

                    response.close();

                } else {

                    InputStream response = connection.getErrorStream();

                    String errorMessage = null;

                    if ("SOAP".equals(_request.getType())) {

                        String responseXML = Strings.getString(response);

                        errorMessage = XML.getElementValue(responseXML, "faultcode");

                    }

                    if (errorMessage == null) {

                        BufferedReader rd = new BufferedReader(new InputStreamReader(response));

                        errorMessage = rd.readLine();

                        rd.close();

                    }

                    // log the error
                    _logger.error(errorMessage);

                    // only if there is no application cache show the error, otherwise it sends an empty response
                    if (actionCache == null) {

                        throw new JSONException(
                                " response code " + responseCode + " from server : " + errorMessage);

                    } else {

                        _logger.debug("Error not shown to user due to cache : " + errorMessage);

                    }

                }

                connection.disconnect();

            } // request url != null

        } // jsonData == null

    } // got app and page

    // if the jsonData is still null make an empty one
    if (jsonData == null)
        jsonData = new JSONObject();

    // add the sequence
    jsonData.put("sequence", sequence);

    // return the object
    return jsonData;

}

From source file:com.basetechnology.s0.agentserver.field.MultiChoiceField.java

public static Field fromJson(SymbolTable symbolTable, JSONObject fieldJson) {
    String type = fieldJson.optString("type");
    if (type == null || !type.equals("multi_choice_field"))
        return null;
    String name = fieldJson.has("name") ? fieldJson.optString("name") : null;
    String label = fieldJson.has("label") ? fieldJson.optString("label") : null;
    String description = fieldJson.has("description") ? fieldJson.optString("description") : null;
    String defaultValue = fieldJson.has("default_value") ? fieldJson.optString("default_value") : null;
    List<String> choices = new ArrayList<String>();
    if (fieldJson.has("choices")) {
        JSONArray choicesJson = fieldJson.optJSONArray("choices");
        int n = choicesJson.length();
        for (int i = 0; i < n; i++)
            choices.add(choicesJson.optString(i));
    }// w  ww . j  a  v a2s .c o m
    int nominalWidth = fieldJson.has("nominal_width") ? fieldJson.optInt("nominal_width") : 0;
    String compute = fieldJson.has("compute") ? fieldJson.optString("compute") : null;
    return new MultiChoiceField(symbolTable, name, label, description, defaultValue, choices, nominalWidth,
            compute);
}

From source file:com.example.protocol.STATUSES.java

public void fromJson(JSONObject jsonObject) throws JSONException {
    if (null == jsonObject) {
        return;//from w w  w. j a  v a2 s .  c  o m
    }

    JSONArray subItemArray;

    this.comments_count = jsonObject.optInt("comments_count");

    this.text = jsonObject.optString("text");

    this.in_reply_to_screen_name = jsonObject.optString("in_reply_to_screen_name");

    this.truncated = jsonObject.optBoolean("truncated");

    this.bmiddle_pic = jsonObject.optString("bmiddle_pic");

    this.thumbnail_pic = jsonObject.optString("thumbnail_pic");

    this.source = jsonObject.optString("source");

    this.favorited = jsonObject.optBoolean("favorited");

    this.original_pic = jsonObject.optString("original_pic");

    this.in_reply_to_status_id = jsonObject.optString("in_reply_to_status_id");

    this.reposts_count = jsonObject.optInt("reposts_count");

    this.created_at = jsonObject.optString("created_at");

    this.in_reply_to_user_id = jsonObject.optString("in_reply_to_user_id");

    subItemArray = jsonObject.optJSONArray("annotations");
    if (null != subItemArray) {
        for (int i = 0; i < subItemArray.length(); i++) {
            String subItemObject = subItemArray.optString(i);
            String subItem = subItemObject;
            this.annotations.add(subItem);
        }
    }

    this.mid = jsonObject.optString("mid");
    USER user = new USER();
    user.fromJson(jsonObject.optJSONObject("user"));
    this.user = user;
    return;
}

From source file:com.vk.sdkweb.api.model.VKApiPost.java

/**
 * Fills a Post instance from JSONObject.
 *///from ww w .  j a va2  s  .com
public VKApiPost parse(JSONObject source) throws JSONException {
    id = source.optInt("id");
    to_id = source.optInt("to_id");
    from_id = source.optInt("from_id");
    date = source.optLong("date");
    text = source.optString("text");
    reply_owner_id = source.optInt("reply_owner_id");
    reply_post_id = source.optInt("reply_post_id");
    friends_only = ParseUtils.parseBoolean(source, "friends_only");
    JSONObject comments = source.optJSONObject("comments");
    if (comments != null) {
        comments_count = comments.optInt("count");
        can_post_comment = ParseUtils.parseBoolean(comments, "can_post");
    }
    JSONObject likes = source.optJSONObject("likes");
    if (likes != null) {
        likes_count = likes.optInt("count");
        user_likes = ParseUtils.parseBoolean(likes, "user_likes");
        can_like = ParseUtils.parseBoolean(likes, "can_like");
        can_publish = ParseUtils.parseBoolean(likes, "can_publish");
    }
    JSONObject reposts = source.optJSONObject("reposts");
    if (reposts != null) {
        reposts_count = reposts.optInt("count");
        user_reposted = ParseUtils.parseBoolean(reposts, "user_reposted");
    }
    post_type = source.optString("post_type");
    attachments.fill(source.optJSONArray("attachments"));
    JSONObject geo = source.optJSONObject("geo");
    if (geo != null) {
        this.geo = new VKApiPlace().parse(geo);
    }
    signer_id = source.optInt("signer_id");
    copy_history = new VKList<VKApiPost>(source.optJSONArray("copy_history"), VKApiPost.class);
    return this;
}

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

private static Map<Integer, Set<Integer>> parseJSONDefinition(JSONObject definition) {
    JSONArray itemsArray = definition.optJSONArray("items");
    if (itemsArray.length() == 0) {
        return null;
    }/*from   ww w .j a v a  2 s  .  co  m*/

    Map<Integer, Set<Integer>> items = new HashMap<>();
    for (int i = 0; i < itemsArray.length(); i++) {
        JSONObject item = itemsArray.optJSONObject(i);
        if (item == null) {
            continue;
        }
        int code = item.optInt("code");
        if (code == 0) {
            continue;
        }
        Set<Integer> subcodes = null;
        JSONArray subcodesArray = item.optJSONArray("subcodes");
        if (subcodesArray != null && subcodesArray.length() > 0) {
            subcodes = new HashSet<>();
            for (int j = 0; j < subcodesArray.length(); j++) {
                int subCode = subcodesArray.optInt(j);
                if (subCode != 0) {
                    subcodes.add(subCode);
                }
            }
        }
        items.put(code, subcodes);
    }
    return items;
}

From source file:com.chaosinmotion.securechat.network.SCNetwork.java

private synchronized void sendRequest(final Request request) {
    callQueue.add(request);/*from ww  w .j  a  va 2s  .  c  om*/

    // If not in background, spin the spinner
    if (request.caller instanceof WaitSpinner) {
        ((WaitSpinner) request.caller).startWaitSpinner();
        request.waitFlag = true;
    }

    request.taskFuture = ThreadPool.get().enqueueAsync(new Runnable() {
        @Override
        public void run() {
            try {
                HttpURLConnection conn = requestWith(request);

                conn.connect();
                Map<String, List<String>> headers = conn.getHeaderFields();
                List<String> clist = headers.get("Set-Cookie");
                if (clist != null) {
                    for (String cookie : clist) {
                        cookies.getCookieStore().add(null, HttpCookie.parse(cookie).get(0));
                    }
                }

                InputStream is = conn.getInputStream();
                JSONObject d = parseResult(is);
                conn.disconnect();

                final Response response = new Response();
                response.serverCode = conn.getResponseCode();
                if (d != null) {
                    response.success = d.optBoolean("success");
                    response.error = d.optInt("error");
                    response.errorMessage = d.optString("message");
                    response.exceptionStack = d.optJSONArray("exception");
                    response.data = d.optJSONObject("data");
                }

                ThreadPool.get().enqueueMain(new Runnable() {
                    @Override
                    public void run() {
                        if (request.waitFlag && ((request.caller instanceof WaitSpinner))) {
                            ((WaitSpinner) request.caller).stopWaitSpinner();
                            request.waitFlag = false;
                        }
                        callQueue.remove(request);
                        handleResponse(response, request);
                    }
                });
            } catch (Exception ex) {
                /*
                 *  This happens if there is a connection error.
                 */
                ThreadPool.get().enqueueMain(new Runnable() {
                    @Override
                    public void run() {
                        if (request.waitFlag && ((request.caller instanceof WaitSpinner))) {
                            ((WaitSpinner) request.caller).stopWaitSpinner();
                            request.waitFlag = false;
                        }
                        callQueue.remove(request);
                        handleIOError(request);
                    }
                });
            }
        }
    });
}

From source file:jfabrix101.billing.BillingSecurity.java

/**
 * Verifies that the data was signed with the given signature, and returns
 * the list of verified purchases. The data is in JSON format and contains
 * a nonce (number used once) that we generated and that was signed
 * (as part of the whole data string) with a private key. The data also
 * contains the {@link PurchaseState} and product ID of the purchase.
 * In the general case, there can be an array of purchase transactions
 * because there may be delays in processing the purchase on the backend
 * and then several purchases can be batched together.
 * @param signedData the signed JSON string (signed, not encrypted)
 * @param signature the signature for the data, signed with the private key
 *///from w  w  w. j a v  a  2  s. com
public static ArrayList<VerifiedPurchase> verifyPurchase(Context context, String signedData, String signature) {
    if (signedData == null) {
        Log.e(TAG, "data is null");
        return null;
    }
    if (BillingConsts.DEBUG) {
        Log.i(TAG, "signedData: " + signedData);
    }
    boolean verified = false;
    if (!TextUtils.isEmpty(signature)) {
        /**
         * Compute your public key (that you got from the Android Market publisher site).
         *
         * Instead of just storing the entire literal string here embedded in the
         * program,  construct the key at runtime from pieces or
         * use bit manipulation (for example, XOR with some other string) to hide
         * the actual key.  The key itself is not secret information, but we don't
         * want to make it easy for an adversary to replace the public key with one
         * of their own and then fake messages from the server.
         *
         * Generally, encryption keys / passwords should only be kept in memory
         * long enough to perform the operation they need to perform.
         */

        SharedPreferences pref = context.getSharedPreferences("billingPK", 0);
        AESObfuscator obfuscator = AESObfuscator.getDefaultObfuscator(context);
        String publicKey = "";
        try {
            publicKey = obfuscator.unobfuscate(pref.getString("pk", ""));
        } catch (Exception e) {
            Log.e(TAG, "Error getting publicc key from repository");
            return null;
        }
        PublicKey key = BillingSecurity.generatePublicKey(publicKey);
        verified = BillingSecurity.verify(key, signedData, signature);
        if (!verified) {
            Log.w(TAG, "signature does not match data.");
            return null;
        }
    }

    JSONObject jObject;
    JSONArray jTransactionsArray = null;
    int numTransactions = 0;
    long nonce = 0L;
    try {
        jObject = new JSONObject(signedData);

        // The nonce might be null if the user backed out of the buy page.
        nonce = jObject.optLong("nonce");
        jTransactionsArray = jObject.optJSONArray("orders");
        if (jTransactionsArray != null) {
            numTransactions = jTransactionsArray.length();
        }
    } catch (JSONException e) {
        return null;
    }

    if (!BillingSecurity.isNonceKnown(nonce)) {
        Log.w(TAG, "Nonce not found: " + nonce);
        return null;
    }

    ArrayList<VerifiedPurchase> purchases = new ArrayList<VerifiedPurchase>();
    try {
        for (int i = 0; i < numTransactions; i++) {
            JSONObject jElement = jTransactionsArray.getJSONObject(i);
            int response = jElement.getInt("purchaseState");
            PurchaseState purchaseState = PurchaseState.valueOf(response);
            String productId = jElement.getString("productId");
            //String packageName = jElement.getString("packageName");
            long purchaseTime = jElement.getLong("purchaseTime");
            String orderId = jElement.optString("orderId", "");
            String notifyId = null;
            if (jElement.has("notificationId")) {
                notifyId = jElement.getString("notificationId");
            }
            String developerPayload = jElement.optString("developerPayload", null);

            // If the purchase state is PURCHASED, then we require a verified nonce.
            if (purchaseState == PurchaseState.PURCHASED && !verified) {
                continue;
            }
            purchases.add(new VerifiedPurchase(purchaseState, notifyId, productId, orderId, purchaseTime,
                    developerPayload));
        }
    } catch (JSONException e) {
        Log.e(TAG, "JSON exception: ", e);
        return null;
    }
    removeNonce(nonce);
    return purchases;
}

From source file:org.eclipse.orion.internal.server.servlets.xfer.TransferResourceDecorator.java

public void addAtributesFor(HttpServletRequest request, URI resource, JSONObject representation) {

    String servlet = request.getServletPath();
    if (!"/file".equals(servlet) && !"/workspace".equals(servlet))
        return;//from   w ww . j  a  va2s . com
    try {
        //don't add import/export directly on a workspace at this point
        if ("/file".equals(servlet))
            addTransferLinks(request, resource, representation);
        JSONArray children = representation.optJSONArray(ProtocolConstants.KEY_CHILDREN);
        if (children != null) {
            for (int i = 0; i < children.length(); i++) {
                JSONObject child = children.getJSONObject(i);
                if (child.getBoolean(ProtocolConstants.KEY_DIRECTORY)) {
                    addTransferLinks(request, resource, child);
                }
            }
        }
    } catch (Exception e) {
        //log and continue
        LogHelper.log(e);
    }
}

From source file:com.example.wcl.test_weiboshare.Status.java

public static Status parse(JSONObject jsonObject) {
    if (null == jsonObject) {
        return null;
    }/*from w  ww. java  2  s .  c om*/

    Status status = new Status();
    status.created_at = jsonObject.optString("created_at");
    status.id = jsonObject.optString("id");
    status.mid = jsonObject.optString("mid");
    status.idstr = jsonObject.optString("idstr");
    status.text = jsonObject.optString("text");
    status.source = jsonObject.optString("source");
    status.favorited = jsonObject.optBoolean("favorited", false);
    status.truncated = jsonObject.optBoolean("truncated", false);

    // Have NOT supported
    status.in_reply_to_status_id = jsonObject.optString("in_reply_to_status_id");
    status.in_reply_to_user_id = jsonObject.optString("in_reply_to_user_id");
    status.in_reply_to_screen_name = jsonObject.optString("in_reply_to_screen_name");

    status.thumbnail_pic = jsonObject.optString("thumbnail_pic");
    status.bmiddle_pic = jsonObject.optString("bmiddle_pic");
    status.original_pic = jsonObject.optString("original_pic");
    status.geo = Geo.parse(jsonObject.optJSONObject("geo"));
    status.user = User.parse(jsonObject.optJSONObject("user"));
    status.retweeted_status = Status.parse(jsonObject.optJSONObject("retweeted_status"));
    status.reposts_count = jsonObject.optInt("reposts_count");
    status.comments_count = jsonObject.optInt("comments_count");
    status.attitudes_count = jsonObject.optInt("attitudes_count");
    status.mlevel = jsonObject.optInt("mlevel", -1); // Have NOT supported
    status.visible = Visible.parse(jsonObject.optJSONObject("visible"));

    JSONArray picUrlsArray = jsonObject.optJSONArray("pic_urls");
    if (picUrlsArray != null && picUrlsArray.length() > 0) {
        int length = picUrlsArray.length();
        status.pic_urls = new ArrayList<String>(length);
        JSONObject tmpObject = null;
        for (int ix = 0; ix < length; ix++) {
            tmpObject = picUrlsArray.optJSONObject(ix);
            if (tmpObject != null) {
                status.pic_urls.add(tmpObject.optString("thumbnail_pic"));
            }
        }
    }

    //status.ad = jsonObject.optString("ad", "");

    return status;
}