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:com.ibm.hellotodoadvanced.MainActivity.java

/**
 * Uses Bluemix Mobile Services SDK to GET the TodoItems from Bluemix and updates the local list.
 *//*w w  w . j av  a  2  s .c o  m*/
private void loadList() {

    // Send GET Request to Bluemix backend to retreive item list with response listener
    Request request = new Request(bmsClient.getBluemixAppRoute() + "/api/Items", Request.GET);
    request.send(getApplicationContext(), new ResponseListener() {
        // Loop through JSON response and create local TodoItems if successful
        @Override
        public void onSuccess(Response response) {
            if (response.getStatus() != 200) {
                Log.e(TAG, "Error pulling items from Bluemix: " + response.toString());
            } else {

                try {

                    mTodoItemList.clear();

                    JSONArray jsonArray = new JSONArray(response.getResponseText());

                    for (int i = 0; i < jsonArray.length(); i++) {
                        JSONObject tempTodoJSON = jsonArray.getJSONObject(i);
                        TodoItem tempTodo = new TodoItem();

                        tempTodo.idNumber = tempTodoJSON.getInt("id");
                        tempTodo.text = tempTodoJSON.getString("text");
                        tempTodo.isDone = tempTodoJSON.getBoolean("isDone");

                        mTodoItemList.add(tempTodo);
                    }

                    // Need to notify adapter on main thread in order for list changes to update visually
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            mTodoItemAdapter.notifyDataSetChanged();

                            Log.i(TAG, "List updated successfully");

                            if (mSwipeLayout.isRefreshing()) {
                                mSwipeLayout.setRefreshing(false);
                            }
                        }
                    });

                } catch (Exception exception) {
                    Log.e(TAG, "Error reading response JSON: " + exception.getLocalizedMessage());
                }
            }
        }

        // Log Errors on failure
        @Override
        public void onFailure(Response response, Throwable throwable, JSONObject extendedInfo) {
            String errorMessage = "";

            if (response != null) {
                errorMessage += response.toString() + "\n";
            }

            if (throwable != null) {
                StringWriter sw = new StringWriter();
                PrintWriter pw = new PrintWriter(sw);
                throwable.printStackTrace(pw);
                errorMessage += "THROWN" + sw.toString() + "\n";
            }

            if (extendedInfo != null) {
                errorMessage += "EXTENDED_INFO" + extendedInfo.toString() + "\n";
            }

            if (errorMessage.isEmpty())
                errorMessage = "Request Failed With Unknown Error.";

            Log.e(TAG, "loadList failed with error: " + errorMessage);
        }
    });

}

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

private Response<List<TransientUser>> parseNetworkResponse(NetworkResponse response) {
    try {/*from  w  w w .  j a  va  2s .  c  om*/
        String jsonString = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
        JSONObject result = new JSONObject(jsonString);
        // set next_cursor
        mNext_cursor = result.optInt(User.next_cursor);
        mTotal_number = result.optInt(User.total_number);
        JSONArray array = result.optJSONArray(User.MULTIPLE);
        if (array != null) {
            List<TransientUser> users = new ArrayList<TransientUser>(array.length());
            for (int i = 0; i < array.length(); i++) {
                users.add(TransientUser.convert(array.optJSONObject(i)));
            }
            return Response.success(users, HttpHeaderParser.parseCacheHeaders(response));
        } else {
            throw new RuntimeException("no users found!");
        }
    } catch (UnsupportedEncodingException e) {
        return Response.error(new ParseError(e));
    } catch (JSONException je) {
        return Response.error(new ParseError(je));
    } catch (Exception ex) {
        return Response.error(new ParseError(ex));
    }
}

From source file:org.dasein.cloud.aws.compute.EC2Instance.java

