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:de.static_interface.sinklibrary.Updater.java

private boolean isUpdateAvailable() {
    try {//from  w  w w  .  j av  a 2 s  . c  om
        final URLConnection conn = url.openConnection();
        conn.setConnectTimeout(5000);

        String version = SinkLibrary.getInstance().getVersion();

        conn.addRequestProperty("User-Agent", "SinkLibrary/v" + version + " (modified by Trojaner)");

        conn.setDoOutput(true);

        final BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        final String response = reader.readLine();

        final JSONArray array = (JSONArray) JSONValue.parse(response);

        if (array.size() == 0) {
            SinkLibrary.getInstance().getLogger()
                    .warning("The updater could not find any files for the project id " + id);
            result = UpdateResult.FAIL_BADID;
            return false;
        }

        versionName = (String) ((JSONObject) array.get(array.size() - 1)).get(Updater.TITLE_VALUE);
        versionLink = (String) ((JSONObject) array.get(array.size() - 1)).get(Updater.LINK_VALUE);
        versionType = (String) ((JSONObject) array.get(array.size() - 1)).get(Updater.TYPE_VALUE);
        versionGameVersion = (String) ((JSONObject) array.get(array.size() - 1)).get(Updater.VERSION_VALUE);

        return true;
    } catch (final IOException e) {
        if (e.getMessage().contains("HTTP response code: 403")) {
            SinkLibrary.getInstance().getLogger()
                    .warning("dev.bukkit.org rejected the API key provided in plugins/Updater/config.yml");
            SinkLibrary.getInstance().getLogger()
                    .warning("Please double-check your configuration to ensure it is correct.");
            result = UpdateResult.FAIL_APIKEY;
        } else {
            SinkLibrary.getInstance().getLogger()
                    .warning("The updater could not contact dev.bukkit.org for updating.");
            SinkLibrary.getInstance().getLogger().warning(
                    "If you have not recently modified your configuration and this is the first time you are seeing this message, the site may be experiencing temporary downtime.");
            result = UpdateResult.FAIL_DBO;
        }
        e.printStackTrace();
        return false;
    }
}

From source file:eu.seaclouds.platform.discoverer.crawler.CloudTypes.java

private Offering generateIAASOffering(CloudHarmonyService chs, JSONObject locationInformation,
        JSONObject computeInstanceType) {
    /* tosca lines into ArrayList */
    ArrayList<String> gt = new ArrayList<>();
    String providerName = chs.name;
    /* name not sanitized (used to access SPECint table) */
    String providerOriginalName = chs.originalName;
    String instanceId = (String) computeInstanceType.get("instanceId");
    String locationCode = (String) locationInformation.get("providerCode");

    /* name, taken as 'cloud service name'_'instance id'_'city where is located'  */
    String name = Offering.sanitizeName(providerName + "_" + instanceId + "_" + locationCode);

    Offering offering = new Offering(name);
    offering.setType("seaclouds.nodes.Compute." + Offering.sanitizeName(providerName));

    offering.addProperty("resource_type", "compute");
    offering.addProperty("hardwareId", instanceId);
    offering.addProperty("location", chs.serviceId);
    offering.addProperty("region", locationCode);

    /* Performance */
    Integer performance = CloudHarmonySPECint.getSPECint(providerOriginalName, instanceId);
    if (performance != null) {
        offering.addProperty("performance", performance.toString());
    }//from  w w  w  .  j a  v  a2 s.  c om
    /* sla */
    if (chs.sla != null) {
        offering.addProperty("availability", this.slaFormat.format(chs.sla / 100.0));
    }

    /* location */
    offering.addProperty("country", expandCountryCode((String) (locationInformation.get("country"))));
    offering.addProperty("city", expandCountryCode((String) (locationInformation.get("city"))));

    JSONArray pricings = (JSONArray) computeInstanceType.get("pricing");

    if (pricings.size() > 0) {
        JSONObject pricing = ((JSONObject) ((JSONArray) computeInstanceType.get("pricing")).get(0));

        Object price = pricing.get("price");
        Object currency = pricing.get("currency");
        Object priceInterval = pricing.get("priceInterval");

        offering.addProperty("cost", price.toString() + " " + currency.toString() + "/" + priceInterval);
    }

    /* compute instance type - numbers */
    for (String k : this.numbers.keySet()) {
        if (computeInstanceType.containsKey(k)) {
            Object vv = computeInstanceType.get(k);
            offering.addProperty(this.numbers.get(k), vv.toString());
        }
    }

    /* compute instance type - strings */
    if (computeInstanceType != null) {
        for (String k : this.strings.keySet()) {
            if (computeInstanceType.containsKey(k)) {
                String v = (String) (computeInstanceType.get(k));
                offering.addProperty(this.strings.get(k), v);
            }
        }
    }

    return offering;
}

