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:at.ac.tuwien.dsg.depic.common.utils.RestfulWSClient.java

public String getJCMetricValue(String metricID, String uri) {

    String metricValue = "";

    try {/*www . j ava 2  s  .  co  m*/

        Client client = Client.create();

        String jcURL = uri + metricID;

        WebResource webResource = client.resource(jcURL);

        ClientResponse response = webResource

                .accept("application/json").get(ClientResponse.class);
        if (response.getStatus() != 200) {
            throw new RuntimeException("Failed : HTTP error code : " + response.getStatus());
        }

        String output = response.getEntity(String.class);
        System.out.println("\n============getResponse============");
        System.out.println(output);

        JSONObject json = (JSONObject) new JSONParser().parse(output);
        String allMetricsStr = json.get("values").toString();

        System.out.println(allMetricsStr);

        try {

            JSONArray nameArray = (JSONArray) new JSONParser().parse(allMetricsStr);
            System.out.println(nameArray.size());
            for (Object js : nameArray) {
                JSONObject element = (JSONObject) js;

                if (metricID.equals(element.get("metricID"))) {
                    metricValue = element.get("value").toString();
                }

            }

        } catch (Exception e) {

        }

    } catch (Exception e) {

    }

    return metricValue;

}

From source file:at.ac.tuwien.dsg.depic.common.utils.RestfulWSClient.java

public String callJcatascopiaMetricWS(String metricName, String uri, String agentID) {

    String metricID = "";

    try {// w  w  w  . j a  v  a 2s  .  co  m

        Client client = Client.create();

        //WebResource webResource = client.resource("http://128.130.172.230:8080/JCatascopia-Web/restAPI/metrics/29e6550085ae4ee193532cd51fae39c1:pgActiveConnections");
        uri = uri.replaceAll("AGENTID", agentID);

        System.out.println("CALLING: " + uri);

        WebResource webResource = client.resource(uri);

        ClientResponse response = webResource

                .accept("application/json").get(ClientResponse.class);
        if (response.getStatus() != 200) {
            throw new RuntimeException("Failed : HTTP error code : " + response.getStatus());
        }

        String output = response.getEntity(String.class);
        System.out.println("\n============getResponse============");
        System.out.println(output);

        JSONObject json = (JSONObject) new JSONParser().parse(output);
        String allMetricsStr = json.get("metrics").toString();

        System.out.println(allMetricsStr);

        try {

            JSONArray nameArray = (JSONArray) new JSONParser().parse(allMetricsStr);
            System.out.println(nameArray.size());
            for (Object js : nameArray) {
                JSONObject element = (JSONObject) js;

                if (metricName.equals(element.get("name"))) {
                    metricID = element.get("metricID").toString();
                }

            }

        } catch (Exception e) {

        }

    } catch (Exception e) {

    }

    return metricID;

}

From source file:org.opencastproject.adminui.endpoint.TasksEndpointTest.java

@Test
public void testGetProcessing() throws ParseException, IOException {
    InputStream stream = TasksEndpointTest.class.getResourceAsStream("/taskProcessing.json");
    InputStreamReader reader = new InputStreamReader(stream);
    JSONArray expected = (JSONArray) new JSONParser().parse(reader);
    JSONArray actual = (JSONArray) parser
            .parse(given().queryParam("tags", "archive").expect().log().all().statusCode(HttpStatus.SC_OK)
                    .contentType(ContentType.JSON).when().get(rt.host("/processing.json")).asString());

    Assert.assertEquals(expected.size(), actual.size());
}

From source file:de.fhg.fokus.odp.portal.datasets.searchresults.BrowseDataSetsSearchResults.java

/**
 * This method adds the screenname of all users, which commented this
 * dataset, to a String array and returns this array.
 * /*from   w  w  w.  ja  v a 2 s. c  o  m*/
 * @param comments
 *            the {@link JSONArray}
 * @return array filled with screennames of commenters
 */