@Override
public Iterable<VirtualMachineProduct> listProducts(VirtualMachineProductFilterOptions options,
        Architecture architecture) throws InternalException, CloudException {
    ProviderContext ctx = getProvider().getContext();
    if (ctx == null) {
        throw new CloudException("No context was set for this request");
    }/*  w  w w. j av a  2  s .com*/
    // FIXME: until core fixes the annotation for architecture let's assume it's nullable
    String cacheName = "productsALL";
    if (architecture != null) {
        cacheName = "products" + architecture.name();
    }
    Cache<VirtualMachineProduct> cache = Cache.getInstance(getProvider(), cacheName,
            VirtualMachineProduct.class, CacheLevel.REGION, new TimePeriod<Day>(1, TimePeriod.DAY));
    Iterable<VirtualMachineProduct> products = cache.get(ctx);

    if (products == null) {
        List<VirtualMachineProduct> list = new ArrayList<VirtualMachineProduct>();

        try {
            InputStream input = EC2Instance.class.getResourceAsStream("/org/dasein/cloud/aws/vmproducts.json");

            if (input != null) {
                BufferedReader reader = new BufferedReader(new InputStreamReader(input));
                StringBuilder json = new StringBuilder();
                String line;

                while ((line = reader.readLine()) != null) {
                    json.append(line);
                    json.append("\n");
                }
                JSONArray arr = new JSONArray(json.toString());
                JSONObject toCache = null;

                for (int i = 0; i < arr.length(); i++) {
                    JSONObject productSet = arr.getJSONObject(i);
                    String cloud, providerName;

                    if (productSet.has("cloud")) {
                        cloud = productSet.getString("cloud");
                    } else {
                        continue;
                    }
                    if (productSet.has("provider")) {
                        providerName = productSet.getString("provider");
                    } else {
                        continue;
                    }
                    if (!productSet.has("products")) {
                        continue;
                    }
                    if (toCache == null || (providerName.equals("AWS") && cloud.equals("AWS"))) {
                        toCache = productSet;
                    }
                    if (providerName.equalsIgnoreCase(getProvider().getProviderName())
                            && cloud.equalsIgnoreCase(getProvider().getCloudName())) {
                        toCache = productSet;
                        break;
                    }
                }
                if (toCache == null) {
                    logger.warn("No products were defined");
                    return Collections.emptyList();
                }
                JSONArray plist = toCache.getJSONArray("products");

                for (int i = 0; i < plist.length(); i++) {
                    JSONObject product = plist.getJSONObject(i);
                    boolean supported = false;

                    if (architecture != null) {
                        if (product.has("architectures")) {
                            JSONArray architectures = product.getJSONArray("architectures");

                            for (int j = 0; j < architectures.length(); j++) {
                                String a = architectures.getString(j);

                                if (architecture.name().equals(a)) {
                                    supported = true;
                                    break;
                                }
                            }
                        }
                        if (!supported) {
                            continue;
                        }
                    }
                    if (product.has("excludesRegions")) {
                        JSONArray regions = product.getJSONArray("excludesRegions");

                        for (int j = 0; j < regions.length(); j++) {
                            String r = regions.getString(j);

                            if (r.equals(ctx.getRegionId())) {
                                supported = false;
                                break;
                            }
                        }
                    }
                    if (!supported) {
                        continue;
                    }
                    VirtualMachineProduct prd = toProduct(product);

                    if (prd != null) {
                        if (options != null) {
                            if (options.matches(prd)) {
                                list.add(prd);
                            }
                        } else {
                            list.add(prd);
                        }
                    }

                }

            } else {
                logger.warn("No standard products resource exists for /org/dasein/cloud/aws/vmproducts.json");
            }
            input = EC2Instance.class.getResourceAsStream("/org/dasein/cloud/aws/vmproducts-custom.json");
            if (input != null) {
                ArrayList<VirtualMachineProduct> customList = new ArrayList<VirtualMachineProduct>();
                TreeSet<String> discard = new TreeSet<String>();
                boolean discardAll = false;

                BufferedReader reader = new BufferedReader(new InputStreamReader(input));
                StringBuilder json = new StringBuilder();
                String line;

                while ((line = reader.readLine()) != null) {
                    json.append(line);
                    json.append("\n");
                }
                JSONArray arr = new JSONArray(json.toString());
                JSONObject toCache = null;

                for (int i = 0; i < arr.length(); i++) {
                    JSONObject listing = arr.getJSONObject(i);
                    String cloud, providerName, endpoint = null;

                    if (listing.has("cloud")) {
                        cloud = listing.getString("cloud");
                    } else {
                        continue;
                    }
                    if (listing.has("provider")) {
                        providerName = listing.getString("provider");
                    } else {
                        continue;
                    }
                    if (listing.has("endpoint")) {
                        endpoint = listing.getString("endpoint");
                    }
                    if (!cloud.equals(getProvider().getCloudName())
                            || !providerName.equals(getProvider().getProviderName())) {
                        continue;
                    }
                    if (endpoint != null && endpoint.equals(ctx.getCloud().getEndpoint())) {
                        toCache = listing;
                        break;
                    }
                    if (endpoint == null && toCache == null) {
                        toCache = listing;
                    }
                }
                if (toCache != null) {
                    if (toCache.has("discardDefaults")) {
                        discardAll = toCache.getBoolean("discardDefaults");
                    }
                    if (toCache.has("discard")) {
                        JSONArray dlist = toCache.getJSONArray("discard");

                        for (int i = 0; i < dlist.length(); i++) {
                            discard.add(dlist.getString(i));
                        }
                    }
                    if (toCache.has("products")) {
                        JSONArray plist = toCache.getJSONArray("products");

                        for (int i = 0; i < plist.length(); i++) {
                            JSONObject product = plist.getJSONObject(i);
                            boolean supported = false;
                            if (architecture != null) {

                                if (product.has("architectures")) {
                                    JSONArray architectures = product.getJSONArray("architectures");

                                    for (int j = 0; j < architectures.length(); j++) {
                                        String a = architectures.getString(j);

                                        if (architecture.name().equals(a)) {
                                            supported = true;
                                            break;
                                        }
                                    }
                                }
                                if (!supported) {
                                    continue;
                                }
                            }
                            if (product.has("excludesRegions")) {
                                JSONArray regions = product.getJSONArray("excludesRegions");

                                for (int j = 0; j < regions.length(); j++) {
                                    String r = regions.getString(j);

                                    if (r.equals(ctx.getRegionId())) {
                                        supported = false;
                                        break;
                                    }
                                }
                            }
                            if (!supported) {
                                continue;
                            }
                            VirtualMachineProduct prd = toProduct(product);

                            if (prd != null) {
                                customList.add(prd);
                            }
                        }
                    }
                    if (!discardAll) {
                        for (VirtualMachineProduct product : list) {
                            if (!discard.contains(product.getProviderProductId())) {
                                customList.add(product);
                            }
                        }
                    }
                    list = customList;
                }
            }
            products = list;
            cache.put(ctx, products);

        } catch (IOException e) {
            throw new InternalException(e);
        } catch (JSONException e) {
            throw new InternalException(e);
        }
    }
    return products;
}