From source file:at.uni_salzburg.cs.ckgroup.cpcc.mapper.algorithms.RandomTaskGenerator.java

private void mergeVehicleData(IVirtualVehicleInfo vehicleInfo)
        throws IOException, IllegalStateException, ParseException {

    String url = vehicleInfo.getEngineUrl() + "/json/vehicleDetails/" + vehicleInfo.getVehicleName();

    HttpGet httpGet = new HttpGet(url);
    HttpClient httpclient = new DefaultHttpClient();
    HttpResponse response = httpclient.execute(httpGet);

    HttpEntity entity = response.getEntity();
    if (entity != null) {
        JSONParser parser = new JSONParser();
        JSONObject vv = (JSONObject) parser.parse(new InputStreamReader(entity.getContent()));

        String vvId = (String) vv.get("vehicle.id");
        VirtualVehicleInfo info = vvInfo.get(vvId);
        if (info == null) {
            LOG.error("Virtual Vehicle " + vvId + " not known! URL=" + url);
            return;
        }/*  w  w w.ja va 2 s  .  c  o m*/

        JSONArray tasks = (JSONArray) vv.get("tasks");
        int k = 0;
        for (ActionPoint ap : info.actionPoints) {
            if (k >= tasks.size()) {
                break;
            }
            JSONObject actionPoint = (JSONObject) tasks.get(k++);
            JSONArray actions = (JSONArray) actionPoint.get("actions");

            long time = 0;
            for (int j = 0; j < actions.size(); ++j) {
                JSONObject a = (JSONObject) actions.get(j);
                Long newTime = (Long) a.get("time");
                if (newTime != null && newTime > time) {
                    time = newTime;
                }
            }

            if (time > 0) {
                ap.completedTime = time;
            }
        }
    }
}

From source file:com.apifest.doclet.integration.tests.DocletTest.java

@Test
public void check_what_doclet_will_generate_correct_metrics_request_parameters() throws Exception {
    // GIVEN/*from w  w w .  j  a va 2 s. c  o  m*/
    String parserFilePath = "./all-mappings-docs.json";
    Map<String, RequestParamDocumentation> correctNameToTypeMap = new HashMap<String, RequestParamDocumentation>();
    addRequestParamToMap("ids", "string", "** user ids goes here **", true, correctNameToTypeMap);
    addRequestParamToMap("fields", "list", "** The keys from result json can be added as filter**", false,
            correctNameToTypeMap);
    // WHEN
    runDoclet();
    // THEN
    JSONParser parser = new JSONParser();
    FileReader fileReader = null;
    try {
        fileReader = new FileReader(parserFilePath);
        JSONObject json = (JSONObject) parser.parse(fileReader);
        JSONArray arr = (JSONArray) json.get("endpoints");
        JSONObject obj = (JSONObject) arr.get(1);

        JSONArray reqParam = (JSONArray) obj.get("requestParams");

        for (int i = 0; i < reqParam.size(); i++) {
            JSONObject currentParam = (JSONObject) reqParam.get(i);
            String currentName = (String) currentParam.get("name");
            RequestParamDocumentation correctCurrentParam = correctNameToTypeMap.get(currentName);
            Assert.assertEquals((String) currentParam.get("type"), correctCurrentParam.getType());
            Assert.assertEquals((String) currentParam.get("name"), correctCurrentParam.getName());
            Assert.assertEquals((String) currentParam.get("description"), correctCurrentParam.getDescription());
            Assert.assertEquals(currentParam.get("required"), correctCurrentParam.isRequired());
            // System.out.println(currentParam.get("name"));
            // System.out.println(correctCurrentParam.getName());
        }
    } finally {
        if (fileReader != null) {
            fileReader.close();
        }
        deleteJsonFile(parserFilePath);
    }
}

