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.Validation.java

public Validation(RapidHttpServlet rapidServlet, JSONObject jsonAction) throws Exception {
    // set the xml version
    super();//  w  w w . j a va2s  . c  om
    // 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 controls
        if (!"controls".equals(key) && !"passActions".equals(key) && !"failActions".equals(key))
            addProperty(key, jsonAction.get(key).toString());
    }
    // grab any controls
    JSONArray jsonControls = jsonAction.optJSONArray("controls");
    // if we had some
    if (jsonControls != null) {
        // instantiate our contols collection
        _controls = new ArrayList<String>();
        // loop the json Controls
        for (int i = 0; i < jsonControls.length(); i++) {
            // add into our collection
            _controls.add(jsonControls.getString(i));
        }
    }

    // grab any passActions
    JSONArray jsonPassActions = jsonAction.optJSONArray("passActions");
    // if we had some
    if (jsonPassActions != null) {
        // instantiate our pass actions collection
        _passActions = Control.getActions(rapidServlet, jsonPassActions);
    }

    // grab any failActions
    JSONArray jsonFailActions = jsonAction.optJSONArray("failActions");
    // if we had some
    if (jsonFailActions != null) {
        // instantiate our fail actions collection
        _failActions = Control.getActions(rapidServlet, jsonFailActions);
    }
}

From source file:io.s4.client.Handshake.java

private ClientConnection clientConnectCreate(byte[] v, ByteArrayIOChannel io, Socket sock, List<String> reason)
        throws IOException {

    try {//from   w w  w  .ja va  2s  .c  o m
        JSONObject cInfo = new JSONObject(new String(v));

        String s = cInfo.optString("uuid", "");
        if (s.isEmpty()) {
            logger.error("missing client identifier during handshake.");
            reason.add("missing UUID");
            return null;
        }

        UUID u = UUID.fromString(s);

        logger.info("connecting to client " + u);

        s = cInfo.optString("readMode", "Private");
        ClientReadMode rmode = ClientReadMode.fromString(s);
        if (rmode == null) {
            logger.error(u + ": unknown readMode " + s);
            reason.add("unknown readMode " + s);
            return null;

        }

        s = cInfo.optString("writeMode", "Enabled");
        ClientWriteMode wmode = ClientWriteMode.fromString(s);
        if (wmode == null) {
            logger.error(u + ": unknown writeMode " + s);
            reason.add("unknown writeMode " + s);
            return null;
        }

        logger.info(u + " read=" + rmode + " write=" + wmode);

        if (rmode == ClientReadMode.None && wmode == ClientWriteMode.Disabled) {
            // client cannot disable read AND write...
            logger.error("client neither reads nor writes.");
            reason.add("read and write disabled");

            return null;
        }

        ClientConnection conn = new ClientConnection(clientStub, sock, u, rmode, wmode);

        if (rmode == ClientReadMode.Select) {
            JSONArray incl = cInfo.optJSONArray("readInclude");
            JSONArray excl = cInfo.optJSONArray("readExclude");

            if (incl == null && excl == null) {
                logger.error(u + ": missing stream selection information");
                reason.add("missing readInclude and readExclude");
                return null;
            }

            if (incl != null) {
                List<String> streams = new ArrayList<String>(incl.length());
                for (int i = 0; i < incl.length(); ++i)
                    streams.add(incl.getString(i));

                conn.includeStreams(streams);
            }

            if (excl != null) {
                List<String> streams = new ArrayList<String>(excl.length());
                for (int i = 0; i < excl.length(); ++i)
                    streams.add(excl.getString(i));

                conn.excludeStreams(streams);
            }

        }

        return conn;

    } catch (JSONException e) {
        logger.error("malformed JSON from client during handshake", e);
        reason.add("malformed JSON");

    } catch (NumberFormatException e) {
        logger.error("received malformed UUID", e);
        reason.add("malformed UUID");

    } catch (IllegalArgumentException e) {
        logger.error("received malformed UUID", e);
        reason.add("malformed UUID");
    }

    return null;
}