From source file:org.dasein.cloud.aws.compute.EC2Instance.java

private @Nullable VirtualMachineProduct toProduct(@Nonnull JSONObject json) throws InternalException {
    /*//from  w  w w .  j  a  v  a  2  s  . c  o  m
            {
        "architectures":["I32"],
        "id":"m1.small",
        "name":"Small Instance (m1.small)",
        "description":"Small Instance (m1.small)",
        "cpuCount":1,
        "rootVolumeSizeInGb":160,
        "ramSizeInMb": 1700
    },
     */
    VirtualMachineProduct prd = new VirtualMachineProduct();

    try {
        if (json.has("id")) {
            prd.setProviderProductId(json.getString("id"));
        } else {
            return null;
        }
        if (json.has("name")) {
            prd.setName(json.getString("name"));
        } else {
            prd.setName(prd.getProviderProductId());
        }
        if (json.has("description")) {
            prd.setDescription(json.getString("description"));
        } else {
            prd.setDescription(prd.getName());
        }
        if (json.has("cpuCount")) {
            prd.setCpuCount(json.getInt("cpuCount"));
        } else {
            prd.setCpuCount(1);
        }
        if (json.has("rootVolumeSizeInGb")) {
            prd.setRootVolumeSize(new Storage<Gigabyte>(json.getInt("rootVolumeSizeInGb"), Storage.GIGABYTE));
        } else {
            prd.setRootVolumeSize(new Storage<Gigabyte>(1, Storage.GIGABYTE));
        }
        if (json.has("ramSizeInMb")) {
            prd.setRamSize(new Storage<Megabyte>(json.getInt("ramSizeInMb"), Storage.MEGABYTE));
        } else {
            prd.setRamSize(new Storage<Megabyte>(512, Storage.MEGABYTE));
        }
        if (json.has("generation") && json.getString("generation").equalsIgnoreCase("previous")) {
            prd.setStatusDeprecated();
        }
        if (json.has("standardHourlyRates")) {
            JSONArray rates = json.getJSONArray("standardHourlyRates");

            for (int i = 0; i < rates.length(); i++) {
                JSONObject rate = rates.getJSONObject(i);

                if (rate.has("rate")) {
                    prd.setStandardHourlyRate((float) rate.getDouble("rate"));
                }
            }
        }
    } catch (JSONException e) {
        throw new InternalException(e);
    }
    return prd;
}

