Example usage for android.util JsonReader JsonReader

List of usage examples for android.util JsonReader JsonReader

Introduction

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

Prototype

public JsonReader(Reader in) 

Source Link

Document

Creates a new instance that reads a JSON-encoded stream from in .

Usage

From source file:Main.java

protected static JsonReader onJsonReaderCreate(Reader reader) {
    if (mJsonReader == null)
        mJsonReader = new JsonReader(reader);
    return mJsonReader;
}

From source file:dk.cafeanalog.AnalogDownloader.java

public AnalogStatus isOpen() {
    HttpURLConnection connection = null;
    JsonReader reader = null;//from www.  j  a  va  2s. c  o m

    try {
        URL url = new URL("http", "cafeanalog.dk", "api/open");
        connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        connection.connect();
        reader = new JsonReader(new InputStreamReader(connection.getInputStream()));
        reader.beginObject();
        while (!reader.nextName().equals("open")) {
            reader.skipValue();
        }
        return reader.nextBoolean() ? AnalogStatus.OPEN : AnalogStatus.CLOSED;
    } catch (IOException e) {
        return AnalogStatus.UNKNOWN;
    } finally {
        if (connection != null)
            connection.disconnect();
        if (reader != null) {
            try {
                reader.close();
            } catch (IOException ignored) {
            }
        }
    }
}

From source file:org.mozilla.focus.webkit.matcher.UrlMatcher.java

