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:formatter.handler.post.FormatterPostHandler.java

/**
 * Process a field we recognise/*from w  w w.  j a  v  a2s . com*/
 * @param fieldName the field's name
 * @param contents its contents
 */
void processField(String fieldName, String contents) {
    //System.out.println("Received field "+fieldName);
    if (fieldName.equals(Params.DOCID))
        docid = contents;
    if (fieldName.equals(Params.VERSION1))
        version1 = contents;
    else if (fieldName.equals(Params.USERDATA)) {
        String key = "I tell a settlers tale of the old times";
        int klen = key.length();
        char[] data = Base64.decode(contents);
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < data.length; i++)
            sb.append((char) (data[i] ^ key.charAt(i % klen)));
        String json = sb.toString();
        //            System.out.println( "USERDATA: decoded json data="+json);
        userdata = (JSONObject) JSONValue.parse(json);
        //            System.out.println("json="+json);
        //            System.out.println( "user was "+userdata.get(JSONKeys.NAME));
        JSONArray roles = (JSONArray) userdata.get(JSONKeys.ROLES);
        //            if ( roles.size()>0 )
        //                System.out.println("role was "+roles.get(0));
        if (roles != null)
            for (int i = 0; i < roles.size(); i++)
                if (((String) roles.get(i)).equals("editor"))
                    isEditor = true;
    }
}

From source file:com.fujitsu.dc.test.jersey.ODataCommon.java

/**
 * $link???./*from  w w w  .j ava 2  s .  c om*/
 * @param json ?
 * @param uri uri?
 */
public static void checkLinResponseBody(final JSONObject json, final ArrayList<String> uri) {
    String value;
    JSONObject jsonResult;

    // results
    JSONArray results = (JSONArray) ((JSONObject) json.get("d")).get("results");

    assertEquals(uri.size(), results.size());
    for (Object result : results) {
        jsonResult = (JSONObject) result;
        value = (String) jsonResult.get("uri");
        assertTrue("expected uri doesn't contain [" + value + "]", uri.contains(value));
    }
}

From source file:com.fujitsu.dc.test.jersey.ODataCommon.java

/**
 * ???./*  w ww  . j a va 2s. c  o m*/
 * @param json ?
 * @param uri ?
 */
public static void checkCommonResponseUri(final JSONObject json, final ArrayList<String> uri) {
    String value;
    int count = 0;
    JSONObject jsonResult;

    // results
    JSONArray results = (JSONArray) ((JSONObject) json.get("d")).get("results");

    assertEquals(uri.size(), results.size());
    for (Object result : results) {
        jsonResult = (JSONObject) result;
        JSONObject resMetadata = (JSONObject) jsonResult.get("__metadata");
        value = (String) resMetadata.get("uri");
        assertEquals(uri.get(count++), value);
    }
}

From source file:com.capitalone.dashboard.client.team.TeamDataClientImpl.java

/**
 * Updates the MongoDB with a JSONArray received from the source system
 * back-end with story-based data.//  w ww. j  a  va2s.  c o m
 * 
 * @param tmpMongoDetailArray
 *            A JSON response in JSONArray format from the source system
 * @param featureCollector
 * @return
 * @return
 */
protected void updateMongoInfo(JSONArray tmpMongoDetailArray) {
    try {
        JSONObject dataMainObj = new JSONObject();
        for (int i = 0; i < tmpMongoDetailArray.size(); i++) {
            if (dataMainObj != null) {
                dataMainObj.clear();
            }
            dataMainObj = (JSONObject) tmpMongoDetailArray.get(i);
            ScopeOwnerCollectorItem team = new ScopeOwnerCollectorItem();

            /*
             * Checks to see if the available asset state is not active from
             * the V1 Response and removes it if it exists and not active:
             */
            if (!TOOLS.sanitizeResponse((String) dataMainObj.get("AssetState")).equalsIgnoreCase("Active")) {

                this.removeInactiveScopeOwnerByTeamId(TOOLS.sanitizeResponse((String) dataMainObj.get("_oid")));

            } else {
                boolean deleted = this
                        .removeExistingEntity(TOOLS.sanitizeResponse((String) dataMainObj.get("_oid")));
                // Id
                if (deleted) {
                    team.setId(this.getOldTeamId());
                    team.setEnabled(this.isOldTeamEnabledState());
                }

                // collectorId
                team.setCollectorId(featureCollectorRepository.findByName(Constants.VERSIONONE).getId());

                // teamId
                team.setTeamId(TOOLS.sanitizeResponse((String) dataMainObj.get("_oid")));

                // name
                team.setName(TOOLS.sanitizeResponse((String) dataMainObj.get("Name")));

                // changeDate;
                team.setChangeDate(
                        TOOLS.toCanonicalDate(TOOLS.sanitizeResponse((String) dataMainObj.get("ChangeDate"))));

                // assetState
                team.setAssetState(TOOLS.sanitizeResponse((String) dataMainObj.get("AssetState")));

                // isDeleted;
                team.setIsDeleted(TOOLS.sanitizeResponse((String) dataMainObj.get("IsDeleted")));

                try {
                    teamRepo.save(team);
                } catch (Exception e) {
                    LOGGER.error(
                            "Unexpected error caused when attempting to save data\nCaused by: " + e.getCause(),
                            e);
                }
            }
        }
    } catch (Exception e) {
        LOGGER.error("FAILED: " + e.getMessage() + ", " + e.getClass(), e);
    }
}

