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:org.xenmaster.web.APICallDecoder.java

License:Open Source License

protected Object[] deserializeToArray(JsonArray arr) {
    ArrayList array = new ArrayList();
    for (Iterator<JsonElement> it = arr.iterator(); it.hasNext();) {
        array.add(deserialize(it.next()));
    }/*from w w w .java 2s. c o m*/
    return array.toArray();
}

From source file:retrievers.SoundcloudRetriever.java

License:BSD License

public Collection<Sound> getSoundsForTag(String tag) {
    String tagDecoded = "";
    String tagEncoded = "";
    try {//from  ww  w .ja  v a 2s  .  com
        tagDecoded = URLDecoder.decode(tag, "UTF-8");
        System.out.println("TagDecoded: " + tagDecoded);
    } catch (UnsupportedEncodingException e1) {
        e1.printStackTrace();
    }
    Collection<Sound> sounds = Lists.newArrayList();
    StringBuilder requestURL = new StringBuilder();
    requestURL.append("https://api.soundcloud.com/");
    requestURL.append("tracks?");
    requestURL.append("client_id=");
    requestURL.append(StedrConstants.SOUNDCLOUD_CLIENT_ID);
    requestURL.append("&q=");
    tagDecoded = tagDecoded.replaceAll(" ", "+");
    tagDecoded = tagDecoded.toLowerCase();
    //tag = tag.toLowerCase();
    System.out.println("Tag: " + tag);
    try {
        tagEncoded = URLEncoder.encode(tagDecoded, "UTF-8");
        //System.out.println("TagEecoded: " + tagEncoded);
    } catch (UnsupportedEncodingException e1) {
        tagEncoded = "stedr";
    }
    tagEncoded = tagEncoded.replaceAll("%2B", "+");
    requestURL.append(tagEncoded);
    requestURL.append("+stedr");
    // get response from the API
    System.out.println("The request URL: " + requestURL);
    String document = HttpUtils.getDocument(requestURL.toString());
    //System.out.println("The response is: " + document);

    // parse response into JSON document
    JsonParser jp = new JsonParser();
    JsonElement jsonDocument = jp.parse(document);

    // find the track elements
    JsonArray trackArray = jsonDocument.getAsJsonArray();
    // iterate over and find info about sound tracks      
    Iterator<JsonElement> trackIter = trackArray.iterator();
    while (trackIter.hasNext()) {
        JsonObject track = trackIter.next().getAsJsonObject();
        Sound s = new Sound();

        String title = getStringWithoutQuotes(track.get("title").toString());
        if (title != null)
            title = convertString(title);
        System.out.println("The title: " + title);
        String tags = track.get("tag_list").toString();
        System.out.println("The tags: " + tags);

        System.out.println("The track: " + track);
        if ((title.contains("stedr")) || (tags.contains("stedr"))) {

            s.setTitle(title);

            if (track.get("permalink_url") != null)
                s.setUrl(getStringWithoutQuotes(track.get("permalink_url").toString()));

            if (track.get("artwork_url") != null)
                s.setArtworkURL(getStringWithoutQuotes(track.get("artwork_url").toString()));

            s.setDescription(convertString(getStringWithoutQuotes(track.get("description").toString())));
            s.setWaveformURL(getStringWithoutQuotes(track.get("waveform_url").toString()));

            s.setFavoriteCount(track.get("favoritings_count").toString());
            s.setStreamURL(getStringWithoutQuotes(track.get("stream_url").toString()) + "?client_id="
                    + StedrConstants.SOUNDCLOUD_CLIENT_ID);

            JsonObject user = track.getAsJsonObject("user");
            s.setAvatarURL(getStringWithoutQuotes(user.get("avatar_url").toString()));
            s.setUsername(getStringWithoutQuotes(user.get("username").toString()));

            if (s.getTitle().length() > 1 && s.getUrl().length() > 22) {
                sounds.add(s);
            }
        }
    }
    return sounds;
}

From source file:securesocial.provider.providers.GitHubProvider.java

License:Apache License

private List<String> extractOrganizations(JsonArray userOrganizations) {
    List<String> organizations = new ArrayList<String>();

    Iterator<JsonElement> i = userOrganizations.iterator();

    while (i.hasNext()) {
        JsonObject userOrganization = i.next().getAsJsonObject();
        String organization = userOrganization.get(LOGIN).getAsString();

        organizations.add(organization);
    }/*  ww  w .j a  v  a 2  s.c om*/

    return organizations;
}

From source file:securesocial.provider.providers.YahooOAuth2Provider.java

