Example usage for android.util JsonReader endObject

List of usage examples for android.util JsonReader endObject

Introduction

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

Prototype

public void endObject() throws IOException 

Source Link

Document

Consumes the next token from the JSON stream and asserts that it is the end of the current object.

Usage

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];/*from   w  w  w .  ja  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: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  ww w .  j a  v  a2s.  c  o 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 boolean verifyAccessToken(final String[] accessTokens) throws Exception {
    final String TAG = "verfyAccessToken";
    String token = accessTokens[0];
    String userId = accessTokens[1];
    try {//from  w ww  . java  2  s  .  c o  m
        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:com.fuzz.android.limelight.util.JSONTool.java

/**
 * @param reader// ww w  . java 2  s  .  c om
 * @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:pedromendes.tempodeespera.HospitalDetailActivity.java

private List<Emergency> readHospitalDetailGetResponse(JsonReader reader) throws IOException {
    List<Emergency> result = null;
    reader.beginObject();/*from   w ww .j a v a2s .  com*/
    while (reader.hasNext()) {
        result = readResult(reader);
    }
    reader.endObject();
    return result;
}

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

/**
 * @param reader/*from  w ww  .j a v  a  2s.c  om*/
 * @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;
}

From source file:com.workday.autoparse.json.parser.JsonParserUtils.java

/**
 * Parse the next value as an object, but do not attempt to convert it or any children to a
 * known type. The returned object will be a {@link JSONObject} and all children will be
 * JSONObjects, JSONArrays, and primitives.
 *
 * @param reader The JsonReader to use. Calls to {@link JsonReader#beginObject()} and {@link
 * JsonReader#endObject()} will be taken care of by this method.
 * @param key The key corresponding to the current value. This is used to make more useful error
 * messages./*from  w  ww .j  a  v a  2s  . c  o  m*/
 */
public static JSONObject parseAsJsonObject(JsonReader reader, String key) throws IOException {
    if (handleNull(reader)) {
        return null;
    }
    assertType(reader, key, JsonToken.BEGIN_OBJECT);
    JSONObject result = new JSONObject();
    reader.beginObject();
    while (reader.hasNext()) {
        try {
            result.put(reader.nextName(), parseNextValue(reader, false));
        } catch (JSONException e) {
            throw new RuntimeException("This should be impossible.", e);
        }
    }
    reader.endObject();
    return result;
}

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();/* www  .jav  a  2s . c o 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.tcity.android.ui.info.BuildInfoTask.java

@Nullable
private String getAgentName(@NotNull JsonReader reader) throws IOException {
    reader.beginObject();/*  w ww. j a  v  a2  s.co  m*/

    String result = null;

    while (reader.hasNext()) {
        switch (reader.nextName()) {
        case "name":
            result = reader.nextString();
            break;
        default:
            reader.skipValue();
        }
    }

    reader.endObject();

    return result;
}

From source file:com.tcity.android.ui.info.BuildArtifactsTask.java

@Nullable
private String getHref(@NotNull JsonReader reader) throws IOException {
    reader.beginObject();/*  w  ww  . j a va  2 s.  com*/

    String result = null;

    while (reader.hasNext()) {
        switch (reader.nextName()) {
        case "href":
            result = reader.nextString();
            break;
        default:
            reader.skipValue();
        }
    }

    reader.endObject();

    return result;
}