Example usage for org.json.simple JSONArray get

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

Introduction

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

Prototype

public E get(int index) 

Source Link

Document

Returns the element at the specified position in this list.

Usage

From source file:msuresh.raftdistdb.RaftClient.java

public static void GetValue(String name, String key) throws FileNotFoundException {
    if (key == null || key.isEmpty()) {
        return;//w  w w  .j  a v  a2s .c  om
    }
    File configFile = new File(Constants.STATE_LOCATION + name + ".info");
    if (!configFile.exists() || configFile.isDirectory()) {
        FileNotFoundException ex = new FileNotFoundException();
        throw ex;
    }
    try {
        System.out.println("Getting key .. Hold on.");
        String content = new Scanner(configFile).useDelimiter("\\Z").next();
        JSONObject config = (JSONObject) (new JSONParser()).parse(content);
        Long numPart = (Long) config.get("countPartitions");
        Integer shardId = key.hashCode() % numPart.intValue();
        JSONArray memberJson = (JSONArray) config.get(shardId.toString());
        List<Address> members = new ArrayList<>();
        for (int i = 0; i < memberJson.size(); i++) {
            JSONObject obj = (JSONObject) memberJson.get(i);
            Long port = (Long) obj.get("port");
            String address = (String) obj.get("address");
            members.add(new Address(address, port.intValue()));
        }
        CopycatClient client = CopycatClient.builder(members).withTransport(new NettyTransport()).build();
        client.open().join();
        Object str = client.submit(new GetQuery(key)).get();
        System.out.println("For the key : " + key + ", the database returned the value : " + (String) str);
        client.close().join();
        while (client.isOpen()) {
            Thread.sleep(1000);
        }
    } catch (Exception ex) {
        System.out.println(ex.toString());
    }
}

From source file:bhl.pages.handler.PagesGetHandler.java

protected static void sortList(JSONArray a) {
    int increment = a.size() / 2;
    while (increment > 0) {
        for (int i = increment; i < a.size(); i++) {
            int j = i;
            JSONObject temp = (JSONObject) a.get(i);
            int tempN = ((Number) temp.get("n")).intValue();
            JSONObject aObj = ((JSONObject) a.get(j - increment));
            int aN = ((Number) aObj.get("n")).intValue();
            while (j >= increment && aN > tempN) {
                a.set(j, a.get(j - increment));
                j = j - increment;/*  w  w  w .j  ava 2 s .c o  m*/
                if (j >= increment) {
                    aObj = ((JSONObject) a.get(j - increment));
                    aN = ((Number) aObj.get("n")).intValue();
                }
            }
            a.set(j, temp);
        }
        if (increment == 2) {
            increment = 1;
        } else {
            increment *= (5.0 / 11);
        }
    }
}

From source file:com.avatarproject.core.storage.UserCache.java

/**
 * Gets a UUID of a user from the custom UserCache.
 * @param playername String name of the player to get.
 * @return UUID of the player./* ww w  .j a va2 s.  c  o m*/
 */