From source file:edu.stanford.mobisocial.dungbeetle.feed.objects.DeleteObj.java

public void handleDirectMessage(Context context, Contact from, JSONObject json) {
    DBHelper dbh = DBHelper.getGlobal(context);
    try {/*from  ww w . j  a va2  s  .co m*/
        long[] hashes;
        if (json.has(HASHES)) {
            JSONArray jsonHashes = json.optJSONArray(HASHES);
            hashes = new long[jsonHashes.length()];
            for (int i = 0; i < jsonHashes.length(); i++) {
                hashes[i] = jsonHashes.optLong(i);
            }
        } else if (json.has(HASH)) {
            hashes = new long[] { json.optLong(HASH) };
        } else {
            Log.d(TAG, "DeleteObj with no hashes!");
            return;
        }
        dbh.markOrDeleteObjs(hashes);
    } finally {
        dbh.close();
    }
}

From source file:edu.stanford.mobisocial.dungbeetle.feed.objects.DeleteObj.java

@Override
public void afterDbInsertion(Context context, DbObj obj) {
    Uri feedUri = obj.getContainingFeed().getUri();
    DBHelper dbh = DBHelper.getGlobal(context);
    try {//from  www .j  ava 2 s. c  o m
        JSONObject json = obj.getJson();
        long[] hashes;
        if (json.optJSONArray(HASHES) != null) {
            JSONArray jsonHashes = json.optJSONArray(HASHES);
            hashes = new long[jsonHashes.length()];
            for (int i = 0; i < jsonHashes.length(); i++) {
                hashes[i] = jsonHashes.optLong(i);
            }
        } else if (json.has(HASH)) {
            hashes = new long[] { json.optLong(HASH) };
        } else {
            Log.d(TAG, "DeleteObj with no hashes!");
            return;
        }
        Log.d(TAG, "marking or deleting " + hashes.length);
        dbh.markOrDeleteFeedObjs(feedUri, hashes, (json.has(FORCE) && json.optBoolean(FORCE)));
    } finally {
        dbh.close();
    }
}

From source file:org.official.json.JSONML.java

/**
 * Reverse the JSONML transformation, making an XML text from a JSONObject.
 * The JSONObject must contain a "tagName" property. If it has children,
 * then it must have a "childNodes" property containing an array of objects.
 * The other properties are attributes with string values.
 * @param jo A JSONObject./*from ww w .  j a v a 2 s  . c o  m*/
 * @return An XML string.
 * @throws JSONException
 */
public static String toString(JSONObject jo) throws JSONException {
    StringBuilder sb = new StringBuilder();
    int i;
    JSONArray ja;
    String key;
    Iterator<String> keys;
    int length;
    Object object;
    String tagName;
    String value;

    //Emit <tagName

    tagName = jo.optString("tagName");
    if (tagName == null) {
        return XML.escape(jo.toString());
    }
    XML.noSpace(tagName);
    tagName = XML.escape(tagName);
    sb.append('<');
    sb.append(tagName);

    //Emit the attributes

    keys = jo.keys();
    while (keys.hasNext()) {
        key = keys.next();
        if (!"tagName".equals(key) && !"childNodes".equals(key)) {
            XML.noSpace(key);
            value = jo.optString(key);
            if (value != null) {
                sb.append(' ');
                sb.append(XML.escape(key));
                sb.append('=');
                sb.append('"');
                sb.append(XML.escape(value));
                sb.append('"');
            }
        }
    }

    //Emit content in body

    ja = jo.optJSONArray("childNodes");
    if (ja == null) {
        sb.append('/');
        sb.append('>');
    } else {
        sb.append('>');
        length = ja.length();
        for (i = 0; i < length; i += 1) {
            object = ja.get(i);
            if (object != null) {
                if (object instanceof String) {
                    sb.append(XML.escape(object.toString()));
                } else if (object instanceof JSONObject) {
                    sb.append(toString((JSONObject) object));
                } else if (object instanceof JSONArray) {
                    sb.append(toString((JSONArray) object));
                } else {
                    sb.append(object.toString());
                }
            }
        }
        sb.append('<');
        sb.append('/');
        sb.append(tagName);
        sb.append('>');
    }
    return sb.toString();
}

