Example usage for org.json JSONArray length

List of usage examples for org.json JSONArray length

Introduction

In this page you can find the example usage for org.json JSONArray length.

Prototype

public int length() 

Source Link

Document

Get the number of elements in the JSONArray, included nulls.

Usage

From source file:org.protorabbit.Config.java

static void processURIResources(int type, JSONObject bsjo, ITemplate temp, String baseURI)
        throws JSONException {

    List<ResourceURI> refs = null;
    refs = new ArrayList<ResourceURI>();

    if (bsjo.has("libs")) {

        JSONArray ja = bsjo.getJSONArray("libs");

        for (int j = 0; j < ja.length(); j++) {

            JSONObject so = ja.getJSONObject(j);
            String url = so.getString("url");
            if (url.startsWith("/") || url.startsWith("http")) {
                baseURI = "";
            }//  w  ww .j  av a2  s  .c  om
            ResourceURI ri = new ResourceURI(url, baseURI, type);
            if (so.has("id")) {
                ri.setId(so.getString("id"));
            }
            if (so.has("uaTest")) {
                ri.setUATest(so.getString("uaTest"));
            }
            if (so.has("test")) {
                ri.setTest(so.getString("test"));
            }
            if (so.has("defer")) {
                ri.setDefer(so.getBoolean("defer"));
            }
            if (so.has("combine")) {
                ri.setCombine(so.getBoolean("combine"));
            }
            if (so.has("uniqueURL")) {
                Boolean unique = so.getBoolean("uniqueURL");
                ri.setUniqueURL(unique);
            }
            refs.add(ri);
        }
    }
    Boolean combine = null;
    if (bsjo.has("combineResources")) {
        combine = bsjo.getBoolean("combineResources");
    }
    Boolean lgzip = null;
    if (bsjo.has("gzip")) {
        lgzip = bsjo.getBoolean("gzip");
    }

    if (type == ResourceURI.SCRIPT) {
        temp.setCombineScripts(combine);
        temp.setGzipScripts(lgzip);
        temp.setScripts(refs);
    } else if (type == ResourceURI.LINK) {
        temp.setGzipStyles(lgzip);
        temp.setStyles(refs);
        temp.setCombineStyles(combine);
    }
}

From source file:org.protorabbit.Config.java

public void registerTemplates(JSONArray templates, String baseURI) {

    for (int i = 0; i < templates.length(); i++) {
        try {//w  ww.  j  av  a  2 s .  c  o  m
            JSONObject t = templates.getJSONObject(i);
            String id = t.getString("id");
            ITemplate temp = new Template(id, baseURI, t, this);
            registerTemplates(temp, t, baseURI);
            tmap.put(id, temp);
            getLogger().info("Added template definition : " + temp.getId());

        } catch (JSONException e) {
            getLogger().log(Level.SEVERE, "Error parsing configuration.", e);
        }
    }
}

From source file:org.protorabbit.Config.java