From source file:com.liferay.mobile.android.auth.SignIn.java

public static void signIn(final Session session, final JSONObjectCallback callback, final SignInMethod method) {

    GroupService groupService = new GroupService(session);

    session.setCallback(new JSONArrayCallback() {

        @Override/*  w  ww  .j ava  2  s  . co m*/
        public void onSuccess(JSONArray sites) {
            if (sites.length() == 0) {
                onFailure(new Exception("User doesn't belong to any site"));
            }

            try {
                JSONObject site = sites.getJSONObject(0);
                long companyId = site.getLong("companyId");

                Session userSession = new SessionImpl(session);
                userSession.setCallback(callback);

                UserService userService = new UserService(userSession);

                String username = getUsername(session);

                if (method == SignInMethod.EMAIL) {
                    userService.getUserByEmailAddress(companyId, username);
                } else if (method == SignInMethod.USER_ID) {
                    userService.getUserById(Long.parseLong(username));
                } else {
                    userService.getUserByScreenName(companyId, username);
                }
            } catch (Exception e) {
                onFailure(e);
            }
        }

        @Override
        public void onFailure(Exception exception) {
            callback.onFailure(exception);
        }

    });

    try {
        groupService.getUserSitesGroups();
    } catch (Exception e) {
        callback.onFailure(e);
    }
}

From source file:com.altamiracorp.lumify.twitter.DefaultLumifyTwitterProcessor.java

