Example usage for android.util JsonReader close

List of usage examples for android.util JsonReader close

Introduction

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

Prototype

public void close() throws IOException 

Source Link

Document

Closes this JSON reader and the underlying Reader .

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  www  .  j av  a2 s . c  om
    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   w w  w .  j a  va2  s .  c  om
        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:com.fuzz.android.limelight.util.JSONTool.java

/**
 * Entry point reader method that starts the call of other reader methods.
 *
 * @param inputStream/*from w  ww. ja  v  a  2  s  . c om*/
 * @return Book object after reading JSON is complete
 * @throws IOException
 */
public static Book readJSON(InputStream inputStream) throws IOException {
    JsonReader jsonReader = new JsonReader(new InputStreamReader(inputStream, "UTF-8"));
    try {
        return readBook(jsonReader);
    } catch (Throwable e) {
        throw new RuntimeException(e);
    } finally {
        jsonReader.close();
    }
}

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  w w. jav a2s .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:android.support.test.espresso.web.model.ModelCodec.java

private static Object decodeViaJSONReader(String json) throws IOException {
    JsonReader reader = null;
    try {/* ww  w .j a  v  a2s  . c o  m*/
        reader = new JsonReader(new StringReader(json));
        while (true) {
            switch (reader.peek()) {
            case BEGIN_OBJECT:
                return decodeObject(reader);
            case BEGIN_ARRAY:
                return decodeArray(reader);
            default:
                throw new IllegalStateException("Bogus document: " + json);
            }
        }
    } finally {
        if (null != reader) {
            try {
                reader.close();
            } catch (IOException ioe) {
                Log.i(TAG, "json reader - close exception", ioe);
            }
        }
    }
}

From source file:pedromendes.tempodeespera.HospitalDetailActivity.java

public List<Emergency> readJsonStream(InputStream in) throws IOException {
    JsonReader reader = new JsonReader(new InputStreamReader(in, "UTF-8"));
    try {/* w  w w.j  a  v a 2s .  c  om*/
        return readHospitalDetailGetResponse(reader);
    } finally {
        reader.close();
    }
}

From source file:at.ac.tuwien.caa.docscan.logic.DataLog.java

private ArrayList<ShotLog> readJsonStream(InputStream in) throws IOException, ParseException {

    JsonReader reader = new JsonReader(new InputStreamReader(in, "UTF-8"));
    ArrayList<ShotLog> shotLog = readList(reader);
    reader.close();

    return shotLog;

}

From source file:com.example.propertylist.handler.JsonPropertyHandler.java

/**
 * Reads the sample JSON data and loads it into a table.
 *  @param sResponse returned internet response data
 * @throws org.json.JSONException/*ww w.j ava  2 s . c  om*/
 */
public List<Property> loadPropertyData(String sResponse) throws JSONException, IOException {
    InputStream stream = new ByteArrayInputStream(sResponse.getBytes("UTF-8"));
    propertyList = new ArrayList<Property>();
    InputStreamReader inputStreamReader;
    BufferedReader bufferedReader;
    JsonReader reader;
    inputStreamReader = new InputStreamReader(stream, "UTF-8");
    bufferedReader = new BufferedReader(inputStreamReader);
    reader = new JsonReader(bufferedReader);
    propertyList = populatePropertySales(reader);
    reader.close();
    return propertyList;
}

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();/*  w  w w.  j a v 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.tcity.android.ui.info.BuildArtifactsTask.java

private void handleResponse(@NotNull HttpResponse response) throws IOException {
    JsonReader reader = new JsonReader(new InputStreamReader(response.getEntity().getContent()));

    //noinspection TryFinallyCanBeTryWithResources
    try {/*  w w  w . ja  v  a  2s  . c o  m*/
        reader.beginObject();

        while (reader.hasNext()) {
            switch (reader.nextName()) {
            case "file":
                handleFiles(reader);
                break;
            default:
                reader.skipValue();
            }
        }

        reader.endObject();
    } finally {
        reader.close();
    }
}