Example usage for android.util JsonReader hasNext

List of usage examples for android.util JsonReader hasNext

Introduction

In this page you can find the example usage for android.util JsonReader hasNext.

Prototype

public boolean hasNext() throws IOException 

Source Link

Document

Returns true if the current array or object has another element.

Usage

From source file:Main.java

/**
 * Read Access token from Json object that we got from O8 Auth server.
 * /*from  w  w w  .j  a v a 2s  .com*/
 */
private static String getAccessToken(JsonReader reader) throws IOException {
    String text = null;

    try {
        reader.beginObject();
        while (reader.hasNext()) {
            String name = reader.nextName();
            if (name.equals("access_token")) {
                text = reader.nextString();
                break;
            }
        }

        //reader.endObject();
    } catch (IOException ex) {
        Log.e(TAG, ex.getStackTrace().toString());
    }
    return text;
}

From source file:org.liberty.android.fantastischmemo.downloader.quizlet.lib.java

public static boolean verifyAccessToken(final String[] accessTokens) throws Exception {
    final String TAG = "verfyAccessToken";
    String token = accessTokens[0];
    String userId = accessTokens[1];
    try {/*w  ww .  j  a va2  s.  c  om*/
        URL url1 = new URL(QUIZLET_API_ENDPOINT + "/users/" + userId);
        HttpsURLConnection conn = (HttpsURLConnection) url1.openConnection();
        conn.addRequestProperty("Authorization", "Bearer " + String.format(token));

        JsonReader s = new JsonReader(new InputStreamReader((conn.getInputStream()), "UTF-8"));
        s.beginObject();
        while (s.hasNext()) {
            String name = s.nextName();
            if ("error".equals(name)) {
                String error = s.nextString();
                Log.e(TAG, "Token validation error: " + error);
                return false;
            } else {
                s.skipValue();
            }
        }
        s.endObject();
        s.close();

    } catch (Exception e) {
        Log.i(TAG, "The saved access token is invalid", e);
        return false;
    }
    return true;
}

From source file:org.liberty.android.fantastischmemo.downloader.quizlet.lib.java

private static String makePostApiCall(URL url, String content, String authToken) throws IOException {
    HttpsURLConnection conn = null;
    OutputStreamWriter writer = null;
    String res = "";
    try {/*from w  w  w .  j  a v  a  2  s.co m*/
        conn = (HttpsURLConnection) url.openConnection();
        conn.setDoInput(true);
        conn.setDoOutput(true);
        conn.setRequestMethod("POST");
        conn.addRequestProperty("Authorization", "Bearer " + authToken);
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

        writer = new OutputStreamWriter(conn.getOutputStream());
        writer.write(content);
        writer.close();

        if (conn.getResponseCode() / 100 >= 3) {
            Log.v("makePostApiCall", "Post content is: " + content);
            String error = "";
            try {
                JsonReader r = new JsonReader(new InputStreamReader(conn.getErrorStream(), "UTF-8"));
                r.beginObject();
                while (r.hasNext()) {
                    error += r.nextName() + ": " + r.nextString() + "\r\n";
                }
                r.endObject();
                r.close();
            } catch (Throwable eex) {

            }
            Log.v("makePostApiCall", "Error string is: " + error);
            res = error;
            throw new IOException(
                    "Response code: " + conn.getResponseCode() + " URL is: " + url + " \nError: " + error);
        } else {
            JsonReader r = new JsonReader(new InputStreamReader(conn.getInputStream()));
            r.beginObject();
            while (r.hasNext()) {
                try {
                    res += r.nextName() + ": " + r.nextString() + "\n";
                } catch (Exception ex) {
                    r.skipValue();
                }
            }
            return res;
        }
    } finally {
        conn.disconnect();
        //return res;
    }
}

From source file:org.liberty.android.fantastischmemo.downloader.quizlet.lib.java

