Example usage for com.google.gson JsonArray iterator

List of usage examples for com.google.gson JsonArray iterator

Introduction

In this page you can find the example usage for com.google.gson JsonArray iterator.

Prototype

public Iterator<JsonElement> iterator() 

Source Link

Document

Returns an iterator to navigate the elements of the array.

Usage

From source file:com.twitter.common.thrift.text.SequenceContext.java

License:Apache License

/**
 * Create an iterator over the children. May be constructed with a null
 * JsonArray if we only use it for writing.
 *///from w  w w .  ja va2s. co m
protected SequenceContext(JsonArray json) {
    children = (null != json) ? json.iterator() : null;
}

From source file:com.twitter.intellij.pants.service.project.model.TargetInfoDeserializer.java

License:Apache License

private <T> List<T> getFieldAsList(JsonArray jsonArray, Function<JsonElement, T> fun) {
    return ContainerUtil.mapNotNull(Iterators.toArray(jsonArray.iterator(), JsonElement.class), fun);
}

From source file:com.yahoo.yqlplus.example.apis.WeatherSource.java

@Query
public List<Forecast> getForecast(@Key("woeid") String woeid)
        throws InterruptedException, ExecutionException, TimeoutException, UnsupportedEncodingException {
    JsonObject jsonObject = HttpUtil.getJsonResponse(BASE_URL, "q",
            "select * from weather.forecast where u = 'f' and woeid = " + woeid);
    JsonArray jsonArray = (JsonArray) jsonObject.getAsJsonObject("query").getAsJsonObject("results")
            .getAsJsonObject("channel").getAsJsonObject("item").get("forecast");
    Iterator<JsonElement> it = jsonArray.iterator();
    List<Forecast> forecasts = Lists.newArrayList();
    while (it.hasNext()) {
        JsonElement ele = it.next();/*from w ww  .j av  a  2 s. c  om*/
        ForecastBase tmp = HttpUtil.getGson().fromJson(ele.toString(), ForecastBase.class);
        forecasts.add(new Forecast(tmp.getCode(), tmp.getDate(), tmp.getDay(), tmp.getHigh(), tmp.getLow(),
                tmp.getText(), woeid, "f"));
    }
    return forecasts;
}

From source file:com.yahoo.yqlplus.example.apis.WeatherSource.java

@Query
public List<Forecast> getForecast(@Key("woeid") String woeid, @Key("u") String u)
        throws InterruptedException, ExecutionException, TimeoutException, UnsupportedEncodingException {
    JsonObject jsonObject = HttpUtil.getJsonResponse(BASE_URL.replace("{woeid}", woeid).replace("{u}", u));
    JsonArray jsonArray = (JsonArray) jsonObject.getAsJsonObject("query").getAsJsonObject("results")
            .getAsJsonObject("channel").getAsJsonObject("item").get("forecast");
    Iterator<JsonElement> it = jsonArray.iterator();
    List<Forecast> forecasts = Lists.newArrayList();
    while (it.hasNext()) {
        JsonElement ele = it.next();/*w  ww  .  ja v  a 2s . c o  m*/
        ForecastBase tmp = HttpUtil.getGson().fromJson(ele.toString(), ForecastBase.class);
        forecasts.add(new Forecast(tmp.getCode(), tmp.getDate(), tmp.getDay(), tmp.getHigh(), tmp.getLow(),
                tmp.getText(), woeid, u));
    }
    return forecasts;
}

From source file:controllers.Rdio.java

License:Open Source License

