Example usage for org.json.simple JSONArray size

List of usage examples for org.json.simple JSONArray size

Introduction

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

Prototype

public int size() 

Source Link

Document

Returns the number of elements in this list.

Usage

From source file:alexaactions.SmartThingsAgent.java

String getById(String path, String id) {
    String devices_json = get(path);

    System.out.println(devices_json);

    JSONParser parser = new JSONParser();
    Object obj = null;/*from ww w  .  j a va  2s  . c o  m*/
    JSONObject device;
    JSONArray arr;

    // the whole purpose of this code is to determine if the id is valid
    try {
        obj = parser.parse(devices_json);
    } catch (ParseException ex) {
        Logger.getLogger(SmartThingsTemperatureDevices.class.getName()).log(Level.SEVERE, null, ex);
    }

    arr = (JSONArray) obj;
    if (arr != null) {
        int i, j;

        for (i = 0; i < arr.size(); i++) {
            device = (JSONObject) arr.get(i);
            String d_id = (String) device.get("id");
            if (d_id == null ? id == null : d_id.equals(id)) {
                for (j = 0; j < endpoints.size(); j++) {
                    JSONObject e = (JSONObject) endpoints.get(j);
                    String url = (String) e.get("uri") + "/" + path + "/" + d_id;
                    HashMap<String, String> headers = new HashMap<String, String>();
                    headers.put("Authorization", "Bearer " + access_token);

                    return smartthings.get(url, headers);
                }
            }
        }
    }
    return null;
}

From source file:alexaactions.SmartThingsAgent.java

String getByLabel(String path, String label) {
    String devices_json = get(path);

    System.out.println(devices_json);

    JSONParser parser = new JSONParser();
    Object obj = null;//w  w  w .  j av  a 2s .  c  o  m
    JSONObject device;
    JSONArray arr;

    // the whole purpose of this code is to determine if the id is valid
    try {
        obj = parser.parse(devices_json);
    } catch (ParseException ex) {
        Logger.getLogger(SmartThingsTemperatureDevices.class.getName()).log(Level.SEVERE, null, ex);
    }

    arr = (JSONArray) obj;
    if (arr != null) {
        int i, j;

        for (i = 0; i < arr.size(); i++) {
            device = (JSONObject) arr.get(i);
            String d_label = (String) device.get("label");
            String d_id = (String) device.get("id");
            if (d_label == null ? label == null : d_label.equals(label)) {
                for (j = 0; j < endpoints.size(); j++) {
                    JSONObject e = (JSONObject) endpoints.get(j);
                    String url = (String) e.get("uri") + "/" + path + "/" + d_id;
                    HashMap<String, String> headers = new HashMap<String, String>();
                    headers.put("Authorization", "Bearer " + access_token);

                    return smartthings.get(url, headers);
                }
            }
        }
    }
    return null;
}

From source file:com.telefonica.iot.cygnus.backends.ckan.CKANCache.java

/**
 * Checks if the resource is cached. If not cached, CKAN is queried in order to update the cache.
 * This method assumes the given organization and package exist and they are cached.
 * @param orgName Organization name//w w w  .j  av  a2  s.  c  o  m
 * @param pkgName Package name
 * @param resName Resource name
 * @return True if the organization was cached, false otherwise
 * @throws Exception
 */