From source file:gov.sfmta.sfpark.DetailViewActivity.java

private void parseHours() throws JSONException {
    Log.v(TAG, "parsing hours");

    beg = null;//from  w  ww .j a v  a 2 s . co m
    end = null;
    from = null;
    to = null;

    JSONObject ophrs = annotation.allGarageData.optJSONObject("OPHRS");

    if (ophrs == null) {
        return;
    }

    listLayout.addView(headerText(getString(R.string.hours)));

    JSONArray opsArray = ophrs.optJSONArray("OPS");

    // its not an array, just one object
    if (opsArray == null) {
        JSONObject opsObject = ophrs.optJSONObject("OPS");

        // want null if fail not 'empty string' ?
        beg = opsObject.optString("BEG", null);
        end = opsObject.optString("END", null);
        from = opsObject.optString("FROM", null);
        to = opsObject.optString("TO", null);

        if (end != null) {
            end = "- " + end;
        } else {
            end = "";
        }

        if (to != null) {
            to = fixDay(to);
            to = "- " + to;
        } else {
            to = "";
        }

        if (beg == null)
            beg = "";
        if (from == null)
            from = "";

        row = fixDay(from) + " " + to + ": " + beg + " " + end;

        listLayout.addView(normalText(row));

        return;
    }

    int hoursRows = opsArray.length();
    for (int i = 0; i < hoursRows; i++) {
        JSONObject opsObject = opsArray.getJSONObject(i);

        // want null if fail not 'empty string' ?
        beg = opsObject.optString("BEG", null);
        end = opsObject.optString("END", null);
        from = opsObject.optString("FROM", null);
        to = opsObject.optString("TO", null);

        if (to != null) {
            row = fixDay(from) + " - " + fixDay(to) + ": " + beg + " - " + end;
        } else {
            row = fixDay(from) + ": " + beg + " - " + end;
        }

        listLayout.addView(normalText(row));
        hr();
    }

}

From source file:gov.sfmta.sfpark.DetailViewActivity.java

private void parseRates() throws JSONException {
    Log.v(TAG, "parsing rates");

    beg = null;/*from w  w  w.  j a  v  a2 s  .c o m*/
    end = null;
    from = null;
    to = null;

    JSONObject rates = annotation.allGarageData.optJSONObject("RATES");

    displayedRates = false;

    if (rates == null) {
        return;
    }

    JSONArray rsArray = rates.optJSONArray("RS");

    if (rsArray == null) { //its not an array, just one object
        JSONObject rsObject = rates.optJSONObject("RS");

        // want null if fail not 'empty string' ?
        beg = rsObject.optString("BEG", null);
        end = rsObject.optString("END", null);
        rate = rsObject.optString("RATE", null);
        rq = rsObject.optString("RQ", null);

        float phr = Float.parseFloat(rate);

        if (beg != null) {
            listLayout.addView(headerText(getString(R.string.rates)));
            displayedRates = true;

            row = beg + " - " + end;

            if (phr == 0) {
                row2 = rq;
            } else {
                row2 = String.format("$%.2f hr", phr);
            }

            row = row + "  " + row2;

            if (annotation.inThisBucketBegin(beg, end)) {
                listLayout.addView(highlightText(row));
            } else {
                listLayout.addView(normalText(row));
            }
        }
        return;
    }

    int rsc = rsArray.length();

    for (int i = 0; i < rsc; i++) {
        JSONObject rsObject = rsArray.getJSONObject(i);

        // want null if fail not 'empty string' ?
        beg = rsObject.optString("BEG", null);
        end = rsObject.optString("END", null);
        rate = rsObject.optString("RATE", null);
        rq = rsObject.optString("RQ", null);

        float phr = Float.parseFloat(rate);

        if (beg != null) {
            if (!displayedRates) {
                listLayout.addView(headerText(getString(R.string.rates)));
                displayedRates = true;
            }

            row = beg + " - " + end;

            if (phr == 0) {
                row2 = rq;
            } else {
                row2 = String.format("$%.2f hr", phr);
            }

            row = row + "  " + row2;

            if (annotation.inThisBucketBegin(beg, end)) {
                listLayout.addView(highlightText(row));
            } else {
                listLayout.addView(normalText(row));
            }

            hr();
        }
    }
}