From source file:com.apifest.doclet.integration.tests.DocletTest.java

@Test
public void check_what_doclet_will_generate_correct_stream_request_parameters() throws Exception {
    // GIVEN//from w ww  . j a  v a 2 s. c o m
    String parserFilePath = "./all-mappings-docs.json";
    Map<String, RequestParamDocumentation> correctNameToTypeMap = new HashMap<String, RequestParamDocumentation>();
    addRequestParamToMap("ids", "string", "** user ids goes here **", true, correctNameToTypeMap);
    addRequestParamToMap("fields", "list", "** The keys from result json can be added as filter**", false,
            correctNameToTypeMap);
    addRequestParamToMap("since", "integer", "** since is optional parameter**", false, correctNameToTypeMap);
    addRequestParamToMap("until", "integer", "** until is optional parameter**", false, correctNameToTypeMap);
    // WHEN
    runDoclet();
    // THEN
    JSONParser parser = new JSONParser();
    FileReader fileReader = null;
    try {
        fileReader = new FileReader(parserFilePath);
        JSONObject json = (JSONObject) parser.parse(fileReader);
        JSONArray arr = (JSONArray) json.get("endpoints");
        JSONObject obj = (JSONObject) arr.get(0);

        JSONArray reqParam = (JSONArray) obj.get("requestParams");

        for (int i = 0; i < reqParam.size(); i++) {
            JSONObject currentParam = (JSONObject) reqParam.get(i);
            String currentName = (String) currentParam.get("name");
            RequestParamDocumentation correctCurrentParam = correctNameToTypeMap.get(currentName);
            Assert.assertEquals((String) currentParam.get("type"), correctCurrentParam.getType());
            Assert.assertEquals((String) currentParam.get("name"), correctCurrentParam.getName());
            Assert.assertEquals((String) currentParam.get("description"), correctCurrentParam.getDescription());
            Assert.assertEquals(currentParam.get("required"), correctCurrentParam.isRequired());
        }
    } finally {
        if (fileReader != null) {
            fileReader.close();
        }
        deleteJsonFile(parserFilePath);
    }
}

From source file:com.apifest.doclet.integration.tests.DocletTest.java

