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:com.boozallen.cognition.ingest.storm.bolt.geo.TwoFishesGeocodeBolt.java

/**
 * Submits a URL query string and builds a TwoFishesFeature for the result and all parents.
 *
 * @param query/* w  w  w. j av a2s.c o  m*/
 * @return
 * @throws IOException
 * @throws ParseException
 */
private TwoFishesFeature[] submitQuery(String query) throws IOException, ParseException {
    URL url = new URL(query);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setRequestMethod("GET");
    conn.setRequestProperty("Accept", "application/json");
    if (conn.getResponseCode() != 200) {
        logger.error("Failed : HTTP error code : " + conn.getResponseCode() + ":" + url.toString());
        _failCount++;
        return null;
    }
    BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
    String jsonStr = br.readLine();
    br.close();
    conn.disconnect();

    JSONParser parser = new JSONParser();
    JSONObject jsonObject = (JSONObject) parser.parse(jsonStr);
    JSONArray interpretations = (JSONArray) jsonObject.get("interpretations");

    if (interpretations.size() == 0) {
        //logger.warn("Twofishes unable to resolve location " + unresolvedLocation);
        _failCount++;
        return null;
    } else {
        if (interpretations.size() > 1) {
            //lat-long searches have multiple interpretations, e.g. city, county, state, country. most specific is first, so still use it.
            logger.debug("Twofishes has more than one interpretation of " + query);
        }
        JSONObject interpretation0 = (JSONObject) interpretations.get(0);

        //ArrayList of main result and parents
        ArrayList<JSONObject> features = new ArrayList<JSONObject>();
        JSONObject feature = (JSONObject) interpretation0.get("feature");

        //save main result
        features.add(feature);

        JSONArray parents = (JSONArray) interpretation0.get("parents");
        //get parents as feature JSONObjects
        for (int i = 0; i < parents.size(); i++) {
            JSONObject parentFeature = (JSONObject) parents.get(i);
            features.add(parentFeature);
        }

        //parse features and return
        TwoFishesFeature[] results = new TwoFishesFeature[features.size()];

        for (int i = 0; i < features.size(); i++) {
            JSONObject f = features.get(i);
            TwoFishesFeature result = new TwoFishesFeature();
            result.name = (String) f.get("name");
            result.countryCode = (String) f.get(CC);
            result.woeType = (long) f.get("woeType");
            JSONObject geometry = (JSONObject) f.get("geometry");
            JSONObject center = (JSONObject) geometry.get("center");
            result.lat = String.valueOf(center.get(LAT));
            result.lng = String.valueOf(center.get(LNG));
            results[i] = result;
        }

        _successCount++;
        return results;
    }

}

From source file:net.bashtech.geobot.JSONUtil.java

public static ArrayList<String> BOIFlyItems(String channel) {

    try {/*from   ww w. jav a2  s  .  c  om*/
        JSONParser parser = new JSONParser();
        Object obj = parser.parse(
                BotManager.getRemoteContent("http://coebot.tv/configs/boir/" + channel.substring(1) + ".json"));

        JSONObject jsonObject = (JSONObject) obj;

        JSONArray items = (JSONArray) jsonObject.get("flyItems");
        ArrayList<String> itemList = new ArrayList<String>();
        for (int i = 0; i < items.size(); i++) {
            itemList.add((String) items.get(i));
        }

        return itemList;
    } catch (Exception ex) {
        return null;
    }
}

From source file:net.bashtech.geobot.JSONUtil.java

public static ArrayList<String> BOIGuppyItems(String channel) {

    try {/*from  w w w.jav a 2 s .  com*/
        JSONParser parser = new JSONParser();
        Object obj = parser.parse(
                BotManager.getRemoteContent("http://coebot.tv/configs/boir/" + channel.substring(1) + ".json"));

        JSONObject jsonObject = (JSONObject) obj;

        JSONArray items = (JSONArray) jsonObject.get("guppyItems");
        ArrayList<String> itemList = new ArrayList<String>();
        for (int i = 0; i < items.size(); i++) {
            itemList.add((String) items.get(i));
        }

        return itemList;
    } catch (Exception ex) {
        return null;
    }
}

From source file:com.gti.redirects.Redirects.RedirectStorage.java

@Override
public List<Map<String, String>> getAll() {
    List<Map<String, String>> redirects = new ArrayList<Map<String, String>>();
    JSONArray jsonArray = null;
    try {/*from w w  w  .j a v a2  s.  c  o  m*/
        jsonArray = parseFile();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (ParseException e) {
        e.printStackTrace();
    }
    if (jsonArray != null) {
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject object = (JSONObject) jsonArray.get(i);
            Map<String, String> map = new HashMap<String, String>();
            map.put("domain", object.get("domain").toString());
            map.put("status", object.get("status").toString());
            map.put("redirect_to", object.get("redirect_to").toString());

            redirects.add(map);
            // now do something with the Object
        }
    }
    return redirects;
}