public static Album retrieveAlbumByRdioId(User user, String album_key) {

    //Logger.info("Retrieving album by ID:" + album_key);
    Album album = Album.find("byRdio_Key", album_key).first();

    if (album != null && album.tracksLoaded == true && album.albumTracks != null
            && album.albumTracks.size() > 1) {
        return album;
    }/*from  w  w w  .ja  v  a2s .c  o  m*/

    // Logger.info("Album not (fully) loaded, loading...");
    WSRequest sign = null;

    String url = endpoint + "/albums/" + album_key + "?include=tracks,images";

    boolean rerequest = false;

    try {
        sign = getConnector(user).sign(user.rdioCreds, WS.url(url), "GET");
    } catch (Exception ex) {

        Logger.error("User " + user.firstName + " had error with credentials");
        Logger.error(ex.toString());
        ex.printStackTrace();
        rerequest = true;
    }

    if (rerequest) {
        setupTokens(user, null, 0);
        try {
            sign = getConnector(user).sign(user.rdioCreds, WS.url(url), "GET");
        } catch (Exception ex) {
            Logger.error(ex.toString());
            ex.printStackTrace();
            return null;
        }
    }

    JsonElement json = sign.get().getJson();

    if (json.toString().equalsIgnoreCase("{\"code\":\"UnauthorizedError\",\"message\":\"Unauthorized\"}")) {
        json = reasssignCatalogAPIAccessToken(user, url, null);
    }

    if (json == null) {
        Logger.error("XZK:001 Null search result for " + user.firstName + " for album key" + album_key);
        return null;
    }

    JsonArray searchArray = json.getAsJsonObject().getAsJsonArray("albums");

    JsonObject searchResult;

    if (searchArray == null) {
        Logger.error("Null searchArray in Rdio.java");
        Logger.info(json.toString());
        return null;
    }
    // Logger.info(searchArray.toString());
    if (searchArray.size() < 1) {
        // @TODO Add flag to album to ignore in future
        Logger.error("Album " + album_key + " is missing from Napster catalog");
        return null;
    }
    searchResult = searchArray.get(0).getAsJsonObject();

    if (album == null) {
        Logger.info("No album at all, creating..0");
        album = new Album();
    }
    if (searchResult.get("name") == null) {
        Logger.error("Strange error:" + searchResult.toString());
        return null;
    }
    album.rdio_key = album_key;
    album.name = searchResult.get("name").getAsString();
    album.artist = searchResult.getAsJsonPrimitive("artistName").getAsString();
    String dateString = searchResult.getAsJsonPrimitive("released").getAsString();
    album.releaseDate = new DateTime(dateString).toDate();
    JsonObject linked = searchResult.getAsJsonObject("linked");
    JsonArray imagesArray = linked.getAsJsonArray("images");
    JsonElement imageElement = imagesArray.get(0);
    album.icon = imageElement.getAsJsonObject().get("url").getAsString();
    album.baseIcon = album.icon;
    album.bigIcon = album.icon;
    JsonArray tracks = linked.getAsJsonArray("tracks");
    Iterator<JsonElement> iterator = tracks.iterator();
    int trackNum = 1;
    album.albumTracks = new ArrayList<Track>();

    int tracksAdded = 0;
    while (iterator.hasNext()) {
        JsonObject trackObj = iterator.next().getAsJsonObject();
        Track track = Track.find("byRdio_Id", trackObj.get("id").getAsString()).first();

        if (track == null) {
            track = new Track();
            RdioHelper.parseNewTrack(user, track, trackObj, true);

        }

        // Make sure track is not already present
        boolean trackPresent = false;

        Iterator iter = album.albumTracks.iterator();
        while (iter.hasNext()) {
            Track albumTrack = (Track) iter.next();
            if (albumTrack.rdio_id == track.rdio_id) {
                trackPresent = true;
                break;
            }
        }

        if (trackPresent) {
            Logger.error("Trying to add a track to an album but it already exists in album!");
        } else {
            tracksAdded++;
            track.album = album;
            album.albumTracks.add(track);
        }
    }

    album.tracksLoaded = true;
    album.save();
    //Logger.info("Saved album " + album.rdio_key + " and added " + tracksAdded + " tracks.");
    return album;

}

From source file:controllers.Rdio.java

License:Open Source License