public boolean isCachedRes(String orgName, String pkgName, String resName) throws Exception {
    // check if the resource has already been cached
    if (tree.get(orgName).get(pkgName).contains(resName)) {
        LOGGER.debug("Resource found in the cache (orgName=" + orgName + ", pkgName=" + pkgName + ", resName="
                + resName + ")");
        return true;
    } // if

    LOGGER.debug("Resource not found in the cache, querying CKAN for the whole package containing it "
            + "(orgName=" + orgName + ", pkgName=" + pkgName + ", resName=" + resName + ")");

    // reached this point, we need to query CKAN about the resource, in order to know if it exists in CKAN
    // nevertheless, the CKAN API allows us to query for a certain resource by id, not by name...
    // the only solution seems to query for the whole package and check again
    // query CKAN for the organization information

    String ckanURL = "/api/3/action/package_show?id=" + pkgName;
    ArrayList<Header> headers = new ArrayList<Header>();
    headers.add(new BasicHeader("Authorization", apiKey));
    JsonResponse res = doRequest("GET", ckanURL, true, headers, null);

    if (res.getStatusCode() == 200) {
        // the package exists in CKAN
        LOGGER.debug("Package found in CKAN, going to update the cached resources (orgName=" + orgName
                + ", pkgName=" + pkgName + ")");

        // there is no need to check if the package is in "deleted" state...

        // there is no need to put the package in the tree nor put it in the package map...

        // get the resource and populate the resource map
        JSONObject result = (JSONObject) res.getJsonObject().get("result");
        JSONArray resources = (JSONArray) result.get("resources");

        if (resources.size() == 0) {
            return false;
        } else {
            LOGGER.debug(
                    "Going to populate the resources cache (orgName=" + orgName + ", pkgName=" + pkgName + ")");
            populateResourcesMap(resources, orgName, pkgName, true);
            return true;
        } // if else
    } else if (res.getStatusCode() == 404) {
        throw new CygnusRuntimeError("Unexpected package error when updating its resources... the package was "
                + "supposed to exist!");
    } else {
        throw new CygnusRuntimeError("Don't know how to treat response code " + res.getStatusCode() + ")");
    } // if else
}

From source file:com.googlecode.fascinator.portal.security.FascinatorWebSecurityExpressionRoot.java

/**
 * get the workflow configuration of a digital object at the current stage
 * /*ww w  . j a va2  s . com*/
 * @param digitalObject
 * @throws StorageException
 * @throws IOException
 */
private JsonObject getWorkflowStageConfig(DigitalObject digitalObject) throws StorageException, IOException {
    JsonSimple workflowMetadata = getWorkflowMetadata(digitalObject);
    String workflowId = workflowMetadata.getString(null, "id");
    JsonSimple workflowConfiguration = getWorkflowConfiguration(workflowId);

    JSONArray workflowStages = workflowConfiguration.getArray("stages");
    JsonObject workflowStageConfiguration = null;
    for (int i = 0; i < workflowStages.size(); i++) {
        JsonObject workflowStage = (JsonObject) workflowStages.get(i);
        if (workflowMetadata.getJsonObject().get("step").equals(workflowStage.get("name"))) {
            workflowStageConfiguration = workflowStage;
            break;
        }
    }
    return workflowStageConfiguration;
}

From source file:com.tremolosecurity.provisioning.core.providers.SugarCRM.java

@Override
public void deleteUser(User user, Map<String, Object> request) throws ProvisioningException {
    try {//  w  ww .  j a va 2 s  . c o m

        String sessionId = sugarLogin();
        Gson gson = new Gson();

        SugarGetEntryList sgel = new SugarGetEntryList();
        sgel.setSession(sessionId);
        sgel.setModule_name("Contacts");
        StringBuffer b = new StringBuffer();
        b.append(
                "contacts.id in (SELECT eabr.bean_id FROM email_addr_bean_rel eabr JOIN email_addresses ea ON (ea.id = eabr.email_address_id) WHERE eabr.deleted=0 AND ea.email_address = '")
                .append(user.getUserID()).append("')");
        sgel.setQuery(b.toString());
        sgel.setOrder_by("");
        sgel.setOffset(0);
        ArrayList<String> reqFields = new ArrayList<String>();
        reqFields.add("id");
        sgel.setSelect_fields(reqFields);
        sgel.setMax_results(-1);
        sgel.setDeleted(false);
        sgel.setLink_name_to_fields_array(new HashMap<String, List<String>>());

        String searchJson = gson.toJson(sgel);
        String respJSON = execJson(searchJson, "get_entry_list");
        JSONObject jsonObj = (JSONObject) JSONValue.parse(respJSON);
        JSONArray jsonArray = (JSONArray) jsonObj.get("entry_list");

        if (jsonArray.size() == 0) {
            throw new Exception("User " + user.getUserID() + " not found");
        }

        String id = (String) ((JSONObject) jsonArray.get(0)).get("id");

        SugarEntry newContact = new SugarEntry();
        newContact.setSession(sessionId);
        newContact.setModule("Contacts");
        Map<String, String> nvps = new HashMap<String, String>();
        nvps.put("id", id);
        nvps.put("deleted", "1");

        newContact.setName_value_list(nvps);
        String createUserJSON = gson.toJson(newContact);

        execJson(createUserJSON, "set_entry");
    } catch (Exception e) {
        throw new ProvisioningException("Could not delete user", e);
    }

}