private String[] getCommentersScreennames(JSONArray comments) {

    String[] commentersNames = new String[comments.size()];
    for (int i = 0; i < comments.size(); i++) {
        String userId = (String) ((JSONObject) comments.get(i)).get("userId");
        try {
            commentersNames[i] = UserLocalServiceUtil.getUserById(Long.parseLong(userId)).getScreenName();
        } catch (NumberFormatException e) {
            LOGGER.error(e.getLocalizedMessage(), e);
        } catch (PortalException e) {
            LOGGER.error(e.getLocalizedMessage(), e);
        } catch (SystemException e) {
            LOGGER.error(e.getLocalizedMessage(), e);
        }
    }
    return commentersNames;
}

From source file:fr.bmartel.speedtest.test.SpeedTestServerTest.java

@Test
public void serverListTest() throws IOException, ParseException, TimeoutException {

    initSocket();/*from   w w w  .  ja  v  a2 s  . c  om*/

    final URL url = getClass().getResource("/" + TestCommon.SERVER_LIST_FILENAME);

    final Object obj = new JSONParser().parse(new FileReader(url.getPath()));

    final JSONArray servers = (JSONArray) obj;

    for (int i = 0; i < servers.size(); i++) {

        final JSONObject serverObj = (JSONObject) servers.get(i);

        if (serverObj.containsKey("host")) {

            final String host = serverObj.get("host").toString();

            if (serverObj.containsKey("download")) {

                final JSONArray downloadEndpoints = (JSONArray) serverObj.get("download");

                for (int j = 0; j < downloadEndpoints.size(); j++) {

                    final JSONObject downloadEndpoint = (JSONObject) downloadEndpoints.get(j);

                    if (downloadEndpoint.containsKey("protocol")) {

                        final String protocol = downloadEndpoint.get("protocol").toString();

                        if (downloadEndpoint.containsKey("uri")) {

                            final String uri = downloadEndpoint.get("uri").toString();

                            switch (protocol) {
                            case "http":
                                System.out.println("[download] HTTP - testing " + host + " with uri " + uri);
                                mWaiter = new Waiter();
                                mSocket.startDownload(host, uri);
                                mWaiter.await(TestCommon.WAITING_TIMEOUT_VERY_LONG_OPERATION, SECONDS);
                                mWaiter = new Waiter();
                                mSocket.forceStopTask();
                                mWaiter.await(TestCommon.WAITING_TIMEOUT_VERY_LONG_OPERATION, SECONDS);
                                break;
                            case "ftp":

                                String username = SpeedTestConst.FTP_DEFAULT_USER;
                                String password = SpeedTestConst.FTP_DEFAULT_PASSWORD;

                                if (downloadEndpoint.containsKey("username")) {
                                    username = downloadEndpoint.get("username").toString();
                                }
                                if (downloadEndpoint.containsKey("password")) {
                                    password = downloadEndpoint.get("password").toString();
                                }
                                System.out.println("[download] FTP - testing " + host + " with uri " + uri);
                                mWaiter = new Waiter();
                                mSocket.startFtpDownload(host, SpeedTestConst.FTP_DEFAULT_PORT, uri, username,
                                        password);
                                mWaiter.await(TestCommon.WAITING_TIMEOUT_VERY_LONG_OPERATION, SECONDS);
                                mWaiter = new Waiter();
                                mSocket.forceStopTask();
                                mWaiter.await(TestCommon.WAITING_TIMEOUT_VERY_LONG_OPERATION, SECONDS);
                                break;
                            default:
                                break;
                            }

                        } else {
                            Assert.fail("download for host " + host + " has no uri");
                        }
                    } else {
                        Assert.fail("download for host " + host + " has no protocol");
                    }
                }
            }
            if (serverObj.containsKey("upload")) {

                final JSONArray uploadEndpoints = (JSONArray) serverObj.get("upload");

                for (int j = 0; j < uploadEndpoints.size(); j++) {

                    final JSONObject uploadEndpoint = (JSONObject) uploadEndpoints.get(j);

                    if (uploadEndpoint.containsKey("protocol")) {

                        final String protocol = uploadEndpoint.get("protocol").toString();

                        if (uploadEndpoint.containsKey("uri")) {

                            final String uri = uploadEndpoint.get("uri").toString();

                            switch (protocol) {
                            case "http":
                                System.out.println("[upload] HTTP - testing " + host + " with uri " + uri);
                                mWaiter = new Waiter();
                                mSocket.startUpload(host, uri, TestCommon.FILE_SIZE_LARGE);
                                mWaiter.await(TestCommon.WAITING_TIMEOUT_VERY_LONG_OPERATION, SECONDS);
                                mWaiter = new Waiter();
                                mSocket.forceStopTask();
                                mWaiter.await(TestCommon.WAITING_TIMEOUT_VERY_LONG_OPERATION, SECONDS);
                                break;
                            case "ftp":
                                String username = SpeedTestConst.FTP_DEFAULT_USER;
                                String password = SpeedTestConst.FTP_DEFAULT_PASSWORD;

                                if (uploadEndpoint.containsKey("username")) {
                                    username = uploadEndpoint.get("username").toString();
                                }
                                if (uploadEndpoint.containsKey("password")) {
                                    password = uploadEndpoint.get("password").toString();
                                }
                                System.out.println("[upload] FTP - testing " + host + " with uri " + uri);
                                final String fileName = generateFileName() + ".txt";
                                mWaiter = new Waiter();
                                mSocket.startFtpUpload(host, SpeedTestConst.FTP_DEFAULT_PORT,
                                        uri + "/" + fileName, TestCommon.FILE_SIZE_LARGE, username, password);
                                mWaiter.await(TestCommon.WAITING_TIMEOUT_VERY_LONG_OPERATION, SECONDS);
                                mWaiter = new Waiter();
                                mSocket.forceStopTask();
                                mWaiter.await(TestCommon.WAITING_TIMEOUT_VERY_LONG_OPERATION, SECONDS);
                                break;
                            default:
                                break;
                            }

                        } else {
                            Assert.fail("upload for host " + host + " has no uri");
                        }

                    } else {
                        Assert.fail("upload for host " + host + " has no protocol");
                    }
                }
            }
        }
    }

    mSocket.clearListeners();
}