@SuppressWarnings("unchecked")
private void registerTemplates(ITemplate temp, JSONObject t, String baseURI) {

    try {//from ww  w .j  a v  a 2  s  . c o m

        if (t.has("timeout")) {
            long templateTimeout = t.getLong("timeout");
            temp.setTimeout(templateTimeout);
        }

        boolean tgzip = false;

        if (!devMode) {
            tgzip = gzip;
        }

        if (t.has("gzip")) {
            tgzip = t.getBoolean("gzip");
            temp.setGzipStyles(tgzip);
            temp.setGzipScripts(tgzip);
            temp.setGzipTemplate(tgzip);
        }

        if (t.has("uniqueURL")) {
            Boolean unique = t.getBoolean("uniqueURL");
            temp.setUniqueURL(unique);
        }

        // template overrides default combineResources
        if (t.has("combineResources")) {
            boolean combineResources = t.getBoolean("combineResources");
            temp.setCombineResources(combineResources);
            temp.setCombineScripts(combineResources);
            temp.setCombineStyles(combineResources);
        }

        if (t.has("template")) {
            String turi = t.getString("template");
            ResourceURI templateURI = new ResourceURI(turi, baseURI, ResourceURI.TEMPLATE);
            temp.setTemplateURI(templateURI);
        }

        if (t.has("namespace")) {
            temp.setURINamespace(t.getString("namespace"));
        }

        if (t.has("extends")) {
            List<String> ancestors = null;
            String base = t.getString("extends");
            if (base.length() > 0) {
                String[] parentIds = null;
                if (base.indexOf(",") != -1) {
                    parentIds = base.split(",");
                } else {
                    parentIds = new String[1];
                    parentIds[0] = base;
                }
                ancestors = new ArrayList<String>();

                for (int j = 0; j < parentIds.length; j++) {
                    ancestors.add(parentIds[j].trim());
                }
            }

            temp.setAncestors(ancestors);
        }

        if (t.has("overrides")) {

            List<TemplateOverride> overrides = new ArrayList<TemplateOverride>();
            JSONArray joa = t.getJSONArray("overrides");
            for (int z = 0; z < joa.length(); z++) {
                TemplateOverride tor = new TemplateOverride();
                JSONObject toro = joa.getJSONObject(z);
                if (toro.has("test")) {
                    tor.setTest(toro.getString("test"));
                }
                if (toro.has("uaTest")) {
                    tor.setUATest(toro.getString("uaTest"));
                }
                if (toro.has("import")) {
                    tor.setImportURI(toro.getString("import"));
                }
                overrides.add(tor);
            }
            temp.setTemplateOverrides(overrides);
        }

        if (t.has("scripts")) {

            JSONObject bsjo = t.getJSONObject("scripts");

            processURIResources(ResourceURI.SCRIPT, bsjo, temp, baseURI);
        }

        if (t.has("styles")) {
            JSONObject bsjo = t.getJSONObject("styles");

            processURIResources(ResourceURI.LINK, bsjo, temp, baseURI);
        }

        if (t.has("properties")) {

            Map<String, IProperty> properties = null;
            JSONObject po = t.getJSONObject("properties");
            properties = new HashMap<String, IProperty>();

            Iterator<String> jit = po.keys();
            while (jit.hasNext()) {

                String name = jit.next();
                JSONObject so = po.getJSONObject(name);
                int type = IProperty.STRING;
                String value = so.getString("value");

                if (so.has("type")) {

                    String typeString = so.getString("type");

                    if ("string".equals(typeString.toLowerCase())) {
                        type = IProperty.STRING;
                    } else if ("include".equals(typeString.toLowerCase())) {
                        type = IProperty.INCLUDE;
                    }
                }

                IProperty pi = new Property(name, value, type, baseURI, temp.getId());

                if (so.has("timeout")) {
                    long timeout = so.getLong("timeout");
                    pi.setTimeout(timeout);
                }
                if (so.has("id")) {
                    pi.setId(so.getString("id"));
                }
                if (so.has("uaTest")) {
                    pi.setUATest(so.getString("uaTest"));
                }
                if (so.has("test")) {
                    pi.setTest(so.getString("test"));
                }
                if (so.has("defer")) {
                    pi.setDefer(so.getBoolean("defer"));
                }
                if (so.has("deferContent")) {
                    pi.setDeferContent(new StringBuffer(so.getString("deferContent")));
                }
                properties.put(name, pi);
            }
            temp.setProperties(properties);
        }

    } catch (JSONException e) {
        getLogger().log(Level.SEVERE, "Error parsing configuration.", e);
    }

}

From source file:edu.umass.cs.msocket.common.policies.GeolocationProxyPolicy.java

/**
 * @throws Exception if a GNS error occurs
 * @see edu.umass.cs.msocket.common.policies.ProxySelectionPolicy#getNewProxy()
 *//*from   w ww.  j  av  a2s .c o m*/