public static UrlMatcher loadMatcher(final Context context, final int blockListFile,
        final int[] blockListOverrides, final int entityListFile) {
    final Map<String, String> categoryPrefMap = loadDefaultPrefMap(context);

    final Map<String, Trie> categoryMap = new HashMap<>(5);
    try (final JsonReader jsonReader = new JsonReader(new InputStreamReader(
            context.getResources().openRawResource(blockListFile), StandardCharsets.UTF_8))) {
        BlocklistProcessor.loadCategoryMap(jsonReader, categoryMap, BlocklistProcessor.ListType.BASE_LIST);
    } catch (IOException e) {
        throw new IllegalStateException("Unable to parse blacklist");
    }//www.  j av a  2 s  .c o m

    if (blockListOverrides != null) {
        for (int i = 0; i < blockListOverrides.length; i++) {
            try (final JsonReader jsonReader = new JsonReader(new InputStreamReader(
                    context.getResources().openRawResource(blockListOverrides[i]), StandardCharsets.UTF_8))) {
                BlocklistProcessor.loadCategoryMap(jsonReader, categoryMap,
                        BlocklistProcessor.ListType.OVERRIDE_LIST);
            } catch (IOException e) {
                throw new IllegalStateException("Unable to parse override blacklist");
            }
        }
    }

    final EntityList entityList;
    try (final JsonReader jsonReader = new JsonReader(new InputStreamReader(
            context.getResources().openRawResource(entityListFile), StandardCharsets.UTF_8))) {
        entityList = EntityListProcessor.getEntityMapFromJSON(jsonReader);
    } catch (IOException e) {
        throw new IllegalStateException("Unable to parse entity list");
    }

    return new UrlMatcher(context, categoryPrefMap, categoryMap, entityList);
}

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//from w  w w  .j  a  va 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();//from  w w  w.  j a  va 2  s.c o 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.BuildInfoTask.java

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

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

        BuildInfoData data = new BuildInfoData();
        SimpleDateFormat dateFormat = new SimpleDateFormat(Common.TEAMCITY_DATE_FORMAT);

        while (reader.hasNext()) {
            switch (reader.nextName()) {
            case "status":
                if (data.status == null) {
                    data.status = com.tcity.android.Status.valueOf(reader.nextString());
                }
                break;
            case "running":
                if (reader.nextBoolean()) {
                    data.status = com.tcity.android.Status.RUNNING;
                }
                break;
            case "branchName":
                data.branch = reader.nextString();
                break;
            case "defaultBranch":
                data.isBranchDefault = reader.nextBoolean();
                break;
            case "statusText":
                data.result = reader.nextString();
                break;
            case "waitReason":
                data.waitReason = reader.nextString();
                break;
            case "queuedDate":
                data.queued = dateFormat.parse(reader.nextString());
                break;
            case "startDate":
                data.started = dateFormat.parse(reader.nextString());
                break;
            case "finishDate":
                data.finished = dateFormat.parse(reader.nextString());
                break;
            case "agent":
                data.agent = getAgentName(reader);
                break;
            default:
                reader.skipValue();
            }
        }

        myResult = data;

        reader.endObject();
    } finally {
        reader.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 {/* w w w. ja v a  2  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: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 {/*from   w  ww  .j  av a 2s .co m*/
        reader.beginObject();

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

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

From source file:com.morlunk.leeroy.LeeroyUpdateService.java

private void handleCheckUpdates(Intent intent, boolean notify, ResultReceiver receiver) {
    List<LeeroyApp> appList = LeeroyApp.getApps(getPackageManager());

    if (appList.size() == 0) {
        return;/*  w w  w .j a v  a  2s  . co  m*/
    }

    List<LeeroyAppUpdate> updates = new LinkedList<>();
    List<LeeroyApp> notUpdatedApps = new LinkedList<>();
    List<LeeroyException> exceptions = new LinkedList<>();
    for (LeeroyApp app : appList) {
        try {
            String paramUrl = app.getJenkinsUrl() + "/api/json?tree=lastSuccessfulBuild[number,url]";
            URL url = new URL(paramUrl);
            URLConnection conn = url.openConnection();
            Reader reader = new InputStreamReader(conn.getInputStream());

            JsonReader jsonReader = new JsonReader(reader);
            jsonReader.beginObject();
            jsonReader.nextName();
            jsonReader.beginObject();

            int latestSuccessfulBuild = 0;
            String buildUrl = null;
            while (jsonReader.hasNext()) {
                String name = jsonReader.nextName();
                if ("number".equals(name)) {
                    latestSuccessfulBuild = jsonReader.nextInt();
                } else if ("url".equals(name)) {
                    buildUrl = jsonReader.nextString();
                } else {
                    throw new RuntimeException("Unknown key " + name);
                }
            }
            jsonReader.endObject();
            jsonReader.endObject();
            jsonReader.close();

            if (latestSuccessfulBuild > app.getJenkinsBuild()) {
                LeeroyAppUpdate update = new LeeroyAppUpdate();
                update.app = app;
                update.newBuild = latestSuccessfulBuild;
                update.newBuildUrl = buildUrl;
                updates.add(update);
            } else {
                notUpdatedApps.add(app);
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
            CharSequence appName = app.getApplicationInfo().loadLabel(getPackageManager());
            exceptions.add(new LeeroyException(app, getString(R.string.invalid_url, appName), e));
        } catch (IOException e) {
            e.printStackTrace();
            exceptions.add(new LeeroyException(app, e));
        }
    }

    if (notify) {
        NotificationManagerCompat nm = NotificationManagerCompat.from(this);
        if (updates.size() > 0) {
            NotificationCompat.Builder ncb = new NotificationCompat.Builder(this);
            ncb.setSmallIcon(R.drawable.ic_stat_update);
            ncb.setTicker(getString(R.string.updates_available));
            ncb.setContentTitle(getString(R.string.updates_available));
            ncb.setContentText(getString(R.string.num_updates, updates.size()));
            ncb.setPriority(NotificationCompat.PRIORITY_LOW);
            ncb.setVisibility(NotificationCompat.VISIBILITY_PUBLIC);
            Intent appIntent = new Intent(this, AppListActivity.class);
            appIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
            ncb.setContentIntent(
                    PendingIntent.getActivity(this, 0, appIntent, PendingIntent.FLAG_CANCEL_CURRENT));
            ncb.setAutoCancel(true);
            NotificationCompat.InboxStyle style = new NotificationCompat.InboxStyle();
            for (LeeroyAppUpdate update : updates) {
                CharSequence appName = update.app.getApplicationInfo().loadLabel(getPackageManager());
                style.addLine(getString(R.string.notify_app_update, appName, update.app.getJenkinsBuild(),
                        update.newBuild));
            }
            style.setSummaryText(getString(R.string.app_name));
            ncb.setStyle(style);
            ncb.setNumber(updates.size());
            nm.notify(NOTIFICATION_UPDATE, ncb.build());
        }

        if (exceptions.size() > 0) {
            NotificationCompat.Builder ncb = new NotificationCompat.Builder(this);
            ncb.setSmallIcon(R.drawable.ic_stat_error);
            ncb.setTicker(getString(R.string.error_checking_updates));
            ncb.setContentTitle(getString(R.string.error_checking_updates));
            ncb.setContentText(getString(R.string.click_to_retry));
            ncb.setPriority(NotificationCompat.PRIORITY_LOW);
            ncb.setVisibility(NotificationCompat.VISIBILITY_PUBLIC);
            ncb.setContentIntent(PendingIntent.getService(this, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT));
            ncb.setAutoCancel(true);
            ncb.setNumber(exceptions.size());
            nm.notify(NOTIFICATION_ERROR, ncb.build());
        }
    }

    if (receiver != null) {
        Bundle results = new Bundle();
        results.putParcelableArrayList(EXTRA_UPDATE_LIST, new ArrayList<>(updates));
        results.putParcelableArrayList(EXTRA_NO_UPDATE_LIST, new ArrayList<>(notUpdatedApps));
        results.putParcelableArrayList(EXTRA_EXCEPTION_LIST, new ArrayList<>(exceptions));
        receiver.send(0, results);
    }
}

From source file:fiskinfoo.no.sintef.fiskinfoo.Http.BarentswatchApiRetrofit.BarentswatchApi.java

public BarentswatchApi() {
    String directoryPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)
            .toString();/*w  w  w .j ava 2 s.co m*/
    String fileName = directoryPath + "/FiskInfo/api_setting.json";
    File file = new File(fileName);
    String environment = null;

    if (file.exists()) {
        InputStream inputStream;
        InputStreamReader streamReader;
        JsonReader jsonReader;

        try {
            inputStream = new BufferedInputStream(new FileInputStream(file));
            streamReader = new InputStreamReader(inputStream, "UTF-8");
            jsonReader = new JsonReader(streamReader);

            jsonReader.beginObject();
            while (jsonReader.hasNext()) {
                String name = jsonReader.nextName();
                if (name.equals("environment")) {
                    environment = jsonReader.nextString();
                } else {
                    jsonReader.skipValue();
                }
            }
            jsonReader.endObject();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (IllegalStateException e) {
            e.printStackTrace();
        }
    }

    targetProd = !"pilot".equals(environment);
    currentPath = targetProd ? barentsWatchProdAddress : barentsWatchPilotAddress;
    BARENTSWATCH_API_ENDPOINT = currentPath + "/api/v1/geodata";

    Executor httpExecutor = Executors.newSingleThreadExecutor();
    MainThreadExecutor callbackExecutor = new MainThreadExecutor();
    barentswatchApi = initializeBarentswatchAPI(httpExecutor, callbackExecutor);
}