public static List retrieveAlbumsForArtist(User user, String artist_key) {
    Logger.info("Rdio.retrieveAlbumsForArtist" + artist_key);

    // Now load discography

    ArrayList<Album> albumResults = new ArrayList();
    WSRequest sign;/*from  ww  w .ja  v a  2  s  .  com*/

    String url = endpoint + "artists/" + artist_key + "/albums" + "?apikey="
            + Play.configuration.getProperty("rdio.key") + "&limit=200";

    //Logger.info(url);

    try {
        sign = getConnector(user).sign(user.rdioCreds, WS.url(url), "GET");
    } catch (Exception ex) {
        Logger.error(ex.toString());
        ex.printStackTrace();
        return albumResults;
    }

    JsonElement searchResult = sign.get().getJson();
    JsonElement albumsJsonElem = searchResult.getAsJsonObject().get("albums");
    JsonArray albumsArray = albumsJsonElem.getAsJsonArray();

    //Logger.info(searchResult.toString());

    JsonArray discs = albumsArray;

    //Logger.info(discs.toString());

    Iterator<JsonElement> iterator = discs.iterator();

    while (iterator.hasNext()) {
        JsonElement elem = iterator.next();
        JsonObject jsonAlbum = elem.getAsJsonObject();
        String aKey = jsonAlbum.get("id").getAsString();

        Album album = Album.find("byRdio_key", aKey).first();

        if (album != null) {
            //Logger.info("Found album " + album.rdio_key);
            Album foundAlbum = album;

            AlbumRating albumRating = AlbumRating.find("byUserAndRdio_key", user, foundAlbum.rdio_key).first();

            if (albumRating == null) {
                albumRating = new AlbumRating();
                albumRating.rdio_key = foundAlbum.rdio_key;
                albumRating.user = user;
                albumRating.rating = -1L;
                albumRating.artist_name = foundAlbum.artist;
                albumRating.album_name = foundAlbum.name;
                albumRating.numOfRatingStars = LibraryItem.getStarCount(albumRating.rating);
            }

            foundAlbum.album_rating = albumRating;

            albumRating.save();
            albumResults.add(foundAlbum);
            //Logger.info(foundAlbum.name);
            continue;
        } else {
            // Logger.info("No matches for album, so loading album " +artist_key);
            album = new Album();
            album.albumTracks = new ArrayList();
        }

        album.rdio_key = aKey;

        //Logger.info(jsonAlbum.toString());
        album.name = jsonAlbum.get("name").getAsString();

        album.artist = jsonAlbum.getAsJsonPrimitive("artistName").getAsString();
        if (jsonAlbum.get("duration") != null) {
            album.duration = jsonAlbum.get("duration").getAsInt();
        }

        // Grab album detail

        url = endpoint + "albums/" + album.rdio_key + "?include=tracks,images";
        try {
            sign = getConnector(user).sign(user.rdioCreds, WS.url(url), "GET");
            sign.setParameter("apikey", Play.configuration.getProperty("rdio.key"));
            sign.setParameter("limit", "100");
        } catch (Exception ex) {
            Logger.error(ex.toString());
            ex.printStackTrace();
            return albumResults;
        }

        //Logger.info(url + "&apiKey=");
        elem = sign.get().getJson();
        // Logger.info(elem.toString());
        JsonArray albums = elem.getAsJsonObject().getAsJsonArray("albums");

        JsonObject thisAlbum = albums.get(0).getAsJsonObject();
        JsonObject linked = thisAlbum.get("linked").getAsJsonObject();
        JsonArray images = linked.getAsJsonArray("images");
        // Logger.info(thisAlbum.toString());
        album.icon = images.get(0).getAsJsonObject().get("url").getAsString();
        album.bigIcon = album.icon;
        album.baseIcon = album.icon;
        String dateString = thisAlbum.getAsJsonPrimitive("released").getAsString();
        album.releaseDate = new DateTime(dateString).toDate();
        album.duration = new Integer(0);

        JsonArray tracks = linked.getAsJsonArray("tracks").getAsJsonArray();
        Iterator<JsonElement> trackIter = tracks.iterator();
        while (trackIter.hasNext()) {
            JsonObject trackObj = trackIter.next().getAsJsonObject();

            String trackId = trackObj.get("id").getAsString();

            List AXtracks = Track.find("byRdio_id", trackId).fetch();

            Track track = null;
            if (AXtracks.size() > 0) {
                track = (Track) AXtracks.get(0);
            }

            if (track == null) {
                track = new Track();
                //                    track.rdio_id = trackObj.get("id").getAsString(); // the object key of the track
                //                    track.save();

                RdioHelper.parseNewTrack(user, track, trackObj, true);
                track.coverArt = album.icon;

            }
            album.duration += (int) track.duration;

        }

        AlbumRating albumRating = AlbumRating.find("byUserAndRdio_key", user, album.rdio_key).first();

        if (albumRating == null) {
            albumRating = new AlbumRating();
            albumRating.rdio_key = album.rdio_key;
            albumRating.user = user;
            albumRating.rating = -1L;
            albumRating.artist_name = album.artist;
            albumRating.album_name = album.name;
            albumRating.numOfRatingStars = LibraryItem.getStarCount(albumRating.rating);
        }

        // Logger.info("Duration:" + album.duration);

        album = album.save();
        album.album_rating = albumRating;

        albumRating.save();

        albumResults.add(album);
    }
    return albumResults;
}