From source file:edu.pitt.dbmi.facebase.hd.FileManager.java

/** populates an ArrayList with Instruction objects using the JSON-formatted fb_queue.instructions column data
 * The JSON string (from the database) is keyed by "csv", "text" and "files" depending on the type of data. 
 * Instructions descendants (InstructionsCsv, InstructionsText, InstructionsFiles) are constructed. 
 * File objects are constructed (and stuffed into their container Instructions objects). 
 * As an example, the JSON shown here would result in 6 Instructions objects, 2 of each kind shown:
 * </ b>//from   ww  w  .ja v  a2  s . c om
 * <pre>
 * {
 *     "csv": [
 *         {
 *             "content": "SELECT name FROM user",
 *             "path": "/Data/User Names.csv"
 *         },
 *         {
 *             "content": "SELECT uid FROM user",
 *             "path": "/Data/User IDs.csv"
 *         }
 *     ],
 *     "text": [
 *         {
 *             "content": "Your data was retrieved on 11-02-2011 and has 28 missing values...",
 *             "path": "/Data/Summary.txt"
 *         },
 *         {
 *             "content": "The Facebase Data User Agreement specifies...",
 *             "path": "/FaceBase Agreement.txt"
 *         }
 *     ],
 *     "files": [
 *         {
 *             "content": "/path/on/server/1101.obj",
 *             "path": "/meshes/1101.obj"
 *         },
 *         {
 *             "content": "/path/on/server/1102.obj",
 *             "path": "/meshes/1102.obj"
 *         }
 *     ]
 * }
 * </pre>
 * </ b>
 * 
 * @param instructionsString the JSON from the data request.
 * @param ali the list of Instructions objects that will be populated during execution of this method.
 * @return true if Instructions object creation effort succeeds.
 */
public boolean makeInstructionsObjects(String instructionsString, ArrayList<Instructions> ali) {
    log.debug("FileManager.makeInstructionsObjects() called.");
    long unixEpicTime = System.currentTimeMillis() / 1000L;
    String unixEpicTimeString = (new Long(unixEpicTime)).toString();
    this.setDataName(dataNamePrefix + unixEpicTimeString);
    trueCryptPath = trueCryptBasePath + dataName + trueCryptExtension;
    trueCryptFilename = dataName + trueCryptExtension;
    trueCryptVolumePath = trueCryptBasePath + dataName + trueCryptMountpoint;
    File trueCryptVolumePathDir = new File(trueCryptVolumePath);
    if (!trueCryptVolumePathDir.isDirectory()) {
        trueCryptVolumePathDir.mkdirs();
    }
    JSONObject jsonObj = (JSONObject) JSONValue.parse(instructionsString);

    if (jsonObj.containsKey("csv")) {
        log.debug("FileManager.makeInstructionsObjects() has a csv.");
        JSONArray jsonCsvArray = (JSONArray) jsonObj.get("csv");
        if (jsonCsvArray.size() > 0) {
            for (Object jsonObjectCsvItem : jsonCsvArray) {
                JSONObject jsonObjSql = (JSONObject) jsonObjectCsvItem;
                String sqlString = (String) jsonObjSql.get("content");
                JSONObject jsonObjSqlPath = (JSONObject) jsonObjectCsvItem;
                String sqlPathString = (String) jsonObjSql.get("path");
                File file = new File(trueCryptBasePath + dataName + sqlPathString);
                InstructionsCsv i = new InstructionsCsv(sqlString, file, sqlPathString);
                ali.add(i);
            }
        }
    }

    if (jsonObj.containsKey("text")) {
        log.debug("FileManager.makeInstructionsObjects() has a text.");
        JSONArray jsonTextArray = (JSONArray) jsonObj.get("text");
        if (jsonTextArray.size() > 0) {
            for (Object jsonObjectTextItem : jsonTextArray) {
                JSONObject jsonObjText = (JSONObject) jsonObjectTextItem;
                String contentString = (String) jsonObjText.get("content");
                JSONObject jsonObjTextPath = (JSONObject) jsonObjectTextItem;
                String textPathString = (String) jsonObjText.get("path");
                File file = new File(trueCryptBasePath + dataName + textPathString);
                InstructionsText i = new InstructionsText(contentString, file, textPathString);
                ali.add(i);
            }
        }
    }

    if (jsonObj.containsKey("files")) {
        log.debug("FileManager.makeInstructionsObjects() has a files.");
        JSONArray jsonFilesArray = (JSONArray) jsonObj.get("files");
        if (jsonFilesArray.size() > 0) {
            for (Object jsonObjectFilesItem : jsonFilesArray) {
                JSONObject jsonObjFiles = (JSONObject) jsonObjectFilesItem;
                String serverPathString = (String) jsonObjFiles.get("content");
                JSONObject jsonObjFilesPath = (JSONObject) jsonObjectFilesItem;
                String archivePathString = (String) jsonObjFiles.get("path");
                File fileSource = new File(serverPathString);
                File fileDest = new File(trueCryptBasePath + dataName + archivePathString);
                InstructionsFiles i = new InstructionsFiles(fileSource, fileDest, archivePathString);
                ali.add(i);
            }
        }
    }
    return true;
}

