Example usage for com.squareup.okhttp Response isSuccessful

List of usage examples for com.squareup.okhttp Response isSuccessful

Introduction

In this page you can find the example usage for com.squareup.okhttp Response isSuccessful.

Prototype

public boolean isSuccessful() 

Source Link

Document

Returns true if the code is in [200..300), which means the request was successfully received, understood, and accepted.

Usage

From source file:com.tanmay.blip.networking.XKCDDownloader.java

License:Apache License

private void redownloadLastTen() {
    final Gson gson = new Gson();
    final DatabaseManager databaseManager = new DatabaseManager(this);
    try {//from  ww w  . j  a  va 2s.  c  o m
        Request todayReq = new Request.Builder().url(LATEST_URL).build();
        Response response = BlipApplication.getInstance().client.newCall(todayReq).execute();
        if (!response.isSuccessful())
            throw new IOException();
        Comic comic = gson.fromJson(response.body().string(), Comic.class);
        final CountDownLatch latch = new CountDownLatch(10);
        final Executor executor = Executors.newFixedThreadPool(5);
        int num = comic.getNum();
        for (int i = num - 9; i <= num; i++) {
            final int index = i;
            executor.execute(new Runnable() {
                @Override
                public void run() {
                    try {
                        String url = String.format(COMICS_URL, index);
                        Request request = new Request.Builder().url(url).build();
                        Response response = BlipApplication.getInstance().client.newCall(request).execute();
                        if (!response.isSuccessful())
                            throw new IOException();
                        String responseBody = response.body().string();
                        Comic comic = null;
                        try {
                            comic = gson.fromJson(responseBody, Comic.class);
                        } catch (JsonSyntaxException e) {
                            Crashlytics.log(1, "XKCDDownloader", e.getMessage() + " POS:" + index);
                        }
                        if (comic != null) {
                            if (databaseManager.comicExists(comic)) {
                                databaseManager.updateComic(comic);
                            } else {
                                databaseManager.addComic(comic);
                            }
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                        LocalBroadcastManager.getInstance(XKCDDownloader.this)
                                .sendBroadcast(new Intent(DOWNLOAD_FAIL));
                    } finally {
                        latch.countDown();
                    }
                }
            });
        }

        try {
            latch.await();
        } catch (InterruptedException e) {
            LocalBroadcastManager.getInstance(XKCDDownloader.this).sendBroadcast(new Intent(DOWNLOAD_FAIL));
        }

        SharedPrefs.getInstance().setLastRedownladTime(System.currentTimeMillis());
        LocalBroadcastManager.getInstance(this).sendBroadcast(new Intent(DOWNLOAD_SUCCESS));

    } catch (IOException e) {
        LocalBroadcastManager.getInstance(this).sendBroadcast(new Intent(DOWNLOAD_FAIL));
    }
}

From source file:com.tanmay.blip.networking.XKCDDownloader.java

License:Apache License

private void downloadAllMissingTranscripts() {
    final Gson gson = new Gson();
    final DatabaseManager databaseManager = new DatabaseManager(this);
    List<Integer> nums = databaseManager.getAllMissingTranscripts();

    final CountDownLatch latch = new CountDownLatch(nums.size());
    final Executor executor = Executors.newFixedThreadPool(nums.size() / 2);
    for (int i : nums) {
        final int index = i;
        executor.execute(new Runnable() {
            @Override//from   w  w w . j  av  a  2s . c om
            public void run() {
                try {
                    String url = String.format(COMICS_URL, index);
                    Request request = new Request.Builder().url(url).build();
                    Response response = BlipApplication.getInstance().client.newCall(request).execute();
                    if (!response.isSuccessful())
                        throw new IOException();
                    String responseBody = response.body().string();
                    Comic comic = null;
                    try {
                        comic = gson.fromJson(responseBody, Comic.class);
                    } catch (JsonSyntaxException e) {
                        Crashlytics.log(1, "XKCDDownloader", e.getMessage() + " POS:" + index);
                    }
                    if (comic != null) {
                        databaseManager.updateComic(comic);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                    LocalBroadcastManager.getInstance(XKCDDownloader.this)
                            .sendBroadcast(new Intent(DOWNLOAD_FAIL));
                } finally {
                    latch.countDown();
                }
            }
        });
    }

    try {
        latch.await();
    } catch (InterruptedException e) {
        LocalBroadcastManager.getInstance(XKCDDownloader.this).sendBroadcast(new Intent(DOWNLOAD_FAIL));
    }
    SharedPrefs.getInstance().setLastTranscriptCheckTime(System.currentTimeMillis());
    LocalBroadcastManager.getInstance(this).sendBroadcast(new Intent(DOWNLOAD_SUCCESS));

}

From source file:com.tanmay.blip.networking.XKCDDownloader.java

License:Apache License

private void downloadAll() {
    final Gson gson = new Gson();
    final DatabaseManager databaseManager = new DatabaseManager(this);
    Request request = new Request.Builder().url(LATEST_URL).build();
    try {/*from   ww w  .  ja v  a  2 s  .  co  m*/
        final Response response = BlipApplication.getInstance().client.newCall(request).execute();
        if (!response.isSuccessful())
            throw new IOException();
        Comic comic = gson.fromJson(response.body().string(), Comic.class);

        final int num = comic.getNum();
        final CountDownLatch latch = new CountDownLatch(num);
        final Executor executor = Executors.newFixedThreadPool(10);

        for (int i = 1; i <= num; i++) {
            final int index = i;
            executor.execute(new Runnable() {

                @Override
                public void run() {
                    try {
                        if (index != 404) {
                            String url = String.format(COMICS_URL, index);
                            Request newReq = new Request.Builder().url(url).build();
                            Response newResp = BlipApplication.getInstance().client.newCall(newReq).execute();
                            if (!newResp.isSuccessful())
                                throw new IOException();
                            String resp = newResp.body().string();
                            Comic comic1 = null;
                            try {
                                comic1 = gson.fromJson(resp, Comic.class);
                            } catch (JsonSyntaxException e) {
                                Crashlytics.log(1, "XKCDDownloader", e.getMessage() + " POS:" + index);
                            }
                            if (comic1 != null) {
                                databaseManager.addComic(comic1);
                                double progress = ((double) databaseManager.getCount() / num) * 100;
                                Intent intent = new Intent(DOWNLOAD_PROGRESS);
                                intent.putExtra(PROGRESS, progress);
                                intent.putExtra(TITLE, comic1.getTitle());
                                LocalBroadcastManager.getInstance(XKCDDownloader.this).sendBroadcast(intent);
                            }
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                        LocalBroadcastManager.getInstance(XKCDDownloader.this)
                                .sendBroadcast(new Intent(DOWNLOAD_FAIL));
                    } finally {
                        latch.countDown();
                    }
                }
            });
        }

        try {
            latch.await();
        } catch (InterruptedException e) {
            throw new IOException(e);
        }

        LocalBroadcastManager.getInstance(this).sendBroadcast(new Intent(DOWNLOAD_SUCCESS));
    } catch (IOException e) {
        e.printStackTrace();
        LocalBroadcastManager.getInstance(this).sendBroadcast(new Intent(DOWNLOAD_FAIL));
    }
}

From source file:com.taobao.weex.bridge.WXWebsocketBridge.java

License:Apache License

@Override
public void onSuccess(Response response) {
    if (response.isSuccessful()) {
        WXSDKManager.getInstance().postOnUiThread(new Runnable() {
            @Override/*from   w ww  .jav a2  s.  co m*/
            public void run() {
                Toast.makeText(WXEnvironment.sApplication,
                        "Has switched to DEBUG mode, you can see the DEBUG information on the browser!",
                        Toast.LENGTH_SHORT).show();
            }
        }, 0);
    }
}

From source file:com.td.innovate.app.Activity.CaptureActivity.java

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    progressDialog = ProgressDialog.show(this, "Getting results", "Processing image", true);
    if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) {
        if (resultCode == RESULT_OK) {
            // Image captured and saved to fileUri specified in the Intent

            try {
                postImage(new Callback() {
                    @Override//from   www. ja v  a 2  s .co  m
                    public void onFailure(Request request, IOException ioe) {
                        // Something went wrong
                        Log.e("Network error", "Error making image post request");
                        progressDialog.dismiss();
                    }

                    @Override
                    public void onResponse(Response response) throws IOException {
                        if (response.isSuccessful()) {
                            String responseStr = response.body().string();
                            // Do what you want to do with the response.
                            Log.d("response", "responseSTR: " + responseStr);
                            System.out.println(responseStr);
                            try {
                                JSONObject myObject = new JSONObject(responseStr);
                                final String token = myObject.getString("token");

                                checkForKeywords(token);
                            } catch (JSONException je) {
                                Log.e("Post response not JSON", je.getMessage());
                            }
                        } else {
                            // Request not successful
                            System.out.println("Request not successful");
                            System.out.println(response.code());
                            System.out.println(response.message());
                            System.out.println(response.body().string());
                            progressDialog.dismiss();
                        }
                    }
                });
            } catch (Throwable e) {
                Log.e("Image call error", e.getMessage());
                progressDialog.dismiss();
            }
        } else if (resultCode == RESULT_CANCELED) {
            // User cancelled the image capture
            progressDialog.dismiss();
        } else {
            // Image capture failed, advise user
            progressDialog.dismiss();
        }
    }
}

From source file:com.td.innovate.app.Activity.CaptureActivity.java

private void checkForKeywords(final String token) {
    this.runOnUiThread(new Runnable() {
        public void run() {
            progressDialog.setMessage("Identifying image");

            final Handler h = new Handler();
            final int delay = 3000; // milliseconds

            h.postDelayed(new Runnable() {
                public void run() {
                    //do something
                    try {
                        getKeywords(token, new Callback() {
                            @Override
                            public void onFailure(Request request, IOException ioe) {
                                // Something went wrong
                                Log.e("Network error", "Error making token request");
                                progressDialog.dismiss();
                            }/*w  ww  . j  a v a 2s  . c o m*/

                            @Override
                            public void onResponse(Response response) throws IOException {
                                if (response.isSuccessful()) {
                                    String responseStr = response.body().string();
                                    // Do what you want to do with the response.
                                    System.out.println(responseStr);
                                    try {
                                        JSONObject myObject = new JSONObject(responseStr);
                                        String status = myObject.getString("status");
                                        if (status.equals("completed")) {
                                            keywords = myObject.getString("name");
                                            gotKeywords = true;
                                        }
                                    } catch (JSONException je) {
                                        Log.e("Get response not JSON", je.getMessage());
                                        progressDialog.dismiss();
                                    }
                                } else {
                                    // Request not successful
                                    System.out.println("Request not successful");
                                    System.out.println(response.code());
                                    System.out.println(response.message());
                                    System.out.println(response.body().string());
                                    progressDialog.dismiss();
                                }
                            }
                        });
                    } catch (Throwable e) {
                        Log.e("Token call error", e.getMessage());
                        progressDialog.dismiss();
                    }

                    if (!gotKeywords) {
                        h.postDelayed(this, delay);
                    } else {
                        System.out.println(keywords);

                        if (progressDialog != null) {
                            progressDialog.dismiss();
                        }

                        Intent intent = new Intent(context, MainViewPagerActivity.class);
                        intent.putExtra("keywords", keywords);
                        intent.putExtra("barcode", "null");
                        startActivity(intent);
                    }
                }
            }, delay);
        }
    });
}

From source file:com.teddoll.movies.reciever.MovieSync.java

License:Apache License

public static synchronized void SyncData(final OkHttpClient client, final MovieProvider movieCache,
        final OnFetchCompleteListener listener) {
    if (inProcess)
        return;//from   w w w  . j  a v  a2  s .  c o m
    inProcess = true;

    Request popRequest = new Request.Builder().url(POP_URL).addHeader("Accept", "application/json").build();
    Request rateRequest = new Request.Builder().url(RATE_URL).addHeader("Accept", "application/json").build();
    Request genresRequest = new Request.Builder().url(GENRE_URL).addHeader("Accept", "application/json")
            .build();
    requestCount = 3;
    pop = null;
    rate = null;
    genres = null;
    client.newCall(popRequest).enqueue(new Callback() {
        @Override
        public void onFailure(Request request, IOException e) {
            onComplete(movieCache, listener);
        }

        @Override
        public void onResponse(Response response) throws IOException {
            if (response.isSuccessful()) {
                try {
                    JSONObject json = new JSONObject(response.body().string());
                    JSONArray array = json.optJSONArray("results");
                    pop = array != null ? array.toString() : null;
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
            onComplete(movieCache, listener);
        }
    });

    client.newCall(rateRequest).enqueue(new Callback() {
        @Override
        public void onFailure(Request request, IOException e) {
            onComplete(movieCache, listener);
        }

        @Override
        public void onResponse(Response response) throws IOException {
            if (response.isSuccessful()) {
                try {
                    JSONObject json = new JSONObject(response.body().string());
                    JSONArray array = json.optJSONArray("results");
                    rate = array != null ? array.toString() : null;
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            onComplete(movieCache, listener);
        }
    });
    client.newCall(genresRequest).enqueue(new Callback() {
        @Override
        public void onFailure(Request request, IOException e) {
            onComplete(movieCache, listener);
        }

        @Override
        public void onResponse(Response response) throws IOException {
            if (response.isSuccessful()) {
                try {
                    JSONObject json = new JSONObject(response.body().string());
                    JSONArray array = json.optJSONArray("genres");
                    genres = array != null ? array.toString() : null;
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            onComplete(movieCache, listener);
        }
    });

}

From source file:com.teddoll.movies.reciever.MovieSync.java

License:Apache License

public static void getVideos(final OkHttpClient client, Movie movie, final OnGetVideosListener listener) {
    if (listener == null)
        throw new IllegalArgumentException("OnGetVideosListener cannot be null");
    Request request = new Request.Builder().url(String.format(Locale.US, VIDEO_URL, movie.id))
            .addHeader("Accept", "application/json").build();

    client.newCall(request).enqueue(new Callback() {
        @Override/*from ww w .  j  a v  a  2s .co  m*/
        public void onFailure(Request request, IOException e) {
            listener.onVideos(new ArrayList<Video>(0));
        }

        @Override
        public void onResponse(Response response) throws IOException {
            if (response.isSuccessful()) {
                try {
                    JSONObject json = new JSONObject(response.body().string());
                    JSONArray array = json.optJSONArray("results");
                    Gson gson = new Gson();
                    Type type = new TypeToken<List<Video>>() {
                    }.getType();
                    List<Video> vids = gson.fromJson(array.toString(), type);
                    listener.onVideos(vids);
                } catch (JSONException e) {
                    listener.onVideos(new ArrayList<Video>(0));
                }
            } else {
                listener.onVideos(new ArrayList<Video>(0));
            }

        }
    });
}

From source file:com.teddoll.movies.reciever.MovieSync.java

License:Apache License

public static void getReviews(final OkHttpClient client, Movie movie, final OnGetReviewsListener listener) {
    if (listener == null)
        throw new IllegalArgumentException("OnGetReviewsListener cannot be null");
    Request request = new Request.Builder().url(String.format(Locale.US, REVIEW_URL, movie.id))
            .addHeader("Accept", "application/json").build();

    client.newCall(request).enqueue(new Callback() {
        @Override//  w w  w  .ja  va2s .c  om
        public void onFailure(Request request, IOException e) {
            listener.onReviews(new ArrayList<Review>(0));
        }

        @Override
        public void onResponse(Response response) throws IOException {
            if (response.isSuccessful()) {
                try {
                    JSONObject json = new JSONObject(response.body().string());
                    JSONArray array = json.optJSONArray("results");
                    Gson gson = new Gson();
                    Type type = new TypeToken<List<Review>>() {
                    }.getType();
                    List<Review> reviews = gson.fromJson(array.toString(), type);
                    listener.onReviews(reviews);
                } catch (JSONException e) {
                    listener.onReviews(new ArrayList<Review>(0));
                }
            } else {
                listener.onReviews(new ArrayList<Review>(0));
            }

        }
    });
}

From source file:com.twitter.heron.scheduler.kubernetes.AppsV1beta1Controller.java

License:Open Source License

@Override
boolean submit(PackingPlan packingPlan) {
    final String topologyName = getTopologyName();
    if (!topologyName.equals(topologyName.toLowerCase())) {
        throw new TopologySubmissionException("K8S scheduler does not allow upper case topologies.");
    }//from   w  ww  . j av  a2  s  .  co  m

    final Resource containerResource = getContainerResource(packingPlan);

    // find the max number of instances in a container so we can open
    // enough ports if remote debugging is enabled.
    int numberOfInstances = 0;
    for (PackingPlan.ContainerPlan containerPlan : packingPlan.getContainers()) {
        numberOfInstances = Math.max(numberOfInstances, containerPlan.getInstances().size());
    }
    final V1beta1StatefulSet statefulSet = createStatefulSet(containerResource, numberOfInstances);

    try {
        final Response response = client
                .createNamespacedStatefulSetCall(getNamespace(), statefulSet, null, null, null).execute();
        if (!response.isSuccessful()) {
            LOG.log(Level.SEVERE, "Error creating topology message: " + response.message());
            KubernetesUtils.logResponseBodyIfPresent(LOG, response);
            // construct a message based on the k8s api server response
            throw new TopologySubmissionException(KubernetesUtils.errorMessageFromResponse(response));
        }
    } catch (IOException | ApiException e) {
        KubernetesUtils.logExceptionWithDetails(LOG, "Error creating topology", e);
        throw new TopologySubmissionException(e.getMessage());
    }

    return true;
}