From source file:controllers.Rdio.java

License:Open Source License

@NoBinding
public static Artist searchArtist(User user, String artist_name) {
    Logger.info("Rdio.searchArtist");
    ArrayList trackResults = null;
    Artist artist = null;//from w w w. ja  va 2 s  .co  m
    // try {

    //String url = endpoint + "search?apikey=" + Play.configuration.getProperty("rdio.key") + "&q=" + URLEncoder.encode(artist_name) + "&type=artist";
    String url = endpoint + "search";
    //Logger.info(url);
    WSRequest sign;
    try {
        sign = getConnector(user).sign(user.rdioCreds, WS.url(url), "GET");
        sign.setParameter("type", "artist");
        sign.setParameter("q", URLEncoder.encode(artist_name));
        sign.setParameter("apikey", Play.configuration.getProperty("rdio.key"));
    } catch (Exception ex) {
        Logger.error(ex.toString());
        ex.printStackTrace();
        return null;
    }
    JsonElement searchResult = sign.get().getJson();
    //Logger.info(searchResult.toString());

    JsonArray results = searchResult.getAsJsonArray();

    JsonObject artistResult = null;

    for (JsonElement result : results) {
        JsonObject resObj = result.getAsJsonObject();
        //Logger.info(resObj.toString());

        if (resObj.get("name").getAsString().equals(artist_name)) {
            artistResult = resObj;
            Logger.info("Found artist " + artist_name + " with " + artistResult.get("id").getAsString());
            break;

        }
    }
    if (artistResult == null) {
        Logger.error("Trying to get artist result for non existent artist");
        return null;
    }

    Artist newArtist = new Artist();
    newArtist.rdio_key = artistResult.get("id").getAsString();
    newArtist.name = artistResult.get("name").getAsString();

    // Grab image
    url = endpoint + "artists/" + newArtist.rdio_key + "/images";
    try {
        sign = getConnector(user).sign(user.rdioCreds, WS.url(url), "GET");
        sign.setParameter("type", "artist");
        sign.setParameter("q", URLEncoder.encode(artist_name));
        sign.setParameter("apikey", Play.configuration.getProperty("rdio.key"));
    } catch (Exception ex) {
        Logger.error(ex.toString());
        ex.printStackTrace();
        return null;
    }

    JsonElement imgResp = sign.get().getJson();
    JsonArray imgArray = imgResp.getAsJsonArray();
    JsonObject firstimage = imgArray.iterator().next().getAsJsonObject();
    newArtist.baseIcon = firstimage.get("url").getAsString();
    newArtist.icon = newArtist.baseIcon;

    return newArtist;

}

From source file:de.winniehell.battlebeavers.storage.SoldierDeserializer.java

License:Open Source License

@Override
public Soldier deserialize(final JsonElement pJson, final Type pType, final JsonDeserializationContext pContext)
        throws JsonParseException {
    if (!pJson.isJsonObject()) {
        return null;
    }//  w  w  w . j  av a  2  s .  com

    final JsonObject object = pJson.getAsJsonObject();

    if (!object.has("id") || !object.has("team") || !object.has("tile") || !object.has("view_angle")
            || !object.has("hp")) {
        return null;
    }

    final Soldier soldier = new Soldier(object.get("team").getAsInt(),
            (Tile) pContext.deserialize(object.get("tile"), Tile.class));

    soldier.setId(object.get("id").getAsInt());
    soldier.setRotation(object.get("view_angle").getAsFloat());
    soldier.setHp(object.get("hp").getAsInt());

    if (object.has("waypoints") && object.get("waypoints").isJsonArray()) {
        currentSoldier = soldier;

        synchronized (currentSoldier) {
            final JsonArray waypoints = object.get("waypoints").getAsJsonArray();

            final Iterator<JsonElement> it = waypoints.iterator();

            if (it.hasNext()) {
                final WayPoint firstWaypoint = pContext.deserialize(it.next(), WayPoint.class);

                if (firstWaypoint.getAim() != null) {
                    soldier.getFirstWaypoint().setAim(firstWaypoint.getAim().getTile());
                }
            }

            while (it.hasNext()) {
                final WayPoint waypoint = pContext.deserialize(it.next(), WayPoint.class);

                soldier.addWayPoint(waypoint);
            }

            currentSoldier = null;
        }
    }

    return soldier;
}