From source file:com.ge.research.semtk.sparqlX.parallel.SparqlParallelQueries.java

@SuppressWarnings("unchecked")
public SparqlParallelQueries(String subqueriesJson, String subqueryType, boolean isSubqueryOptional,
        String columnsToFuseOn, String columnsToReturn) throws Exception {
    // parse the json array and build the subquery objects as we go
    gResultTable = null;/*  ww  w  .j av a2  s .  c  om*/

    JSONArray subqueries = (JSONArray) (new JSONParser()).parse(subqueriesJson);
    this.subqueries = new ArrayList<>(subqueries.size());
    for (int i = 0; i < subqueries.size(); i++) {
        JSONObject subquery = (JSONObject) subqueries.get(i);
        // let the constructor do the heavy lifting here
        this.subqueries.add(new SparqlSubquery(subquery));
    }

    this.subqueryType = subqueryType;
    this.isSubqueryOptional = isSubqueryOptional;
    this.columnsToFuseOn = new LinkedHashSet<>(Arrays.asList(columnsToFuseOn.split(",")));
    this.columnsToReturn = new LinkedHashSet<>(Arrays.asList(columnsToReturn.split(",")));

    if (this.subqueries.size() == 0) {
        // this was completely invalid a call as we have no subqueries to process
        throw new Exception("subqueries json does not contain any subqueries.");
    }
}

From source file:edu.ncsu.epc.models.Yelp.java