@Override
public List<InetSocketAddress> getNewProxy() throws Exception {
    // Lookup for active location service GUIDs
    final UniversalGnsClient gnsClient = gnsCredentials.getGnsClient();
    final GuidEntry guidEntry = gnsCredentials.getGuidEntry();
    JSONArray guids;
    try {
        guids = gnsClient.fieldRead(proxyGroupName, GnsConstants.ACTIVE_LOCATION_FIELD, guidEntry);
    } catch (Exception e) {
        throw new GnsException("Could not find active location services (" + e + ")");
    }

    // Try every location proxy in the list until one works
    for (int i = 0; i < guids.length(); i++) {
        // Retrieve the location service IP and connect to it
        String locationGuid = guids.getString(i);
        String locationIP = gnsClient.fieldRead(locationGuid, GnsConstants.LOCATION_SERVICE_IP, guidEntry)
                .getString(0);
        logger.fine("Contacting location service " + locationIP + " to request " + numProxies + " proxies");

        // Location IP is stored as host:port
        StringTokenizer st = new StringTokenizer(locationIP, ":");
        try {
            // Protocol is send the number of desired proxies and receive strings
            // containing proxy IP:port
            Socket s = new Socket(st.nextToken(), Integer.parseInt(st.nextToken()));
            ObjectOutputStream oos = new ObjectOutputStream(s.getOutputStream());
            ObjectInputStream ois = new ObjectInputStream(s.getInputStream());
            oos.writeInt(numProxies);
            oos.flush();
            List<InetSocketAddress> result = new LinkedList<InetSocketAddress>();
            while (!s.isClosed() && result.size() < numProxies) {
                String proxyIP = ois.readUTF();
                StringTokenizer stp = new StringTokenizer(proxyIP, ":");
                result.add(new InetSocketAddress(stp.nextToken(), Integer.parseInt(stp.nextToken())));
            }
            if (!s.isClosed()) // We receive all the proxies we need, just close the
                               // socket
                s.close();
            return result;
        } catch (Exception e) {
            logger.info("Failed to obtain proxy from location service" + locationIP + " (" + e + ")");
        }
    }

    throw new GnsException("Could not find any location service to provide a geolocated proxy");
}

From source file:census.couchdroid.CouchViewResults.java

/**
 * Retrieves a list of documents that matched this View.
 * These documents only contain the data that the View has returned (not the full document).
 * <p>/*w w w  . jav a 2 s.  co  m*/
 * You can load the remaining information from Document.reload();
 * 
 * @return