@Test
public void check_what_doclet_will_generate_correct_stream_result_parameters() throws Exception {
    // GIVEN/* www  . j a v a2s. c o m*/
    String parserFilePath = "./all-mappings-docs.json";
    Map<String, ResultParamDocumentation> resNameToTypeMap = new HashMap<String, ResultParamDocumentation>();
    addResultParamToMap("tw_id", "integer", "The ** tw_id ** description", true, resNameToTypeMap);
    addResultParamToMap("in_reply_to_screen_name", "string", "The ** in_reply_to_screen_name ** description",
            true, resNameToTypeMap);
    addResultParamToMap("request_handle", "string", "The ** request_handle ** description", true,
            resNameToTypeMap);
    addResultParamToMap("in_reply_to_status_id", "string", "The ** in_reply_to_status_id ** description", true,
            resNameToTypeMap);
    addResultParamToMap("channel", "string", "The ** channel ** description", true, resNameToTypeMap);
    // WHEN
    runDoclet();
    // THEN
    JSONParser parser = new JSONParser();
    FileReader fileReader = null;
    try {
        fileReader = new FileReader(parserFilePath);
        JSONObject json = (JSONObject) parser.parse(fileReader);
        JSONArray arr = (JSONArray) json.get("endpoints");
        JSONObject obj = (JSONObject) arr.get(0);

        JSONArray resParam = (JSONArray) obj.get("resultParams");
        for (int i = 0; i < resParam.size(); i++) {
            JSONObject currentParam = (JSONObject) resParam.get(i);
            String currentName = (String) currentParam.get("name");
            ResultParamDocumentation correctCurrentParam = resNameToTypeMap.get(currentName);
            Assert.assertEquals((String) currentParam.get("type"), correctCurrentParam.getType());
            Assert.assertEquals((String) currentParam.get("name"), correctCurrentParam.getName());
            Assert.assertEquals((String) currentParam.get("description"), correctCurrentParam.getDescription());
            Assert.assertEquals(currentParam.get("required"), correctCurrentParam.isRequired());
        }
    } finally {
        if (fileReader != null) {
            fileReader.close();
        }
        deleteJsonFile(parserFilePath);
    }
}

From source file:eu.juniper.MonitoringLib.java

private ArrayList<String> readJson(ArrayList<String> elementsList, JSONObject jsonObject, PrintWriter writer,
        String TagName) throws FileNotFoundException, IOException, ParseException {
    String appId = "";
    if (jsonObject.get(TagName) == null) {
        elementsList.add("null");
    } else {/*from w  w w.  ja  v a  2  s .  co m*/
        String Objectscontent = jsonObject.get(TagName).toString();
        if (Objectscontent.startsWith("[{") && Objectscontent.endsWith("}]")) {
            JSONArray jsonArray = (JSONArray) jsonObject.get(TagName);

            for (int temp = 0; temp < jsonArray.size(); temp++) {
                System.out.println("Array:" + jsonArray.toJSONString());
                JSONObject jsonObjectResult = (JSONObject) jsonArray.get(temp);
                System.out.println("Result:" + jsonObjectResult.toJSONString());

                Set<String> jsonObjectResultKeySet = jsonObjectResult.keySet();
                System.out.println("KeySet:" + jsonObjectResultKeySet.toString());

                for (String s : jsonObjectResultKeySet) {
                    System.out.println(s);
                    readJson(elementsList, jsonObjectResult, writer, s);
                }
            }
        } else {
            appId = jsonObject.get(TagName).toString();
            elementsList.add(appId);
        }
    }
    return elementsList;
}

From source file:com.apifest.doclet.integration.tests.DocletTest.java