public static String[] getAccessTokens(final String[] requests) throws Exception {
    final String TAG = "getAccesTokens";
    String code = requests[0];/* w ww.  j  a  v  a  2  s  .c  o  m*/
    String clientIdAndSecret = QUIZLET_CLIENT_ID + ":" + QUIZLET_CLIENT_SECRET;
    String encodedClientIdAndSecret = Base64.encodeToString(clientIdAndSecret.getBytes(), 0);
    URL url1 = new URL("https://api.quizlet.com/oauth/token");
    HttpsURLConnection conn = (HttpsURLConnection) url1.openConnection();
    conn.addRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");

    // Add the Basic Authorization item
    conn.addRequestProperty("Authorization", "Basic " + encodedClientIdAndSecret);

    conn.setRequestMethod("POST");
    conn.setDoInput(true);
    conn.setDoOutput(true);
    String payload = String.format("grant_type=%s&code=%s&redirect_uri=%s",
            URLEncoder.encode("authorization_code", "UTF-8"), URLEncoder.encode(code, "UTF-8"),
            URLEncoder.encode(Data.RedirectURI, "UTF-8"));
    OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream());
    out.write(payload);
    out.close();

    if (conn.getResponseCode() / 100 >= 3) {
        Log.e(TAG, "Http response code: " + conn.getResponseCode() + " response message: "
                + conn.getResponseMessage());
        JsonReader r = new JsonReader(new InputStreamReader(conn.getErrorStream(), "UTF-8"));
        String error = "";
        r.beginObject();
        while (r.hasNext()) {
            error += r.nextName() + r.nextString() + "\r\n";
        }
        r.endObject();
        r.close();
        Log.e(TAG, "Error response for: " + url1 + " is " + error);
        throw new IOException("Response code: " + conn.getResponseCode());
    }

    JsonReader s = new JsonReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
    try {
        String accessToken = null;
        String userId = null;
        s.beginObject();
        while (s.hasNext()) {
            String name = s.nextName();
            if (name.equals("access_token")) {
                accessToken = s.nextString();
            } else if (name.equals("user_id")) {
                userId = s.nextString();
            } else {
                s.skipValue();
            }
        }
        s.endObject();
        s.close();
        return new String[] { accessToken, userId };
    } catch (Exception e) {
        // Throw out JSON exception. it is unlikely to happen
        throw new RuntimeException(e);
    } finally {
        conn.disconnect();
    }
}

From source file:android.support.test.espresso.web.model.ModelCodec.java

private static List<Object> decodeArray(JsonReader reader) throws IOException {
    List<Object> array = Lists.newArrayList();
    reader.beginArray();//from   w ww.j a  va 2  s .  c  o m
    while (reader.hasNext()) {
        switch (reader.peek()) {
        case BEGIN_OBJECT:
            array.add(decodeObject(reader));
            break;
        case NULL:
            reader.nextNull();
            array.add(null);
            break;
        case STRING:
            array.add(reader.nextString());
            break;
        case BOOLEAN:
            array.add(reader.nextBoolean());
            break;
        case BEGIN_ARRAY:
            array.add(decodeArray(reader));
            break;
        case NUMBER:
            array.add(decodeNumber(reader.nextString()));
            break;
        default:
            throw new IllegalStateException(String.format("%s: bogus token", reader.peek()));
        }
    }

    reader.endArray();
    return array;
}

From source file:android.support.test.espresso.web.model.ModelCodec.java

private static Object decodeObject(JsonReader reader) throws IOException {
    Map<String, Object> obj = Maps.newHashMap();
    List<String> nullKeys = Lists.newArrayList();
    reader.beginObject();/*from   ww  w  . ja  v  a  2  s .co m*/
    while (reader.hasNext()) {
        String key = reader.nextName();
        Object value = null;
        switch (reader.peek()) {
        case BEGIN_OBJECT:
            obj.put(key, decodeObject(reader));
            break;
        case NULL:
            reader.nextNull();
            nullKeys.add(key);
            obj.put(key, JSONObject.NULL);
            break;
        case STRING:
            obj.put(key, reader.nextString());
            break;
        case BOOLEAN:
            obj.put(key, reader.nextBoolean());
            break;
        case NUMBER:
            obj.put(key, decodeNumber(reader.nextString()));
            break;
        case BEGIN_ARRAY:
            obj.put(key, decodeArray(reader));
            break;
        default:
            throw new IllegalStateException(String.format("%: bogus token.", reader.peek()));
        }
    }
    reader.endObject();
    Object replacement = maybeReplaceMap(obj);
    if (null != replacement) {
        return replacement;
    } else {
        for (String key : nullKeys) {
            obj.remove(key);
        }
    }
    return obj;
}