From source file:gov.sfmta.sfpark.DetailViewActivity.java

private void parseInfo() throws JSONException {
    Log.v(TAG, "parsing info");

    beg = null;//from ww  w. j  a v  a 2 s  .co  m
    end = null;
    from = null;
    to = null;

    boolean displayedInfo = false;

    JSONObject rates = annotation.allGarageData.optJSONObject("RATES");

    if (rates == null) {
        return;
    }

    JSONArray rsArray = rates.optJSONArray("RS");

    // just return if it is not an array
    if (rsArray == null) {
        return;
    }

    int rsc = rsArray.length();

    for (int i = 0; i < rsc; i++) {
        JSONObject rsObject = rsArray.getJSONObject(i);

        desc = rsObject.optString("DESC", null);
        rate = rsObject.optString("RATE", null);
        rq = rsObject.optString("RQ", null);
        rr = rsObject.optString("RR", null);

        float phr = Float.parseFloat(rate);

        if (desc != null) {
            if (!displayedInfo) {
                if (displayedRates) {
                    listLayout.addView(headerText(getString(R.string.info)));
                } else {
                    listLayout.addView(headerText(getString(R.string.rates)));
                }
                displayedInfo = true;
            }

            row = desc + ":";
            listLayout.addView(normalText(row));

            if (phr == 0) {
                listLayout.addView(normalText(rq));
            } else {
                if (rq != null) {
                    row = String.format("$%.2f ", phr) + rq;
                } else {
                    row = String.format("$%.2f hr", phr);
                }

                listLayout.addView(normalText(row));
            }

            if (rr != null) {
                //check for semicolon, insert new line
                String rrn = rr.replace(";", "\n");
                listLayout.addView(normalText(rrn));
            }
            hr();
        }
    }
}

From source file:de.luhmer.owncloudnewsreader.reader.GoogleReaderApi.GoogleReaderMethods.java