License:Apache License

@Override
protected void fillProfile(SocialUser user, Map<String, Object> authContext) {
    Logger.info("!-*-------------------------USER ACESS TOKEN " + user.accessToken);

    //OBS: Eduardo Medeiros quem fez =D - Implementacao diferente da do googleOauth2provider\
    //OBS: O Yahoo requer o token no cabecalho, ja o Google envia o token como parametro

    JsonObject me = WS.url(ME_API)//  www  .  j  a v a  2s.c  o  m
            .setHeader("Authorization",
                    new StringBuilder("Bearer").append(SPACE).append(user.accessToken).toString())
            .get().getJson().getAsJsonObject();
    JsonObject error = me.getAsJsonObject(ERROR);
    Logger.info("!-*-------------------------MEEEE " + me);

    if (error != null) {
        final String message = error.get(MESSAGE).getAsString();
        final String type = error.get(TYPE).getAsString();
        Logger.error("Error retrieving profile information from Yahoo. Error type: %s, message: %s.", type,
                message);
        throw new AuthenticationException();
    }

    //        {"profile":
    //            {"guid":"QAI7B3PCDJQZ662E7CAJAAECME",
    //                    "addresses":[{"city":"","country":"BR","current":true,"id":1,"postalCode":"","state":"","street":"","type":"HOME"},{"city":"","country":"BR","current":true,"id":2,"postalCode":"","state":"","street":"","type":"WORK"}],
    //                "ageCategory":"A",
    //                    "created":"2015-12-01T23:23:43Z",
    //                    "emails":[{"handle":"brnwebbery@yahoo.com","id":1,"primary":true,"type":"HOME"}],
    //                "familyName":"Silva",
    //                    "gender":"M",
    //                    "givenName":"Bruno",
    //                    "image":{"height":192,"imageUrl":"https://s.yimg.com/dh/ap/social/profile/profile_b192.png","size":"192x192","width":192},
    //                "intl":"br",
    //                    "jurisdiction":"br",
    //                    "lang":"pt-BR",
    //                    "memberSince":"2015-11-29T20:55:29Z",
    //                    "migrationSource":1,
    //                    "nickname":"Bruno",
    //                    "notStored":true,
    //                    "nux":"0",
    //                    "phones":[{"id":10,"number":"55-8488312000","type":"MOBILE"}],
    //                "profileMode":"PUBLIC",
    //                    "profileStatus":"ACTIVE",
    //                    "profileUrl":"http://profile.yahoo.com/QAI7B3PCDJQZ662E7CAJAAECME",
    //                    "timeZone":"America/Buenos_Aires",
    //                    "isConnected":true,
    //                    "profileHidden":false,
    //                    "bdRestricted":true,
    //                    "profilePermission":"PRIVATE",
    //                    "uri":"https://social.yahooapis.com/v1/user/QAI7B3PCDJQZ662E7CAJAAECME/profile"}}
    //        user.id.id = me.get(ID).getAsString();

    JsonObject profile = me.get(PROFILE).getAsJsonObject();

    String id = profile.get("guid").getAsString();

    JsonElement givenName = profile.get("givenName");
    JsonElement nickName = profile.get("givenName");
    String fullName = (givenName != null) ? givenName.getAsString()
            : ((nickName != null) ? nickName.getAsString() : null);
    String surName = (profile.get("familyName")) != null ? profile.get("familyName").getAsString() : null;
    String gender = profile.get("gender") != null ? profile.get("gender").getAsString() : null;
    JsonObject image = profile.get("image") != null ? profile.get("image").getAsJsonObject() : null;
    String url = image != null ? image.get("imageUrl").getAsString() : null;
    JsonArray j = profile.get("emails").getAsJsonArray();
    String asdasd = j != null ? j.iterator().next().getAsJsonObject().get("handle").getAsString() : null;

    user.id.id = id;
    user.email = asdasd;
    user.displayName = new StringBuilder(fullName).append(SPACE).append(surName).toString();
    user.avatarUrl = url;
}