From source file:com.fuzz.android.limelight.util.JSONTool.java

/**
 * @param reader/*w ww . ja v a  2 s.c o  m*/
 * @return list of BaseChapter objects and ChapterTransition objects from JSON
 * @throws IOException
 */
public static ArrayList<Chapter> readChapterArray(JsonReader reader) throws IOException {
    ArrayList<Chapter> chapters = new ArrayList<Chapter>();
    reader.beginArray();
    while (reader.hasNext()) {
        reader.beginObject();
        String name = reader.nextName();
        if (name.equals("type")) {
            String type = reader.nextString();

            if (type.equals("transition")) {
                chapters.add(readTransition(reader));
            } else if (type.equals("chapter")) {
                chapters.add(readChapter(reader));
            }
        }
    }
    reader.endArray();

    return chapters;
}

From source file:com.fuzz.android.limelight.util.JSONTool.java

/**
 * @param reader//  ww w .j a  va 2 s .  c  o  m
 * @return the generated BaseChapter object from the JSON
 * @throws IOException
 */
public static Chapter readChapter(JsonReader reader) throws IOException {
    long time = -1;
    boolean hasActView = false;
    BaseChapter chapter = new BaseChapter();

    while (reader.hasNext()) {
        String name = reader.nextName();
        if (name.equals("duration"))
            time = reader.nextLong();
        else if (name.equals("has_act_view"))
            hasActView = reader.nextBoolean();
        else if (name.equals("act"))
            chapter.setAct(readAct(reader));
    }
    reader.endObject();

    chapter.setTime(time);
    chapter.setHasActView(hasActView);
    return chapter;
}

From source file:com.murrayc.galaxyzoo.app.LoginUtils.java

public static LoginResult parseLoginResponseContent(final InputStream content) throws IOException {
    //A failure by default.
    LoginResult result = new LoginResult(false, null, null);

    final InputStreamReader streamReader = new InputStreamReader(content, Utils.STRING_ENCODING);
    final JsonReader reader = new JsonReader(streamReader);
    reader.beginObject();//from ww  w  .  j av a 2 s  .co  m
    boolean success = false;
    String apiKey = null;
    String userName = null;
    String message = null;
    while (reader.hasNext()) {
        final String name = reader.nextName();
        switch (name) {
        case "success":
            success = reader.nextBoolean();
            break;
        case "api_key":
            apiKey = reader.nextString();
            break;
        case "name":
            userName = reader.nextString();
            break;
        case "message":
            message = reader.nextString();
            break;
        default:
            reader.skipValue();
        }
    }

    if (success) {
        result = new LoginResult(true, userName, apiKey);
    } else {
        Log.info("Login failed.");
        Log.info("Login failure message: " + message);
    }

    reader.endObject();
    reader.close();

    streamReader.close();

    return result;
}

From source file:com.fuzz.android.limelight.util.JSONTool.java

/**
 * @param reader//from  w w w  .j ava2s  .com
 * @return the generated Book object from JSON
 * @throws IOException
 */
public static Book readBook(JsonReader reader) throws IOException {
    String title = null;
    String fontName = null;
    String packageName = null;
    ArrayList<Chapter> chapters = null;

    reader.beginObject();
    //input code for taking name data from reader and creating Book object\
    int count = 0;
    while (reader.hasNext()) {
        if (count >= 4) {
            break;
        }
        String name = reader.nextName();
        if (name.equals("title")) {
            count++;
            title = reader.nextString();
        } else if (name.equals("font")) {
            count++;
            fontName = reader.nextString();
        } else if (name.equals("package")) {
            count++;
            packageName = reader.nextString();
        } else if (name.equals("chapters")) {
            count++;
            chapters = readChapterArray(reader);
        }
    }
    reader.endObject();

    String currentPackage = LimeLight.getActivity().getPackageName();

    if (!currentPackage.equals(packageName)) {
        Toast.makeText(LimeLight.getActivity(),
                LimeLight.getActivity().getString(R.string.wrong_application) + " " + packageName,
                Toast.LENGTH_LONG).show();
        return null;
    }

    Book book = new Book();
    book.setTitle(title);
    book.setFont(fontName);
    book.setPackage(packageName);

    for (Chapter chapter : chapters) {
        book.addChapter(chapter);
    }
    return book;
}