@Override
public void extractEntities(final String processId, final JSONObject jsonTweet, final Vertex tweetVertex,
        final TwitterEntityType entityType) {
    // TODO set visibility
    Visibility visibility = new Visibility("");
    String tweetText = JSON_TEXT_PROPERTY.getFrom(jsonTweet);
    // only process if text is found in the tweet
    if (tweetText != null && !tweetText.trim().isEmpty()) {
        String tweetId = tweetVertex.getId().toString();
        User user = getUser();/*from www .ja v  a 2  s .c  o  m*/
        Graph graph = getGraph();
        OntologyRepository ontRepo = getOntologyRepository();
        AuditRepository auditRepo = getAuditRepository();

        Concept concept = ontRepo.getConceptByName(entityType.getConceptName());
        Vertex conceptVertex = concept.getVertex();
        String relDispName = conceptVertex.getPropertyValue(LumifyProperties.DISPLAY_NAME.getKey(), 0)
                .toString();

        JSONArray entities = jsonTweet.getJSONObject("entities").getJSONArray(entityType.getJsonKey());
        List<TermMentionModel> mentions = new ArrayList<TermMentionModel>();

        for (int i = 0; i < entities.length(); i++) {
            JSONObject entity = entities.getJSONObject(i);
            String id;
            String sign = entity.getString(entityType.getSignKey());
            if (entityType.getConceptName().equals(CONCEPT_TWITTER_MENTION)) {
                id = TWITTER_USER_PREFIX + entity.get("id");
            } else if (entityType.getConceptName().equals(CONCEPT_TWITTER_HASHTAG)) {
                sign = sign.toLowerCase();
                id = TWITTER_HASHTAG_PREFIX + sign;
            } else {
                try {
                    id = URLEncoder.encode(TWITTER_URL_PREFIX + sign, "UTF-8");
                } catch (UnsupportedEncodingException e) {
                    throw new RuntimeException("URL id could not be UTF-8 encoded");
                }
            }
            checkNotNull(sign, "Term sign cannot be null");
            JSONArray indices = entity.getJSONArray("indices");
            TermMentionRowKey termMentionRowKey = new TermMentionRowKey(tweetId, indices.getLong(0),
                    indices.getLong(1));
            TermMentionModel termMention = new TermMentionModel(termMentionRowKey);
            termMention.getMetadata().setSign(sign)
                    .setOntologyClassUri(
                            (String) conceptVertex.getPropertyValue(LumifyProperties.DISPLAY_NAME.getKey(), 0))
                    .setConceptGraphVertexId(concept.getId()).setVertexId(id);
            mentions.add(termMention);
        }

        for (TermMentionModel mention : mentions) {
            String sign = mention.getMetadata().getSign().toLowerCase();
            String rowKey = mention.getRowKey().toString();
            String id = mention.getMetadata().getGraphVertexId();

            ElementMutation<Vertex> termVertexMutation;
            Vertex termVertex = graph.getVertex(id, user.getAuthorizations());
            if (termVertex == null) {
                termVertexMutation = graph.prepareVertex(id, visibility, user.getAuthorizations());
            } else {
                termVertexMutation = termVertex.prepareMutation();
            }

            TITLE.setProperty(termVertexMutation, sign, visibility);
            ROW_KEY.setProperty(termVertexMutation, rowKey, visibility);
            CONCEPT_TYPE.setProperty(termVertexMutation, concept.getId(), visibility);

            if (!(termVertexMutation instanceof ExistingElementMutation)) {
                termVertex = termVertexMutation.save();
                getAuditRepository().auditVertexElementMutation(termVertexMutation, termVertex, processId, user,
                        visibility);
            } else {
                getAuditRepository().auditVertexElementMutation(termVertexMutation, termVertex, processId, user,
                        visibility);
                termVertex = termVertexMutation.save();
            }

            String termId = termVertex.getId().toString();

            mention.getMetadata().setVertexId(termId);
            getTermMentionRepository().save(mention);

            graph.addEdge(tweetVertex, termVertex, entityType.getRelationshipLabel(), visibility,
                    user.getAuthorizations());

            auditRepo.auditRelationship(AuditAction.CREATE, tweetVertex, termVertex, relDispName, processId, "",
                    user, visibility);
            graph.flush();
        }
    }
}

From source file:net.di2e.ddf.argo.probe.responselistener.ProbeResponseEndpoint.java

@POST
@Consumes("application/json")
public void getJSONServices(String jsonResponse) {
    LOGGER.debug("Got a probe response in JSON format:\n{}", jsonResponse);
    JSONArray services = new JSONArray(jsonResponse);
    Set<String> createdSources = new HashSet<String>();
    for (int i = 0; i < services.length(); i++) {
        JSONObject jsonService = services.getJSONObject(i);
        // determine factory pid
        String sourceId = jsonService.getString(ArgoConstants.ID_KEY);
        if (!sourceIdExists(sourceId, createdSources)) {
            String serviceContractId = jsonService.getString(ArgoConstants.SERVICE_CONTRACTID_KEY);
            String serviceType = getServiceType(serviceContractId);
            if (serviceType != null) {
                String pid = serviceResolver.getFactoryPid(serviceType);
                LOGGER.debug(/* w ww .j  a v a 2 s  . c  o  m*/
                        "Got a factory pid of '{}' for service '{}' with service contract id '{}' so attempting to create new source '{}'",
                        pid, serviceType, serviceContractId, sourceId);
                createSource(pid, sourceId, jsonService.getString(ArgoConstants.URL_KEY));
                createdSources.add(sourceId);
            } else {
                LOGGER.debug("Could not find a Service Type for the Service Contract ID '{}'",
                        serviceContractId);
            }
        } else {
            LOGGER.debug(
                    "A Source with id '{}' already exists, so not creating a new one from probe, but checking if any values should be overridden",
                    sourceId);
            // TODO override properties
        }
    }
}