From source file:com.sforce.cd.apexUnit.client.codeCoverage.CodeCoverageComputer.java

/**
 * This method is not used currently Calculate code coverage results for the
 * Apex classes using Tooling API's This method is intended to provide code
 * coverage at method level for each class . This indicates which exact
 * method needs more coverage//from  w w w  . j a  v a  2 s.com
 * 
 * @return
 */
public void calculateCodeCoverageUsingToolingAPI(String classArrayAsStringForQuery) {
    int classCounter = 0;
    String relativeServiceURL = "/services/data/v" + SUPPORTED_VERSION + "/tooling";
    String soqlcc = QueryConstructor.getClassLevelCodeCoverage(classArrayAsStringForQuery);
    LOG.debug("OAuthTokenGenerator.getOrgToken() : " + OAuthTokenGenerator.getOrgToken());
    JSONObject responseJsonObject = null;
    responseJsonObject = WebServiceInvoker.doGet(relativeServiceURL, soqlcc, OAuthTokenGenerator.getOrgToken());

    if (responseJsonObject != null) {
        String responseStr = responseJsonObject.toJSONString();
        LOG.debug(responseStr);
        JSONArray recordObject = (JSONArray) responseJsonObject.get("records");
        for (int i = 0; i < recordObject.size(); ++i) {
            classCounter++;
            // The object below is one record from the ApexCodeCoverage
            // object
            JSONObject rec = (JSONObject) recordObject.get(i);

            int coveredLines = Integer.valueOf((String) rec.get("NumLinesCovered").toString());
            int unCoveredLines = Integer.valueOf((String) rec.get("NumLinesUncovered").toString());
            // ApexTestClassId - The ID of the test class.
            String apexTestClassID = (String) rec.get("ApexTestClassId").toString();
            // ApexClassOrTriggerId - The ID of the class or trigger under
            // test.
            String apexClassorTriggerId = (String) rec.get("ApexClassOrTriggerId").toString();
            String testMethodName = (String) rec.get("TestMethodName").toString();
            LOG.info("Record number # " + classCounter + " : coveredLines : " + coveredLines
                    + " : unCoveredLines : " + unCoveredLines + " : apexTestClassID : " + apexTestClassID
                    + " : apexClassorTriggerId : " + apexClassorTriggerId + " : testMethodName : "
                    + testMethodName);

        }

    }
}