public ArrayList<YelpInfo> getYelpItems(String response) {
    // Update tokens here from Yelp developers site, Manage API access.
    int i = 0;/*from  w  w  w  .j ava2s  .  c o m*/
    ArrayList<YelpInfo> list = new ArrayList<YelpInfo>();
    YelpInfo yelpInfo;

    //System.out.println(response);
    try {
        JSONObject json = (JSONObject) new JSONParser().parse(response);
        JSONArray jsonArray = (JSONArray) new JSONParser().parse(json.get("businesses").toString());
        //System.out.println(json.keySet());
        //JSONObject json1 = (JSONObject) new JSONParser().parse(jsonArray.get(3).toString());
        //System.out.println(json1.keySet());

        while (i < jsonArray.size()) {
            yelpInfo = new YelpInfo();
            JSONObject json1 = (JSONObject) new JSONParser().parse(jsonArray.get(i).toString());
            i++;
            yelpInfo.rating = Double.parseDouble(json1.get("rating").toString());
            JSONObject json2 = (JSONObject) new JSONParser().parse(json1.get("location").toString());
            JSONArray jsonArray2 = (JSONArray) new JSONParser().parse(json2.get("address").toString());
            if (jsonArray2.size() == 0)
                continue;
            yelpInfo.address = jsonArray2.get(0).toString();
            //            if(yelpInfo.address.length()==2) continue;
            //            yelpInfo.address = yelpInfo.address.substring(1, yelpInfo.address.length()-1);
            //            yelpInfo.address = yelpInfo.address.substring(1, yelpInfo.address.length()-1);
            yelpInfo.address += "," + json2.get("city") + "," + json2.get("state_code");
            list.add(yelpInfo);

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

    return list;
    //        Iterator<String> iterator = jsonArray.iterator();
    //        while (iterator.hasNext()) {
    //            String str = (String)iterator.next();
    //            System.out.println(str);
    //            JSONObject json1 = (JSONObject) new JSONParser().parse(iterator.next().toString());
    //            System.out.println(json1.keySet());
    //        }

}

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

private Condition parseConditions(JSONArray conditionJson) {
    List<Condition> conditions = new ArrayList<Condition>();
    String operand = (String) conditionJson.get(0);

    for (int i = 1; i < conditionJson.size(); i++) {
        Object obj = conditionJson.get(i);
        if (obj instanceof JSONArray) {
            conditions.add(parseConditions((JSONArray) conditionJson.get(i)));
        } else {// www .  j a v a 2 s.co  m
            JSONObject conditionMap = (JSONObject) obj;
            conditions.add(new UserAttribute((String) conditionMap.get("name"),
                    (String) conditionMap.get("type"), (String) conditionMap.get("value")));
        }
    }

    Condition condition;
    if (operand.equals("and")) {
        condition = new AndCondition(conditions);
    } else if (operand.equals("or")) {
        condition = new OrCondition(conditions);
    } else {
        condition = new NotCondition(conditions.get(0));
    }

    return condition;
}

From source file:main.java.gov.wa.wsdot.candidate.evaluation.App.java

/**
 * Returns an ArrayList of Camera objects that are within a given radius of
 * users location.//from w  w w .  java2 s  .c  om
 * 
 * @param jArray    JSONArray with WSDOT camera data
 * @param userLat   users current latitude
 * @param userLong  users current longitude
 * @param radius    max distance to look for cameras
 * @return          ArrayList of cameras within max distance of users location
 */
private ArrayList<Camera> scanCameras(JSONArray jArray, double userLat, double userLong, int radius) {

    JSONObject jObj1;
    JSONObject jObj2;
    double camLat;
    double camLong;
    double dist;
    ArrayList<Camera> cameras = new ArrayList<Camera>();

    for (int i = 0; i < jArray.size(); i++) {
        jObj1 = (JSONObject) jArray.get(i);
        jObj2 = (JSONObject) jObj1.get("CameraLocation");
        camLat = (double) jObj2.get("Latitude");
        camLong = (double) jObj2.get("Longitude");
        dist = getDistance(userLat, userLong, camLat, camLong);
        if (dist < radius) {
            cameras.add(new Camera(jObj1.get("Title").toString(), dist));
        }
    }
    return cameras;
}

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

/**
 * Json??results?.//from www .  j  a va2  s .  c o  m
 * @param json JSONObject
 * @param locationHeader LOCATION
 * @param type ?
 * @param additional ???
 * @param np NP???
 * @param etag etag???
 * @param published published???
 */
@SuppressWarnings("unchecked")
public static final void checkResults(final JSONObject json, final String locationHeader, final String type,
        final Map<String, Object> additional, Map<String, String> np, String etag, String published) {
    String value;

    // d:__published?????????
    value = (String) json.get("__published");
    assertNotNull(value);
    assertTrue(validDate(value));

    // d:__published??????????
    if (published != null) {
        assertEquals(published, value);
    }

    // d:__updated?????????
    value = (String) json.get("__updated");
    assertNotNull(value);
    assertTrue(validDate(value));

    // __metadata?
    JSONObject metadata = (JSONObject) json.get("__metadata");
    // uri?
    value = (String) metadata.get("uri");
    assertNotNull(value);
    if (locationHeader != null) {
        // LOCATION?????
        assertEquals(locationHeader, value);
    }
    // etag?
    value = (String) metadata.get("etag");
    if (etag != null) {
        assertEquals(etag, value);
    }

    // type?
    value = (String) metadata.get("type");
    assertNotNull(value);
    assertEquals(type, value);

    if (additional != null) {
        // ??
        for (Map.Entry<String, Object> e : additional.entrySet()) {
            Object jsonValue = json.get(e.getKey());
            if (jsonValue instanceof Integer) {
                jsonValue = ((Integer) jsonValue).longValue();
            }
            if (jsonValue instanceof JSONArray) {
                JSONArray array = ((JSONArray) jsonValue);
                for (int i = 0; i < array.size(); i++) {
                    if (array.get(i) instanceof Integer) {
                        array.set(i, ((Integer) array.get(i)).longValue());
                    }
                }
            }
            Object expected = e.getValue();
            if (expected instanceof Integer) {
                expected = ((Integer) expected).longValue();
            }
            if (expected instanceof JSONArray) {
                JSONArray array = ((JSONArray) expected);
                for (int i = 0; i < array.size(); i++) {
                    if (array.get(i) instanceof Integer) {
                        array.set(i, ((Integer) array.get(i)).longValue());
                    }
                }
            }
            assertEquals(expected, jsonValue);
        }
    }

    if (np != null) {
        // NP???
        for (Map.Entry<String, String> e : np.entrySet()) {
            JSONObject jsonValue = (JSONObject) json.get(e.getKey());
            JSONObject defferedValue = (JSONObject) jsonValue.get("__deferred");
            String uriValue = (String) defferedValue.get("uri");
            assertEquals(e.getValue(), uriValue);
        }
    }
}