@SuppressWarnings("unused")
public static ArrayList<RssFile> getFeeds(String _USERNAME, String _PASSWORD, String _TAG_LABEL) {
    Log.d("mygr", "METHOD: getUnreadFeeds()");

    ArrayList<RssFile> items = new ArrayList<RssFile>();

    String returnString = null;/*from   ww  w .j  a  v  a 2 s  .  co  m*/

    /*
    String _TAG_LABEL = null;
    try {
       //_TAG_LABEL = "stream/contents/user/" + AuthenticationManager.getGoogleUserID(_USERNAME, _PASSWORD) + "/state/com.google/reading-list?n=1000&r=n&xt=user/-/state/com.google/read";
       _TAG_LABEL = "stream/contents/user/-/state/com.google/reading-list?n=1000&r=n&xt=user/-/state/com.google/read";
    }catch(Exception e){
       e.printStackTrace();
    }*/

    try {

        HttpClient client = new DefaultHttpClient();
        HttpGet request = new HttpGet(GoogleReaderConstants._API_URL + _TAG_LABEL);
        request.addHeader("Authorization", GoogleReaderConstants._AUTHPARAMS
                + AuthenticationManager.getGoogleAuthKey(_USERNAME, _PASSWORD));

        HttpResponse response = client.execute(request);

        returnString = HttpHelper.request(response);

        try {
            JSONObject jObj = new JSONObject(returnString);
            JSONArray jItems = (JSONArray) jObj.get("items");
            for (int i = 0; i < jItems.length(); i++) {
                JSONObject jItem = jItems.getJSONObject(i);

                try {
                    String streamID = jItem.optJSONObject("origin").optString("streamId");
                    String feedTitel = jItem.getString("title");
                    String feedID = jItem.optString("id");
                    String content = "";
                    String link = "";
                    String timestamp = jItem.optString("published");

                    JSONObject jSummary = jItem.optJSONObject("summary");
                    JSONObject jContent = jItem.optJSONObject("content");

                    //JSONArray jCategories

                    if (jSummary != null)
                        content = (String) jItem.getJSONObject("summary").get("content");

                    if (jContent != null)
                        content = (String) jItem.getJSONObject("content").get("content");

                    //if(jItem.has("origin"));
                    //   link = (String) jItem.getJSONObject("origin").get("htmlUrl");

                    if (jItem.has("alternate"))
                        ;
                    link = (String) jItem.optJSONArray("alternate").getJSONObject(0).getString("href");

                    JSONArray jCategories = jItem.optJSONArray("categories");
                    List<String> categories = new ArrayList<String>();
                    if (jCategories != null) {
                        for (int t = 0; t < jCategories.length(); t++)
                            categories.add((String) jCategories.get(t));
                    }

                    Boolean starred = false;
                    Boolean read = false;

                    if (_TAG_LABEL.equals(Constants._TAG_LABEL_STARRED)) {
                        starred = true;
                        read = true;
                    }

                    content = content.replaceAll("<img[^>]*feedsportal.com.*>", "");
                    content = content
                            .replaceAll("<img[^>]*statisches.auslieferung.commindo-media-ressourcen.de.*>", "");
                    content = content.replaceAll("<img[^>]*auslieferung.commindo-media-ressourcen.de.*>", "");
                    content = content.replaceAll("<img[^>]*rss.buysellads.com.*>", "");

                    //content = (String) jItem.getJSONObject("content").get("content");
                    /*
                    RssFile sItem = new  RssFile(0, feedTitel, link, content, read, 0, feedID, categories, streamID, new Date(Long.parseLong(timestamp) * 1000), starred, null, null);//TODO implement this here again
                    items.add(sItem);*/
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
            //Log.d("HI", jObj.toString());
        } catch (JSONException e) {
            e.printStackTrace();
        }

        /*
        Pattern pattern = Pattern.compile("\"alternate\":\\[\\{\"href\":\"(.*?)\",");
        Matcher matcher = pattern.matcher(returnString);
                
        ArrayList<String> resultList = new ArrayList<String>();
                
        while (matcher.find())
           resultList.add(matcher.group(1));
                
        String[] ret = new String[resultList.size()];
        resultList.toArray(ret);*/
        //return ret;

    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
    return items;
}

From source file:org.uiautomation.ios.context.BaseWebInspector.java

public List<Cookie> getCookies() {

    List<Cookie> res = new ArrayList<Cookie>();
    JSONObject o = sendCommand(Page.getCookies());
    JSONArray cookies = o.optJSONArray("cookies");
    if (cookies != null) {
        for (int i = 0; i < cookies.length(); i++) {
            JSONObject cookie = cookies.optJSONObject(i);
            String name = cookie.optString("name");
            String value = cookie.optString("value");
            String domain = cookie.optString("domain");
            String path = cookie.optString("path");
            Date expiry = new Date(cookie.optLong("expires"));
            boolean isSecure = cookie.optBoolean("secure");
            Cookie c = new Cookie(name, value, domain, path, expiry, isSecure);
            res.add(c);/* w ww . j  a va2 s. c o  m*/
        }
        return res;
    } else {
        // TODO
    }
    return null;
}