From source file:com.optimizely.ab.config.parser.JsonSimpleConfigParser.java

private List<Audience> parseAudiences(JSONArray audienceJson) throws ParseException {
    JSONParser parser = new JSONParser();
    List<Audience> audiences = new ArrayList<Audience>(audienceJson.size());

    for (Object obj : audienceJson) {
        JSONObject audienceObject = (JSONObject) obj;
        String id = (String) audienceObject.get("id");
        String key = (String) audienceObject.get("name");
        String conditionString = (String) audienceObject.get("conditions");

        JSONArray conditionJson = (JSONArray) parser.parse(conditionString);
        Condition conditions = parseConditions(conditionJson);
        audiences.add(new Audience(id, key, conditions));
    }// w  w  w .j a  va2s . c  o m

    return audiences;
}

From source file:interfaceTisseoWS.ST3.java

/**
 * Indique si l'une des lignes qui passe par cet arrt (format JSon) est une ligne au dpart de l'universit
 * @param dest/*from   w w  w  . j a  v a  2 s .  c o m*/
 * @return 
 */
public boolean estDeservieDepuisPS(JSONArray dest) {
    String line;
    for (int i = 0; i < dest.size(); i++) {
        for (int j = 0; j < ((JSONArray) ((JSONObject) dest.get(i)).get("line")).size(); j++) {
            line = (String) ((JSONObject) ((JSONArray) ((JSONObject) dest.get(i)).get("line")).get(j))
                    .get("shortName");
            if (estLignePS(line)) {
                lblResultat.setText("Votre zone est dsservie directement depuis \nPaul Sabatier par la ligne "
                        + line + ", utilisez le rseau Tisso");
                return true;
            }
        }
    }

    return false;
}

From source file:com.rackspacecloud.blueflood.outputs.serializers.JSONBasicRollupOutputSerializerTest.java

@Test
public void testTransformRollupDataString() throws SerializationException {
    final JSONBasicRollupsOutputSerializer serializer = new JSONBasicRollupsOutputSerializer();
    final MetricData metricData = new MetricData(FakeMetricDataGenerator.generateFakeStringPoints(), "unknown",
            MetricData.Type.STRING);

    JSONObject metricDataJSON = serializer.transformRollupData(metricData, filterStats);

    final JSONArray data = (JSONArray) metricDataJSON.get("values");

    // Assert that we have some data to test
    Assert.assertTrue(data.size() > 0);

    for (int i = 0; i < data.size(); i++) {
        final JSONObject dataJSON = (JSONObject) data.get(i);
        final Points.Point point = (Points.Point) metricData.getData().getPoints()
                .get(dataJSON.get("timestamp"));

        Assert.assertEquals(point.getData(), dataJSON.get("value"));

        Assert.assertNull(dataJSON.get("average"));
        Assert.assertNull(dataJSON.get("min"));
        Assert.assertNull(dataJSON.get("max"));
        Assert.assertNull(dataJSON.get("variance"));
    }//from  w ww  .  ja v a  2  s. co m
}

From source file:com.db.comserv.main.utilities.HttpCaller.java

private Boolean matchPattern(final String url, String multiplierStr, String method) {
    JSONArray jsonArr = (JSONArray) Utility.parse(multiplierStr);
    for (int i = 0; i < jsonArr.size(); i++) {
        JSONObject obj = (JSONObject) jsonArr.get(i);
        String regex = obj.get("path").toString();
        String methodStr = obj.get("method").toString();
        Pattern pattern = Pattern.compile(regex);
        Matcher match = pattern.matcher(url);
        boolean found = match.find();
        if (found && methodStr.contains(method)) {
            return (found && methodStr.contains(method));
        }// ww  w .  j  av  a  2  s  .  c  om
    }
    return false;
}

From source file:iphonestalker.util.FindMyIPhoneReader.java