From source file:ServerPages.tingtong.java

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    DataBaseEntry dbEntry = new DataBaseEntry();
    Connection con = dbEntry.getDbConnection();
    try (PrintWriter out = response.getWriter()) {
        /* TODO output your page here. You may use following sample code. */
        String sqlString = "INSERT INTO COOKIE VALUES (? , ? , ? , ?)";
        String getconid = "SELECT MAX(CONN_ID) FROM COOKIE";
        Gson gson = new Gson();
        String userName = request.getParameter("cookieValue");
        JsonElement jelem = gson.fromJson(userName, JsonElement.class);
        JsonObject jobj = jelem.getAsJsonObject();
        JsonArray arr = jobj.getAsJsonArray("Cookies");
        Iterator it = arr.iterator();
        Statement connStmt = con.createStatement();
        ResultSet rs = connStmt.executeQuery(getconid);
        String temp = null;/*  www.  ja  va2 s.  c  om*/
        while (rs.next()) {
            temp = rs.getString("MAX(CONN_ID)");
        }
        if (temp == null)
            connectionID = 0;
        else
            connectionID = Integer.parseInt(temp);
        connectionID++;
        while (it.hasNext()) {
            PreparedStatement stmt = con.prepareStatement(sqlString);
            JsonObject innerObj = (JsonObject) it.next();
            String cookieName = innerObj.get("CookieName").getAsString();
            String cookieValue = innerObj.get("CookieValue").getAsString();
            String cookieDomain = innerObj.get("CookieDomain").getAsString();
            stmt.setInt(1, connectionID);
            stmt.setString(2, cookieName);
            stmt.setString(3, cookieValue);
            stmt.setString(4, cookieDomain);
            int result = stmt.executeUpdate();
            if (result == 0) {
                out.write("The Result of Insertion is Failure");
            } else {
                out.write("The Result of Insertion is Success");
            }
        }
    } catch (Exception e) {
        System.out.println("The Exception Caught in tington" + e.toString());
    } finally {
        dbEntry.resetConnection();
    }
}

From source file:tk.wurst_client.files.FileManager.java

License:Open Source License

public void loadXRayBlocks() {
    try {/*from   ww w .j a va2  s .com*/
        BufferedReader load = new BufferedReader(new FileReader(xray));
        JsonArray json = JsonUtils.jsonParser.parse(load).getAsJsonArray();
        load.close();
        Iterator<JsonElement> itr = json.iterator();
        while (itr.hasNext())
            try {
                String jsonBlock = itr.next().getAsString();
                XRayMod.xrayBlocks.add(Block.getBlockFromName(jsonBlock));
            } catch (Exception e) {
                e.printStackTrace();
            }
        XRayUtils.sortBlocks();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:ua.pp.msk.cliqr.validators.JobValidator.java

License:Apache License

private boolean validateCloudParams(JsonElement je) throws ParameterException {
    if (je.isJsonObject()) {
        JsonObject jo = je.getAsJsonObject();
        if (!jo.has(CLOUD)) {
            throw new MissingParameterException("Missing Cloud propery in cloud parameters");
        }/*  w w  w  .  j ava 2  s  .c  o  m*/
        if (!jo.has(INSTANCE)) {
            throw new MissingParameterException("Missing instance property in cloud parameters");
        } else {
            validateInstance(jo.get(INSTANCE).getAsString());
        }
        if (!jo.has(CLOUDPROPERTIES)) {
            if (!jo.get(CLOUDPROPERTIES).isJsonArray()) {
                throw new WrongParameterException("Cloud properties  should be a json array");
            } else {
                JsonArray ja = jo.get(CLOUDPROPERTIES).getAsJsonArray();
                Iterator<JsonElement> iterator = ja.iterator();
                while (iterator.hasNext()) {
                    validateNVJson(iterator.next());
                }
            }
        }

    } else {
        throw new WrongParameterException("Cloud parameters should be a JSON Object");
    }
    return true;
}

From source file:ua.pp.msk.cliqr.validators.JobValidator.java

License:Apache License

private boolean validateAppParams(JsonElement je) throws ParameterException {
    if (!je.isJsonArray()) {
        throw new WrongParameterException("Application parameters should be a json array");
    } else {//from ww  w  . j  av  a2s.c om
        JsonArray ja = je.getAsJsonArray();
        Iterator<JsonElement> iterator = ja.iterator();
        while (iterator.hasNext()) {
            validateNVJson(iterator.next());
        }
    }
    return true;
}

From source file:ua.pp.msk.cliqr.validators.JobValidator.java

License:Apache License

private boolean validateJobs(JsonElement je) throws ParameterException {
    if (!je.isJsonArray()) {
        throw new WrongParameterException("Jobs property  should be a json array");
    } else {/* w w w . j ava 2  s.  c  o m*/
        JsonArray ja = je.getAsJsonArray();
        Iterator<JsonElement> iterator = ja.iterator();
        while (iterator.hasNext()) {
            validateJob(iterator.next());
        }
    }
    return true;
}