From source file:net.gtl.movieanalytics.data.InfoStore.java

private void readJsonFile(String path) {
    JSONParser parser = new JSONParser();

    try {//from  w w w  .  j  av a2s .  c  om
        JSONObject root = (JSONObject) parser.parse(new FileReader(path));
        double testRecordPercentage = (Double) root.get("testRecordPercentage");
        this.setTestRecordPercentage(testRecordPercentage);

        JSONArray tolerances = (JSONArray) root.get("errorToleranceRate");

        double errorToleranceRate[] = new double[tolerances.size()];
        Iterator<Double> iter = tolerances.iterator();
        int i = 0;
        while (iter.hasNext()) {
            errorToleranceRate[i] = iter.next();
            i++;
        }
        this.setErrorToleranceRate(errorToleranceRate);
        String tableName = (String) root.get("tableName");
        this.setTableName(tableName);
        String sourceTableName = (String) root.get("sourceTableName");
        this.setSourceTableName(sourceTableName);
        String resultFieldName = (String) root.get("resultFieldName");
        this.setResultFieldName(resultFieldName);

        JSONObject tdObj = (JSONObject) root.get("testDataSource");
        boolean isNew = (Boolean) tdObj.get("newGenerated");
        String tdPath = (String) tdObj.get("saveToFilePath");
        if ((tdPath == null) || (tdPath.equals(""))) {
            isNew = true;
        }
        this.setNewGeneratedTestDataSet(isNew);
        this.setTestDataSetIdFilePath(tdPath);

        String dbHost = (String) root.get("dbHost");
        this.setDbHost(dbHost);

        JSONArray features = (JSONArray) root.get("features");
        Iterator<JSONObject> iterator = features.iterator();
        while (iterator.hasNext()) {
            JSONObject featureObj = iterator.next();
            String name = (String) featureObj.get("name");
            String type = (String) featureObj.get("type");
            DBFieldType fType = DBFieldType.valueOf(type);
            int subNum = ((Long) featureObj.get("subNum")).intValue();

            FeatureDimension feature = new FeatureDimension(fType, name, subNum);
            this.addFeature(feature);
        }

        JSONArray fm = (JSONArray) root.get("featuresInModel");
        List<Feature> featuresInModel = new ArrayList<Feature>();
        Iterator<JSONObject> iterS = fm.iterator();
        while (iterS.hasNext()) {
            JSONObject currentFeature = iterS.next();
            Boolean isEnabled = (Boolean) currentFeature.get("enabled");
            if ((isEnabled != null) && (isEnabled.booleanValue() == false)) {
                continue;
            }

            String featureName = (String) currentFeature.get("name");
            Feature feature = new Feature(featureName);

            JSONArray functions = (JSONArray) currentFeature.get("functions");
            if (functions != null) {
                List<FeatureFunction> functionList = new ArrayList<FeatureFunction>();
                Iterator<JSONObject> funs = functions.iterator();
                while (funs.hasNext()) {
                    JSONObject function = funs.next();
                    String functionName = (String) function.get("name");
                    FeatureFunction featureFunction = new FeatureFunction(functionName);
                    JSONArray args = (JSONArray) function.get("arguments");

                    if ((args != null) && (args.size() > 0)) {
                        double arguments[] = new double[tolerances.size()];
                        Iterator<Double> iterA = args.iterator();
                        i = 0;
                        while (iterA.hasNext()) {
                            arguments[i] = iterA.next();
                            i++;
                        }
                        featureFunction.setArguments(arguments);
                    }
                    functionList.add(featureFunction);
                }
                feature.setFunctions(functionList);
            }
            featuresInModel.add(feature);
        }

        this.setFeaturesInModel(featuresInModel);

    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:functionaltests.RestSchedulerJobTaskTest.java

@Test
public void testJobTaskStates() throws Exception {
    String jobId = submitDefaultJob().value();
    String resource = "jobs/" + jobId + "/taskstates";
    String schedulerUrl = getResourceUrl(resource);
    HttpGet httpGet = new HttpGet(schedulerUrl);
    setSessionHeader(httpGet);//from  ww  w .j  av a  2s .c  o  m
    HttpResponse response = executeUriRequest(httpGet);
    assertHttpStatusOK(response);
    JSONObject jsonObject = toJsonObject(response);
    JSONArray jsonArray = (JSONArray) jsonObject.get("list");
    assertTrue(jsonArray.size() > 0);
}

From source file:de.fhg.fokus.odp.portal.datasets.searchresults.BrowseDataSetsSearchResults.java

/**
 * This method adds for each package in our {@link JSONArray} the correct
 * number of comments and ratings in a specific array. These arrays will be
 * saved our {@link RenderRequest};/*  www. j av a2 s  .co m*/
 * 
 * @param request
 *            the {@link RenderRequest}
 * @param arr
 *            the {@link JSONArray}
 */
private void addNumberOfRatingsAndCommentsToRequest(RenderRequest request, JSONArray arr) {
    int[] ratingsNumberArray = new int[arr.size()];
    int[] commentsNumberArray = new int[arr.size()];
    for (int i = 0; i < arr.size(); i++) {
        JSONObject dataset = (JSONObject) arr.get(i);
        JSONObject extras = (JSONObject) dataset.get("extras");
        // don't have any extras -> dont have ratings and comments
        if (extras == null) {
            ratingsNumberArray[i] = 0;
            commentsNumberArray[i] = 0;
        } else {
            String rating = (String) extras.get("ratings");
            String comments = (String) extras.get(BrowseDataSetsSearchResults.COMMENTS_STRING);
            // don't have any ratings -> ratings = 0
            if (rating == null) {
                ratingsNumberArray[i] = 0;
            } else {
                int ratingsNumber = countNumberofOccurences(rating, '{');
                ratingsNumberArray[i] = ratingsNumber;
            }
            // don't have any comments -> ratings = 0
            if (comments == null) {
                commentsNumberArray[i] = 0;
            } else {
                int commentsNumber = countNumberofOccurences(comments, '{');
                commentsNumberArray[i] = commentsNumber;
            }
        }
    }

    request.setAttribute("ratingsNumber", ratingsNumberArray);
    request.setAttribute("commentsNumber", commentsNumberArray);
}

From source file:com.alvexcore.repo.documents.generation.ExportDataListToXlsx.java

protected Workbook createXlsx(JSONArray rows, String XLS_SHEET_NAME) {

    Workbook wb = new XSSFWorkbook();
    CreationHelper createHelper = wb.getCreationHelper();
    Sheet sheet = wb.createSheet(XLS_SHEET_NAME);

    for (int k = 0; k < rows.size(); k++) {
        Row row = sheet.createRow((short) k);
        JSONArray cells = (JSONArray) rows.get(k);
        for (int c = 0; c < cells.size(); c++) {
            String displayValue;/* w  w  w. j a  va  2s.c o  m*/
            Object item = cells.get(c);
            if (item == null)
                displayValue = I18NUtil.getMessage("label.empty");
            else if (item instanceof Boolean)
                displayValue = (Boolean) item ? I18NUtil.getMessage("label.yes")
                        : I18NUtil.getMessage("label.no");
            else
                displayValue = item.toString();
            row.createCell(c).setCellValue(createHelper.createRichTextString(displayValue));
        }
    }

    return wb;
}