@Test
public void check_what_doclet_will_generate_correct_metrics_result_parameters() throws Exception {
    // GIVEN//from   ww  w .  j  a v a 2 s . co m
    String parserFilePath = "./all-mappings-docs.json";
    Map<String, ResultParamDocumentation> resNameToTypeMap = new HashMap<String, ResultParamDocumentation>();
    addResultParamToMap("channel", "string", "The **channel** description", true, resNameToTypeMap);
    addResultParamToMap("updated_time", "string", "The **updated_time** description", true, resNameToTypeMap);
    addResultParamToMap("request_handle", "string", "The **request_handle** description", true,
            resNameToTypeMap);
    addResultParamToMap("sentiment.score", "string", "The **sentiment_score** description", true,
            resNameToTypeMap);
    addResultParamToMap("sentiment.positive", "string", "The **sentiment_positive** description", true,
            resNameToTypeMap);
    addResultParamToMap("sentiment.neutral", "string", "The **sentiment_neutral** description", true,
            resNameToTypeMap);
    addResultParamToMap("sentiment.negative", "string", "The **sentiment_negative** description", true,
            resNameToTypeMap);
    addResultParamToMap("engagement.replies", "integer", "The **engagement_replies** description", true,
            resNameToTypeMap);
    addResultParamToMap("engagement.tweets", "integer", "The **engagement_tweets** description", true,
            resNameToTypeMap);
    // WHEN
    runDoclet();
    // THEN
    JSONParser parser = new JSONParser();
    FileReader fileReader = null;
    try {
        fileReader = new FileReader(parserFilePath);
        JSONObject json = (JSONObject) parser.parse(fileReader);
        JSONArray arr = (JSONArray) json.get("endpoints");
        JSONObject obj = (JSONObject) arr.get(1);

        JSONArray resParam = (JSONArray) obj.get("resultParams");
        for (int i = 0; i < resParam.size(); i++) {
            JSONObject currentParam = (JSONObject) resParam.get(i);
            String currentName = (String) currentParam.get("name");
            ResultParamDocumentation correctCurrentParam = resNameToTypeMap.get(currentName);
            Assert.assertEquals((String) currentParam.get("type"), correctCurrentParam.getType());
            Assert.assertEquals((String) currentParam.get("name"), correctCurrentParam.getName());
            Assert.assertEquals((String) currentParam.get("description"), correctCurrentParam.getDescription());
            Assert.assertEquals(currentParam.get("required"), correctCurrentParam.isRequired());

        }
    } finally {
        if (fileReader != null) {
            fileReader.close();
        }
        deleteJsonFile(parserFilePath);
    }
}

From source file:importer.handler.post.stages.StageThreeXML.java

boolean verifyCorCode(String stil, String text) {
    JSONObject jObj = (JSONObject) JSONValue.parse(stil);
    JSONArray ranges = (JSONArray) jObj.get(JSONKeys.RANGES);
    int offset = 0;
    for (int i = 0; i < ranges.size(); i++) {
        JSONObject range = (JSONObject) ranges.get(i);
        offset += ((Number) range.get("reloff")).intValue();
        int len = ((Number) range.get("len")).intValue();
        if (offset + len > text.length())
            return false;
    }//from   w w w  .  j av a  2s.com
    return true;
}

From source file:coria2015.server.JsonRPCMethods.java

private int convert(Object p, Arguments description, int score, Object args[], int index) {
        Object o;/*  w w w . j a  v  a  2s.co  m*/
        if (p instanceof JSONObject)
            // If p is a map, then use the json name of the argument
            o = ((JSONObject) p).get(description.getArgument(index).name());

        else if (p instanceof JSONArray)
            // if it is an array, then map it
            o = ((JSONArray) p).get(index);
        else {
            // otherwise, suppose it is a one value array
            if (index > 0)
                return Integer.MIN_VALUE;
            o = p;
        }

        final Class aType = description.getType(index);

        if (o == null) {
            if (description.getArgument(index).required())
                return Integer.MIN_VALUE;

            return score - 10;
        }

        if (aType.isArray()) {
            if (o instanceof JSONArray) {
                final JSONArray array = (JSONArray) o;
                final Object[] arrayObjects = args != null ? new Object[array.size()] : null;
                Arguments arguments = new Arguments() {
                    @Override
                    public RPCArgument getArgument(int i) {
                        return new RPCArrayArgument();
                    }

                    @Override
                    public Class<?> getType(int i) {
                        return aType.getComponentType();
                    }

                    @Override
                    public int size() {
                        return array.size();
                    }
                };
                for (int i = 0; i < array.size() && score > Integer.MIN_VALUE; i++) {
                    score = convert(array.get(i), arguments, score, arrayObjects, i);
                }
                return score;
            }
            return Integer.MIN_VALUE;
        }

        if (aType.isAssignableFrom(o.getClass())) {
            if (args != null)
                args[index] = o;
            return score;
        }

        if (o.getClass() == Long.class && aType == Integer.class) {
            if (args != null)
                args[index] = ((Long) o).intValue();
            return score - 1;
        }

        return Integer.MIN_VALUE;
    }