From source file:org.uiautomation.ios.grid.IOSCapabilitiesMonitor.java

private List<DesiredCapabilities> getNodeCapabilities() {
    try {/* ww w . j  a  v a2  s .c  o m*/
        List<DesiredCapabilities> capabilities = new ArrayList<DesiredCapabilities>();

        JSONObject status = getNodeStatusJson();
        if (status == null) {
            return null;
        }

        String ios = status.getJSONObject("value").getJSONObject("ios").optString("simulatorVersion");
        JSONArray supportedApps = status.getJSONObject("value").getJSONArray("supportedApps");

        for (int i = 0; i < supportedApps.length(); i++) {
            Map<String, Object> capability = new HashMap<String, Object>();
            capability.put("maxInstances", "1");
            if (ios.isEmpty()) {
                capability.put("ios", "5.1");
                capability.put("browserName", "IOS Device");
                capability.put(IOSCapabilities.DEVICE, DeviceType.iphone);
            } else {
                capability.put("ios", ios);
                capability.put("browserName", "IOS Simulator");
            }
            JSONObject app = supportedApps.getJSONObject(i);
            for (String key : JSONObject.getNames(app)) {
                if ("locales".equals(key)) {
                    JSONArray loc = app.getJSONArray(key);
                    List<String> locales = new ArrayList<String>();
                    for (int j = 0; j < loc.length(); j++) {
                        locales.add(loc.getString(j));
                    }
                    capability.put("locales", locales);
                } else {
                    Object o = app.get(key);
                    capability.put(key, o);
                }
            }
            capabilities.add(new DesiredCapabilities(capability));
        }
        return capabilities;
    } catch (Exception e) {
        return null;
    }
}

From source file:org.springframework.social.showcase.flux.support.FluxImpl.java

@Override
public List<String> getProjects() throws Exception {
    MessageConnector conn = getMessagingConnector();
    SingleResponseHandler<List<String>> rh = new SingleResponseHandler<List<String>>(getMessagingConnector(),
            GET_PROJECTS_RESPONSE) {/*from  www .j  a va2 s. c o m*/
        @Override
        protected List<String> parse(String messageType, JSONObject message) throws Exception {
            //Example message:
            //{"projects":[
            //      {"name":"bikok"},
            //      {"name":"hello-world"}
            //   ],
            //   "username":"kdvolder",
            //   "requestSenderID":"amq.gen-55217jjvJI3cJMF9-DZR4A"
            //}
            List<String> projects = new ArrayList<String>();
            JSONArray jps = message.getJSONArray("projects");
            for (int i = 0; i < jps.length(); i++) {
                projects.add(jps.getJSONObject(i).getString("name"));
            }
            return projects;
        }

    };
    conn.send(GET_PROJECTS_REQUEST, new JSONObject().put(USERNAME, getUsername()));
    return rh.awaitResult();
}

From source file:nl.hnogames.domoticz.Domoticz.EventsParser.java

@Override
public void parseResult(String result) {
    try {/*from ww  w  .j a  v a 2 s .co m*/
        JSONArray jsonArray = new JSONArray(result);
        ArrayList<EventInfo> mVars = new ArrayList<>();

        if (jsonArray.length() > 0) {
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject row = jsonArray.getJSONObject(i);
                mVars.add(new EventInfo(row));
            }
        }

        if (mVars == null || mVars.size() <= 0)
            onError(new NullPointerException("No Events devined in Domoticz."));
        else
            varsReceiver.onReceiveEvents(mVars);

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