public String connect(String username, String password) {

    numDevices = 0;//from   ww  w  . j  a  va 2 s.  co  m

    // Setup HTTP parameters
    HttpParams params = new BasicHttpParams();
    params.setParameter("http.useragent", "Find iPhone/1.1 MeKit (iPhone: iPhone OS/4.2.1)");
    client = new DefaultHttpClient(params);

    // Construct the post
    post = new HttpPost("https://fmipmobile.me.com/fmipservice/device/" + username);
    post.addHeader("X-Client-Uuid", "0000000000000000000000000000000000000000");
    post.addHeader("X-Client-Name", "My iPhone");
    Header[] headers = { new BasicHeader("X-Apple-Find-Api-Ver", "2.0"),
            new BasicHeader("X-Apple-Authscheme", "UserIdGuest"),
            new BasicHeader("X-Apple-Realm-Support", "1.0"),
            new BasicHeader("Content-Type", "application/json; charset=utf-8"),
            new BasicHeader("Accept-Language", "en-us"), new BasicHeader("Pragma", "no-cache"),
            new BasicHeader("Connection", "keep-alive"), new BasicHeader("Authorization",
                    "Basic " + new String(Base64.encodeBase64((username + ":" + password).getBytes()))) };
    post.setHeaders(headers);

    HttpResponse response = null;
    try {
        // Execute
        response = client.execute(post);

        // We should get a redirect
        if (response.getStatusLine().getStatusCode() == 330) {
            String newHost = (((Header[]) response.getHeaders("X-Apple-MME-Host"))[0]).getValue();
            try {
                post.setURI(new URI("https://" + newHost + "/fmipservice/device/" + username + "/initClient"));
            } catch (URISyntaxException ex) {
                logger.log(Level.SEVERE, null, ex);
                return "Couldn't post URI: " + ex;
            }

            // Dump the data so we can execute a new post
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
            JSONObject object = (JSONObject) JSONValue.parse(reader);

            // This post should get us our data
            response = client.execute(post);
            reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));

            // Read the data
            object = (JSONObject) JSONValue.parse(reader);
            JSONArray array = ((JSONArray) object.get("content"));
            numDevices = array.size();

            // Setup the route data
            iPhoneRouteList = new ArrayList<IPhoneRoute>();

            for (int i = 0; i < numDevices; i++) {
                // Get the device data
                object = (JSONObject) array.get(i);
                IPhoneLocation iPhoneLocation = getLocation(object);

                // Add route data
                IPhoneRoute iPhoneRoute = new IPhoneRoute();
                String modelDisplayName = (String) object.get("modelDisplayName");
                String deviceModelName = (String) object.get("deviceModel");
                String name = (String) object.get("name");

                Calendar cal = Calendar.getInstance();
                cal.setTimeInMillis(System.currentTimeMillis());
                iPhoneRoute.name = "[FMI #" + (i + 1) + "]" + name + ":" + modelDisplayName + " "
                        + deviceModelName;
                iPhoneRoute.lastBackupDate = cal.getTime();
                iPhoneRoute.setFMI(true);

                if (iPhoneLocation != null) {
                    iPhoneRoute.addLocation(iPhoneLocation);
                }
                iPhoneRouteList.add(iPhoneRoute);
            }

        } else {
            logger.log(Level.WARNING, "Couldn\'t retrieve iPhone data: " + response.getStatusLine().toString());
            return "Couldn't retrieve iPhone data: " + response.getStatusLine().toString();
        }
    } catch (ClientProtocolException ex) {
        logger.log(Level.SEVERE, null, ex);
        return "Couldn't retrieve iPhone data: " + ex;
    } catch (IOException ex) {
        logger.log(Level.SEVERE, null, ex);
        return "Couldn't retrieve iPhone data: " + ex;
    }

    return null;
}

From source file:com.gmail.bleedobsidian.itemcase.Updater.java

/**
 * Query ServerMods API for project variables.
 *
 * @return If successful or not.// w  w  w . ja v  a 2s  .  c o m
 */
private boolean query() {
    try {
        final URLConnection con = this.url.openConnection();
        con.setConnectTimeout(5000);
        con.setReadTimeout(5000);

        if (this.apiKey != null) {
            con.addRequestProperty("X-API-Key", this.apiKey);
        }

        con.addRequestProperty("User-Agent", this.plugin.getName() + " Updater");

        con.setDoOutput(true);

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

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

        if (array.size() == 0) {
            this.result = UpdateResult.ERROR_ID;
            return false;
        }

        this.versionName = (String) ((JSONObject) array.get(array.size() - 1)).get("name");
        this.versionLink = (String) ((JSONObject) array.get(array.size() - 1)).get("downloadUrl");
        this.versionType = (String) ((JSONObject) array.get(array.size() - 1)).get("releaseType");
        this.versionGameVersion = (String) ((JSONObject) array.get(array.size() - 1)).get("gameVersion");

        return true;
    } catch (IOException e) {
        if (e.getMessage().contains("HTTP response code: 403")) {
            this.result = UpdateResult.ERROR_APIKEY;
        } else {
            this.result = UpdateResult.ERROR_SERVER;
        }

        return false;
    }

}