*/
public List<CouchDocument> getResults() {
    JSONArray ar = null;
    try {
        android.util.Log.e("Census", getJSONObject().toString());
        ar = getJSONObject().getJSONArray("rows");
    } catch (JSONException e) {
        return null;
    }
    List<CouchDocument> docs = new ArrayList<CouchDocument>(ar.length());
    for (int i = 0; i < ar.length(); i++) {
        try {
            if (ar.get(i) != null && !ar.getString(i).equals("null")) {
                CouchDocument d = new CouchDocument(ar.getJSONObject(i));
                d.setDatabase(database);
                docs.add(d);
            }
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    return docs;

}

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

public static Favorite parse(JSONObject jsonObject) {
    if (null == jsonObject) {
        return null;
    }//from ww  w  . j  a  v a 2 s  . c o m

    Favorite favorite = new Favorite();
    favorite.status = Status.parse(jsonObject.optJSONObject("status"));
    favorite.favorited_time = jsonObject.optString("favorited_time");

    JSONArray jsonArray = jsonObject.optJSONArray("tags");
    if (jsonArray != null && jsonArray.length() > 0) {
        int length = jsonArray.length();
        favorite.tags = new ArrayList<Tag>(length);
        for (int ix = 0; ix < length; ix++) {
            favorite.tags.add(Tag.parse(jsonArray.optJSONObject(ix)));
        }
    }

    return favorite;
}

From source file:nl.hnogames.domoticzapi.Parsers.NotificationsParser.java

@Override
public void parseResult(String result) {
    try {//from   w w  w  .  j  a v  a 2  s .com
        JSONArray jsonArray = new JSONArray(result);
        ArrayList<NotificationInfo> mNotificationInfo = new ArrayList<>();

        if (jsonArray.length() > 0) {
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject row = jsonArray.getJSONObject(i);
                mNotificationInfo.add(new NotificationInfo(row));
            }
        }
        notificationsReceiver.onReceiveNotifications(mNotificationInfo);

    } catch (JSONException e) {
        Log.e(TAG, "JSON exception");
        e.printStackTrace();
        notificationsReceiver.onError(e);
    }
}

From source file:ub.botiga.data.User.java

public User(JSONObject obj, HashMap<String, Product> totalproducts) throws JSONException {
    this.mName = obj.getString("name");
    this.mCredit = (float) obj.getDouble("credit");
    this.mProducts = new HashMap<String, Product>();
    JSONArray m = obj.getJSONArray("products");
    String p;/*from   w  w  w .  ja  va2  s. c om*/
    for (int i = 0; i < m.length(); i++) {
        p = m.getString(i);
        if (totalproducts.containsKey(p)) {
            mProducts.put(p, totalproducts.get(p));
        }
    }

}

From source file:com.pansapiens.occyd.JSONdecoder.java

/**
* Abstract utility class for parsing JSON objects (as strings) and
* returning Java objects./*from  ww w  . j ava2s .  c o  m*/
*/
public static ArrayList<Post> json2postArray(String json_txt) throws JSONException {
    /**
     * Takes an appropriate JSON format string, returned as a response
     * by the server to a search query, returns an ArrayList
     *  of Post objects. 
     */
    ArrayList<Post> post_results = new ArrayList();

    if (json_txt != null) {
        // http://code.google.com/android/reference/org/json/JSONObject.html
        JSONTokener jsontok = new JSONTokener(json_txt);
        JSONObject json;
        String geohash = null;
        String[] tags = null;

        // TODO: read these from the JSON too
        //String key = null;
        //String user = null;
        //String desc = null;
        //URL link = null;
        // see: http://java.sun.com/j2se/1.4.2/docs/api/java/util/Date.html
        //Date date = null;
        // parse "2008-12-31 03:22:23.350798" format date with:
        // (could have an issue with to many millisecond places SSSSSS .... may need to truncate)
        // SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
        // Date date = dateformat.parse(dateString);

        float lat, lon;

        json = new JSONObject(jsontok);

        // catch any error codes in the returned json
        String result = json.getString("result");
        if (!result.equals("done")) {
            return post_results;
        }

        // unpack the json into Post objects, add them to the result list
        JSONArray posts = json.getJSONArray("posts");
        for (int i = 0; i < posts.length(); i++) {
            JSONObject p = posts.getJSONObject(i);
            geohash = (String) p.get("geohash");
            JSONArray coordinates = p.getJSONArray("coordinates");
            lat = (float) coordinates.getDouble(0);
            lon = (float) coordinates.getDouble(1);

            JSONArray t = p.getJSONArray("tags");
            tags = new String[t.length()];
            for (int j = 0; j < t.length(); j++) {
                tags[j] = t.getString(j);
            }

            Post post = new Post(lat, lon, geohash, tags);
            post_results.add(post);
        }
    }
    return post_results;
}

From source file:net.jmhertlein.mcanalytics.console.gui.LoginPane.java

private void loadHostPanes(JSONObject config) {

    if (config.has("hosts")) {
        JSONArray hosts = config.getJSONArray("hosts");
        for (int i = 0; i < hosts.length(); i++) {
            JSONObject host = hosts.getJSONObject(i);
            HostEntry entry = HostEntry.fromJSON(host);
            try {
                entry.setHasCert(trust.containsAlias(entry.getUrl() + "-private"));
            } catch (KeyStoreException ex) {
                Logger.getLogger(LoginPane.class.getName()).log(Level.SEVERE, null, ex);
            }/*w w  w  .ja va2s. co m*/
            hostList.getItems().add(entry);
        }
    }

    if (!hostList.getItems().isEmpty())
        hostList.getSelectionModel().select(0);
}