public static UUID getUser(String playername) {
    JSONArray array = getUserCache();
    try {
        for (int n = 0; n < array.size(); n++) { //Loop through all the objects in the array.
            JSONObject object = (JSONObject) array.get(n);
            if (String.valueOf(object.get("name")).equalsIgnoreCase(playername)) {
                return UUID.fromString(String.valueOf(object.get("id")));
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

From source file:mp3downloader.ZingSearch.java

public static ArrayList<Playlist> searchPlaylist(String term) {
    ArrayList<Playlist> playlists = new ArrayList<>();
    try {/* ww w .  java2 s .  c  o m*/
        String content = getSearchResult(term, 8);
        JSONParser parser = new JSONParser();
        JSONObject obj = (JSONObject) parser.parse(content);
        JSONArray items = (JSONArray) obj.get("Data");

        for (int i = 0; i < items.size(); i++) {
            JSONObject item = (JSONObject) items.get(i);
            String id = (String) item.get("ID");
            String title = (String) item.get("Title");
            String artist = (String) item.get("Artist");
            String genre = (String) item.get("Genre");
            String pictureUrl = (String) item.get("PictureURL");
            long totalListen = 0;
            if (item.get("TotalListen") != null) {
                totalListen = (long) item.get("TotalListen");
            }
            Playlist p = new Playlist(id, title, artist, genre, pictureUrl, totalListen);
            playlists.add(p);
        }
    } catch (Exception ex) {
        Logger.getLogger(ZingSearch.class.getName()).log(Level.SEVERE, null, ex);
    }
    return playlists;
}

From source file:MyTest.ParseJson.java

private static void getDetailInfo(JSONObject jstep_detail) {
    //        System.out.println(jstep_detail);
    long id = (long) jstep_detail.get("id");
    System.out.println("id:" + id);
    String name = (String) jstep_detail.get("name");
    System.out.println("name:" + name);
    JSONArray inputs = (JSONArray) jstep_detail.get("inputs");
    if (inputs.isEmpty()) {
        System.out.println("inputs:null");

    } else {/*from   www . j a va 2  s .  c om*/
        System.out.println("inputs:");
        for (int i = 0; i < inputs.size(); i++) {
            System.out.println(inputs.get(i) + "\n");
        }
    }

    JSONArray outpus = (JSONArray) jstep_detail.get("outputs");
    if (outpus.isEmpty()) {
        System.out.println("outpus:null");
    } else {
        System.out.println("outpus:");
        for (int i = 0; i < outpus.size(); i++) {
            System.out.print(outpus.get(i) + "\n");
        }
    }

    JSONObject links = (JSONObject) jstep_detail.get("input_connections");
    if (links.isEmpty()) {
        System.out.println("input_connections:null");
    } else {
        Iterator it = links.keySet().iterator();
        System.out.println("input_connections: ");
        while (it.hasNext()) {
            Object input_link = it.next();
            System.out.println(links.get(input_link));
        }
    }
    System.out.println("-------------------------------------------------------");
}

From source file:com.avatarproject.core.storage.UserCache.java

/**
 * Adds a player into the custom UserCache.
 * @param player Player to add to the cache.
 *///from  w  w  w. j  a v a 2  s  . c  o  m
@SuppressWarnings("unchecked")
public static void addUser(Player player) {
    String name = player.getName();
    UUID uuid = player.getUniqueId();
    JSONArray array = getUserCache();
    try {
        for (int n = 0; n < array.size(); n++) { //Loop through all the objects in the array.
            JSONObject object = (JSONObject) array.get(n);
            if (object.get("id").equals(uuid.toString())) { //Check if the player's UUID exists in the cache.
                if (String.valueOf(object.get("name")).equalsIgnoreCase(name)) {
                    return;
                } else {
                    object.put("name", name); //Update the user.
                    FileWriter fileOut = new FileWriter(usercache);
                    fileOut.write(array.toJSONString()); //Write the JSON array to the file.
                    fileOut.close();
                    return;
                }
            }
        }
        JSONObject newEntry = new JSONObject();
        newEntry.put("id", uuid.toString());
        newEntry.put("name", name);
        array.add(newEntry); //Add a new player into the cache.
        FileWriter fileOut = new FileWriter(usercache);
        fileOut.write(array.toJSONString()); //Write the JSON array to the file.
        fileOut.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:iracing.webapi.SeasonParser.java

public static List<Season> parse(String json) {
    JSONParser parser = new JSONParser();
    List<Season> output = null;
    try {// w  w w .ja  v a  2 s  .c om
        JSONArray rootArray = (JSONArray) parser.parse(json);
        output = new ArrayList<Season>();
        for (int i = 0; i < rootArray.size(); i++) {
            JSONObject r = (JSONObject) rootArray.get(i);
            Season season = new Season();
            season.setId(getInt(r, "seasonid"));
            season.setPrefImage(getString(r, "prefimg", true));
            season.setSeriesName(getString(r, "seriesname", true));
            season.setSeasonShortName(getString(r, "seasonshortname", true));
            season.setWhatsHotImage(getString(r, "whatshotimg", true));
            season.setCautionTypeRoad(getInt(r, "cautionTypeRoad"));
            season.setCautionTypeOval(getInt(r, "cautionTypeOval"));
            season.setRaceWeeks(getInt(r, "raceweek"));
            season.setActive((Boolean) r.get("active"));
            season.setMinimumSafetyRating(getString(r, "minsr"));
            season.setMinimumLicenseLevel(getInt(r, "minlicenselevel"));
            season.setMaximumLicenseLevel(getInt(r, "maxlicenselevel"));
            JSONArray array = (JSONArray) r.get("tracks");
            List<Season.Track> trackList = new ArrayList<Season.Track>();
            // to work around a website bug where tracks are listed 3 times each, 
            // we only add ones that have different raceweek values
            int lastRaceWeek = -1;
            for (int j = 0; j < array.size(); j++) {
                //{"config":"","priority":0,"raceweek":0,"pkgid":90,"night":0,"name":"Mosport+International+Raceway","id":144,"lowername":"mosport+international+raceway"}
                JSONObject o = (JSONObject) array.get(j);
                int raceWeek = getInt(o, "raceweek");
                if (raceWeek != lastRaceWeek) {
                    Season.Track track = new Season.Track();
                    track.setId(getInt(o, "id"));
                    track.setNightMode((getInt(o, "night")) == 1);
                    trackList.add(track);
                    lastRaceWeek = raceWeek;
                }
            }
            season.setTracks(trackList);
            //"carclasses":[{"carsinclass":[{"name":"Cadillac+CTS-V+Racecar","id":41}],"shortname":"Cadillac+CTS-VR","name":"Cadillac+CTS-VR","id":45,"lowername":"cadillac+cts-vr"}]
            List<Integer> carClasses = new ArrayList<Integer>();
            array = (JSONArray) r.get("carclasses");
            for (int j = 0; j < array.size(); j++) {
                JSONObject o = (JSONObject) array.get(j);
                //JSONArray array2 = (JSONArray)o.get("carsinclass");
                carClasses.add(getInt(o, "id"));
            }
            season.setCarClasses(carClasses);
            season.setApiUserClubAllowed((Boolean) r.get("isClubAllowed"));
            season.setSeriesLicenseGroupId(getInt(r, "serieslicgroupid"));
            season.setCurrentTrack(getInt(r, "currentTrack"));
            season.setSeriesId(getInt(r, "seriesid"));
            season.setLicenseGroupId(getInt(r, "licgroupid"));
            season.setLicenseIgnoredForPractice((Boolean) r.get("ignoreLicenseForPractice"));
            season.setWorldCupEvent((Boolean) r.get("isWorldCup"));
            season.setStartDate(new Date(getLong(r, "start")));
            season.setEndDate(new Date(getLong(r, "end")));
            array = (JSONArray) r.get("cars");
            List<Integer> carList = new ArrayList<Integer>();
            for (int j = 0; j < array.size(); j++) {
                JSONObject o = (JSONObject) array.get(j);
                carList.add(getInt(o, "id"));
            }
            season.setCars(carList);
            season.setMultiClass((Boolean) r.get("multiclass"));
            season.setRegionalCompetitionEvent((Boolean) r.get("isRegionCompetition"));
            season.setQuarter(getInt(r, "quarter"));
            season.setYear(getInt(r, "year"));
            season.setSeriesShortName(getString(r, "seriesshortname", true));
            season.setCategoryId(getInt(r, "catid")); // also stored under 'category'
            season.setOfficial((Boolean) r.get("isOfficial"));
            season.setApiUserLicenseEligible((Boolean) r.get("licenseEligible"));
            season.setComplete((Boolean) r.get("complete"));
            output.add(season);
        }
    } catch (ParseException ex) {
        Logger.getLogger(SeasonParser.class.getName()).log(Level.SEVERE, null, ex);
    }
    return output;
}

From source file:com.grouptuity.venmo.VenmoSDK.java

public static VenmoResponse validateVenmoPaymentResponse(String signed_payload) {
    String encoded_signature, payload;
    if (signed_payload == null) {
        return new VenmoResponse(null, null, null, "0");
    }//from   ww w.  j av  a 2s. com
    try {
        String[] encodedsig_payload_array = signed_payload.split("\\.");
        encoded_signature = encodedsig_payload_array[0];
        payload = encodedsig_payload_array[1];
    } catch (ArrayIndexOutOfBoundsException e) {
        return new VenmoResponse(null, null, null, "0");
    }

    String decoded_signature = base64_url_decode(encoded_signature);
    String data;
    // check signature 
    String expected_sig = hash_hmac(payload, Grouptuity.VENMO_SECRET, "HmacSHA256");

    Log.d("VenmoSDK", "expected_sig using HmacSHA256:" + expected_sig);

    VenmoResponse myVenmoResponse;

    if (decoded_signature.equals(expected_sig)) {
        data = base64_url_decode(payload);

        try {
            JSONArray response = (JSONArray) JSONValue.parse(data);
            JSONObject obj = (JSONObject) response.get(0);
            String payment_id = obj.get("payment_id").toString();
            String note = obj.get("note").toString();
            String amount = obj.get("amount").toString();
            String success = obj.get("success").toString();
            myVenmoResponse = new VenmoResponse(payment_id, note, amount, success);
        } catch (Exception e) {
            Log.d("VenmoSDK", "Exception caught: " + e.getMessage());
            myVenmoResponse = new VenmoResponse(null, null, null, "0");
        }
    } else {
        Log.d("VenmoSDK", "Signature does NOT match");
        myVenmoResponse = new VenmoResponse(null, null, null, "0");
    }
    return myVenmoResponse;
}

From source file:com.github.itoshige.testrail.util.ConfigrationUtil.java

private static List<RunIdInfo> getRunIdInfos(JSONArray runIds) {
    List<RunIdInfo> runIdInfos = new ArrayList<RunIdInfo>();
    for (int i = 0; i < runIds.size(); i++) {
        JSONObject runIdInfo = (JSONObject) runIds.get(i);
        runIdInfos.add(new RunIdInfo(runIdInfo.get("target"), runIdInfo.get("runId")));
    }//ww w . j a v  a2s.c  o m
    Collections.sort(runIdInfos, new RunIdInfoComparator());
    return runIdInfos;
}

From source file:OCRRestAPI.java

private static void PrintOCRResponse(String jsonResponse) throws ParseException, IOException {
    // Parse JSON data
    JSONParser parser = new JSONParser();
    JSONObject jsonObj = (JSONObject) parser.parse(jsonResponse);

    // Get available pages
    System.out.println("Available pages: " + jsonObj.get("AvailablePages"));

    // get an array from the JSON object
    JSONArray text = (JSONArray) jsonObj.get("OCRText");

    // For zonal OCR: OCRText[z][p]    z - zone, p - pages
    for (int i = 0; i < text.size(); i++) {
        System.out.println(" " + text.get(i));
    }/* w w  w  . ja  v  a2  s  . c  o  m*/

    // Output file URL
    String outputFileUrl = (String) jsonObj.get("OutputFileUrl");

    // If output file URL is specified
    if (outputFileUrl != null && !outputFileUrl.equals("")) {
        // Download output file
        DownloadConvertedFile(outputFileUrl);
    }
}