From source file:DS.Model.java

private String parseResponse(String json) {
    JsonParser parser = new JsonParser();
    JsonElement jsonTree = parser.parse(json); //Parse json from yelp
    JsonObject jsonReply = new JsonObject();
    JsonArray jsonReplyArray = new JsonArray(); //The json that will be sent to Android

    //Check to see if the json element is a json object
    if (jsonTree.isJsonObject()) {
        JsonObject jsonObject = jsonTree.getAsJsonObject();
        JsonArray jarray = jsonObject.getAsJsonArray("businesses");

        //Loop through the businesses that were sent in the json array
        Iterator i = jarray.iterator();
        while (i.hasNext()) {
            //get the name, rating, and address from the business
            //Add the information to the replyBusiness json which will be sent to Android
            JsonObject replyBusiness = new JsonObject();
            JsonObject business = (JsonObject) i.next();

            String name = business.get("name").getAsString();
            replyBusiness.addProperty("name", name);

            String rating = business.get("rating").getAsString();
            replyBusiness.addProperty("rating", rating);

            JsonElement location = business.get("location");
            JsonObject locObject = location.getAsJsonObject();
            JsonArray addressArray = locObject.getAsJsonArray("display_address");
            Iterator i2 = addressArray.iterator();
            String displayAddress = "";

            //The address is split across multiple lines, so retrieve all lines and combine into one line
            while (i2.hasNext()) {
                JsonElement line = (JsonElement) i2.next();
                displayAddress += line.toString();
            }/*www .j a v a  2  s  .co m*/
            displayAddress = displayAddress.replaceAll("\\\"+", " ").trim();
            replyBusiness.addProperty("address", displayAddress);
            jsonReplyArray.add(replyBusiness);

            //Try and log the restaurant to the mongodb database
            try {
                MongoConnect();
                logRestaurant(name, Double.parseDouble(rating), displayAddress);
            } finally {
                CloseMongo();
            }
        }
        jsonReply.add("businesses", jsonReplyArray);
    }

    //Returns the json string containing 3 restaurants to android
    return jsonReply.toString();
}

From source file:edu.ucla.cs.scai.canali.webapp.EntitySearchServlet.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from w w  w.ja v a2  s .  c  o m
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 *
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    WebAppUtils.printParameters(this.getServletName(), request);

    response.setContentType("application/json;charset=UTF-8");

    JsonParser jp = new JsonParser();
    JsonArray ja = jp.parse(request.getParameter("s")).getAsJsonArray();
    String label = null;
    String restrictedText;
    for (Iterator<JsonElement> it = ja.iterator(); it.hasNext();) {
        JsonObject jo = it.next().getAsJsonObject();
        label = jo.get("l").getAsString();
        restrictedText = jo.get("r").getAsString();
        break;
    }
    String endpoint = request.getParameter("e");
    String limitS = request.getParameter("l");
    int limit = 100;
    try {
        limit = Integer.parseInt(limitS);
    } catch (Exception e) {

    }
    HashMap<String, String> res[] = null;
    try {
        res = new QueryService().describeEntity(label, endpoint, limit);
    } catch (Exception ex) {
        ex.printStackTrace();
        res[0].put("Error", ex.getMessage());
    }

    Gson gson = new Gson();
    try (PrintWriter out = response.getWriter()) {
        out.println(gson.toJson(res));
        /*
         if ($_GET["callback"]) {
         $json_response = $_GET["callback"] . "(" . $json_response . 
         }")";
         */
    }
}