From source file:com.orthancserver.SelectImageDialog.java

public void Unserialize(String s) {
    if (s.length() == 0) {
        // Add default Orthanc server
        AddOrthancServer(new OrthancConnection());
    } else {//  w ww.  j a v a2s .c  o  m
        String decoded = new String(DatatypeConverter.parseBase64Binary(s));
        JSONArray config = (JSONArray) JSONValue.parse(decoded);
        if (config != null) {
            for (int i = 0; i < config.size(); i++) {
                AddOrthancServer(OrthancConnection.Unserialize((JSONObject) config.get(i)));
            }
        }
    }
}

From source file:functionaltests.RestSchedulerTagTest.java

@Test
public void testJobTagsPrefix() throws Exception {
    HttpResponse response = sendRequest("jobs/" + submittedJobId + "/tasks/tags/startsWith/LOOP");
    JSONArray jsonArray = toJsonArray(response);

    System.out.println(jsonArray.toJSONString());

    assertTrue(jsonArray.contains("LOOP-T2-1"));
    assertTrue(jsonArray.contains("LOOP-T2-2"));
    assertTrue(jsonArray.contains("LOOP-T2-3"));
    assertEquals(3, jsonArray.size());
}

From source file:com.mp.gw2api.data.GW2APIMap.java

@Override
public void LoadFromJsonText(String text) {
    JSONParser parser = new JSONParser();
    JSONObject json = null;//from  www . j a va2s .com
    JSONArray ja = null;
    JSONArray jb = null;

    try {
        //Parse json array
        json = (JSONObject) parser.parse(text);

        id = (long) json.get("id");
        name = (String) json.get("name");
        minLevel = (long) json.get("min_level");
        maxLevel = (long) json.get("max_level");
        defFloor = (long) json.get("default_floor");

        ja = (JSONArray) json.get("floors");
        if (ja != null)
            if (ja.size() > 0) {
                floors = new long[ja.size()];
                for (int i = 0; i < ja.size(); i++)
                    floors[i] = (long) ja.get(i);
            }

        region = new GW2APIMapRegion((long) json.get("region_id"), (String) json.get("region_name"));
        continent = new GW2APIMapContinent((long) json.get("continent_id"),
                (String) json.get("continent_name"));

        mapRect = new PointRectangle();
        ja = (JSONArray) json.get("map_rect");
        jb = (JSONArray) ja.get(0);
        mapRect.begin.x = (long) jb.get(0);
        mapRect.begin.y = (long) jb.get(1);
        jb = (JSONArray) ja.get(1);
        mapRect.end.x = (long) jb.get(0);
        mapRect.end.y = (long) jb.get(1);

        contRect = new PointRectangle();
        ja = (JSONArray) json.get("continent_rect");
        jb = (JSONArray) ja.get(0);
        contRect.begin.x = (long) jb.get(0);
        contRect.begin.y = (long) jb.get(1);
        jb = (JSONArray) ja.get(1);
        contRect.end.x = (long) jb.get(0);
        contRect.end.y = (long) jb.get(1);

    } catch (ParseException ex) {
        Logger.getLogger(GW2APIMapList.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:com.shuffle.mock.MockCoin.java

public static MockCoin fromJSON(Reader jsonObject) throws IllegalArgumentException {

    JSONObject json = null;/*from w  ww . j  av  a  2 s . c  o m*/
    JSONArray outputs = null;
    JSONArray transactions = null;
    try {
        json = (JSONObject) JSONValue.parse(jsonObject);
        if (json == null) {
            throw new IllegalArgumentException("could not parse json object.");
        }

        outputs = (JSONArray) json.get("outputs");
        if (outputs == null) {
            throw new IllegalArgumentException("Missing field \"outputs\".");
        }

        transactions = (JSONArray) json.get("transactions");
        if (transactions == null) {
            throw new IllegalArgumentException("Missing field \"transactions\".");
        }
    } catch (ClassCastException e) {
        throw new IllegalArgumentException("could not parse json object.");
    }

    MockCoin mock = new MockCoin();

    Map<Long, Output> outList = new HashMap<>();
    for (int i = 1; i <= outputs.size(); i++) {
        JSONObject o = null;
        try {
            o = (JSONObject) outputs.get(i - 1);
        } catch (ClassCastException e) {
            throw new IllegalArgumentException("Could not read " + outputs.get(i - 1) + " as json object.");
        }

        Object address = o.get("address");
        Long amount = (Long) o.get("amount");
        if (address == null) {
            throw new IllegalArgumentException("Output missing field \"address\".");
        }
        if (amount == null) {
            throw new IllegalArgumentException("Output missing field \"amount\".");
        }

        Output bo = null;
        if (address instanceof String) {
            bo = new Output(new MockAddress((String) address), amount);
        } else if (address instanceof Long) {
            bo = new Output(new MockAddress((Long) address), amount);
        } else {
            throw new IllegalArgumentException("Could not read " + address + " as address");
        }

        outList.put((long) i, bo);
        mock.blockchain.put(bo.address, bo);
    }

    for (Object t : transactions) {

        JSONObject trans = (JSONObject) t;
        JSONArray in = (JSONArray) trans.get("inputs");
        JSONArray out = (JSONArray) trans.get("outputs");
        List<Output> tout = new LinkedList<>();
        List<Output> tin = new LinkedList<>();

        for (Object i : in) {
            Output o = outList.get(i);
            if (o == null) {
                throw new IllegalArgumentException("Missing output " + o);
            }
            tin.add(outList.get(i));
        }

        for (Object i : out) {
            Output o = outList.get(i);
            if (o == null) {
                throw new IllegalArgumentException("Missing output " + o);
            }
            tout.add(outList.get(i));
        }

        MockTransaction tr;
        Long z = null;
        Object zz = trans.get("z");
        try {

            if (zz == null) {
                tr = new MockTransaction(tin, tout, mock);
            } else {
                z = (Long) zz;
                tr = new MockTransaction(tin, tout, z.intValue(), mock, new HashMap<Output, VerificationKey>());
            }
        } catch (ClassCastException e) {
            throw new IllegalArgumentException("Could not read z value " + zz + " as long.");
        }
    }

    return mock;
}

From source file:co.mcme.animations.animations.MCMEAnimation.java

public void loadConfiguration() {
    JSONParser parser = new JSONParser();
    try {/*from   w ww .  ja  v a2  s.  c  o  m*/
        Object obj = parser.parse(new FileReader(configFile));

        animationConfiguration = (JSONObject) obj;

        animationName = (String) animationConfiguration.get("name");
        schematicBaseName = animationName;

        localWorldName = (String) animationConfiguration.get("world-index");

        JSONArray JSONFrames = (JSONArray) animationConfiguration.get("frames");
        JSONArray JSONDurations = (JSONArray) animationConfiguration.get("durations");

        for (int i = 0; i < JSONFrames.size(); i++) {
            MCMEAnimationFrame frame = new MCMEAnimationFrame((String) JSONFrames.get(i),
                    (Long) JSONDurations.get(i));
            frames.add(frame);
        }

        JSONArray JSONOrigin = (JSONArray) animationConfiguration.get("origin");
        origin = new Location(MCMEAnimations.WEPlugin.getServer().getWorlds().get(0), (Long) JSONOrigin.get(0),
                (Long) JSONOrigin.get(1), (Long) JSONOrigin.get(2));

        try {
            animationDescription = (String) animationConfiguration.get("description");
        } catch (Exception ex) {
            //Failed to load description.
            //Put in a try-catch block for backward compatibility
        }

        loadTriggers();

        loadActions();

    } catch (IOException ex) {
        Logger.getLogger(OneTimeAnimation.class.getName()).log(Level.SEVERE, null, ex);
    } catch (ParseException ex) {
        Logger.getLogger(OneTimeAnimation.class.getName()).log(Level.SEVERE, null, ex);
    }
}