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:p1.nd.khan.jubair.mohammadd.popularmovies.sync.ReviewSyncAdapter.java

License:Apache License

private void getMovieReviews(final String movieId) {
    OkHttpClient client = new OkHttpClient();
    String builtUri = Uri.parse(MessageFormat.format(mContext.getString(R.string.MOVIE_REVIEW_URL), movieId))
            .buildUpon().appendQueryParameter("api_key", mContext.getString(R.string.PERSONAL_API_KEY)).build()
            .toString();/*from  w w  w . j  a  v  a 2  s  .c  o  m*/
    Log.v(LOG_TAG, "URL:" + builtUri);

    Request request = new Request.Builder().url(builtUri).build();
    client.newCall(request).enqueue(new Callback() {
        @Override
        public void onFailure(Request request, IOException e) {
            Log.e(LOG_TAG, "==onFailure[getMovieReviews]:", e);
            return;
        }

        @Override
        public void onResponse(Response response) throws IOException {
            try {
                String jsonData = response.body().string();
                if (response.isSuccessful()) {
                    insertReviewContentValues(movieId, jsonData);
                }
            } catch (IOException | JSONException e) {
                Log.e(LOG_TAG, "IOException | JSONException: Exception caught: ", e);
                return;
            }
        }
    });
}

From source file:p1.nd.khan.jubair.mohammadd.popularmovies.sync.TrailerSyncAdapter.java

License:Apache License

private void getMovieTrailers(final String movieId) {
    OkHttpClient client = new OkHttpClient();
    String builtUri = Uri.parse(MessageFormat.format(mContext.getString(R.string.MOVIE_TRAILER_URL), movieId))
            .buildUpon().appendQueryParameter("api_key", mContext.getString(R.string.PERSONAL_API_KEY)).build()
            .toString();//from www . ja va  2 s . co  m

    Log.v(LOG_TAG, "URL:" + builtUri);

    Request request = new Request.Builder().url(builtUri).build();
    client.newCall(request).enqueue(new Callback() {
        @Override
        public void onFailure(Request request, IOException e) {
            Log.e(LOG_TAG, "==onFailure[getMovieTrailers]:", e);
            return;
        }

        @Override
        public void onResponse(Response response) throws IOException {
            try {
                String jsonData = response.body().string();
                if (response.isSuccessful()) {
                    insertTrailerContentValues(movieId, jsonData);
                }
            } catch (IOException | JSONException e) {
                Log.e(LOG_TAG, "IOException | JSONException: Exception caught: ", e);
                return;
            }
        }
    });
}

From source file:pct.droid.base.providers.media.EZTVProvider.java

License:Open Source License

/**
 * Fetch the list of movies from EZTV/*from  ww  w  .ja v a  2 s. c  o  m*/
 *
 * @param currentList    Current shown list to be extended
 * @param requestBuilder Request to be executed
 * @param callback       Network callback
 * @return Call
 */
private Call fetchList(final ArrayList<Media> currentList, final Request.Builder requestBuilder,
        final Filters filters, final Callback callback) {
    return enqueue(requestBuilder.build(), new com.squareup.okhttp.Callback() {
        @Override
        public void onFailure(Request request, IOException e) {
            String url = requestBuilder.build().urlString();
            if (url.equals(MIRROR_URL)) {
                callback.onFailure(e);
            } else {
                url = url.replace(API_URL, MIRROR_URL);
                requestBuilder.url(url);
                fetchList(currentList, requestBuilder, filters, callback);
            }
        }

        @Override
        public void onResponse(Response response) throws IOException {
            try {
                if (response.isSuccessful()) {
                    String responseStr = response.body().string();

                    ArrayList<LinkedTreeMap<String, Object>> list = null;
                    if (responseStr.isEmpty()) {
                        list = new ArrayList<>();
                    } else {
                        list = (ArrayList<LinkedTreeMap<String, Object>>) mGson.fromJson(responseStr,
                                ArrayList.class);
                    }

                    EZTVReponse result = new EZTVReponse(list);
                    if (list == null) {
                        callback.onFailure(new NetworkErrorException("Empty response"));
                    } else {
                        ArrayList<Media> formattedData = result.formatListForPopcorn(currentList);
                        callback.onSuccess(filters, formattedData, list.size() > 0);
                        return;
                    }
                }
            } catch (Exception e) {
                callback.onFailure(e);
            }
            callback.onFailure(new NetworkErrorException("Couldn't connect to EZTVAPI"));
        }
    });
}

From source file:pct.droid.base.providers.media.EZTVProvider.java

License:Open Source License

@Override
public Call getDetail(String videoId, final Callback callback) {
    Request.Builder requestBuilder = new Request.Builder();
    requestBuilder.url(API_URL + "show/" + videoId);
    requestBuilder.tag(MEDIA_CALL);/*  w  w w .  j  a va2s .com*/

    return enqueue(requestBuilder.build(), new com.squareup.okhttp.Callback() {
        @Override
        public void onFailure(Request request, IOException e) {
            callback.onFailure(e);
        }

        @Override
        public void onResponse(Response response) throws IOException {
            if (response.isSuccessful()) {
                String responseStr = response.body().string();
                LinkedTreeMap<String, Object> map = mGson.fromJson(responseStr, LinkedTreeMap.class);
                EZTVReponse result = new EZTVReponse(map);
                if (map == null) {
                    callback.onFailure(new NetworkErrorException("Empty response"));
                } else {
                    ArrayList<Media> formattedData = result.formatDetailForPopcorn();

                    if (formattedData.size() > 0) {
                        callback.onSuccess(null, formattedData, true);
                        return;
                    }
                    callback.onFailure(new IllegalStateException("Empty list"));
                    return;
                }
            }
            callback.onFailure(new NetworkErrorException("Couldn't connect to EZTVAPI"));
        }
    });
}

From source file:pct.droid.base.providers.media.HaruProvider.java

License:Open Source License

/**
 * Fetch the list of movies from Haruhichan
 *
 * @param currentList    Current shown list to be extended
 * @param requestBuilder Request to be executed
 * @param callback       Network callback
 * @return Call//from  ww w  . ja  v a 2  s  . c o m
 */
private Call fetchList(final ArrayList<Media> currentList, final Request.Builder requestBuilder,
        final Filters filters, final Callback callback) {
    return enqueue(requestBuilder.build(), new com.squareup.okhttp.Callback() {
        @Override
        public void onFailure(Request request, IOException e) {
            callback.onFailure(e);
        }

        @Override
        public void onResponse(Response response) throws IOException {
            try {
                if (response.isSuccessful()) {
                    String responseStr = response.body().string();

                    ArrayList<LinkedTreeMap<String, Object>> list = null;
                    if (responseStr.isEmpty()) {
                        list = new ArrayList<>();
                    } else {
                        list = (ArrayList<LinkedTreeMap<String, Object>>) mGson.fromJson(responseStr,
                                ArrayList.class);
                    }

                    HaruResponse result = new HaruResponse(list);
                    if (list == null) {
                        callback.onFailure(new NetworkErrorException("Empty response"));
                    } else {
                        ArrayList<Media> formattedData = result.formatListForPopcorn(currentList);
                        callback.onSuccess(filters, formattedData, list.size() > 0);
                        return;
                    }
                }
            } catch (Exception e) {
                callback.onFailure(e);
            }
            callback.onFailure(new NetworkErrorException("Couldn't connect to Haruhichan"));
        }
    });
}

From source file:pct.droid.base.providers.media.HaruProvider.java

License:Open Source License

@Override
public Call getDetail(String videoId, final Callback callback) {
    Request.Builder requestBuilder = new Request.Builder();
    requestBuilder.url(API_URL + "anime.php?id=" + videoId);
    requestBuilder.tag(MEDIA_CALL);/*from w w w .j  a  v  a 2s  .  c om*/

    return enqueue(requestBuilder.build(), new com.squareup.okhttp.Callback() {
        @Override
        public void onFailure(Request request, IOException e) {
            callback.onFailure(e);
        }

        @Override
        public void onResponse(Response response) throws IOException {
            if (response.isSuccessful()) {
                String responseStr = response.body().string();
                LinkedTreeMap<String, Object> map = mGson.fromJson(responseStr, LinkedTreeMap.class);
                HaruResponse result = new HaruResponse(map);
                if (map == null) {
                    callback.onFailure(new NetworkErrorException("Empty response"));
                } else {
                    ArrayList<Media> formattedData = result.formatDetailForPopcorn();

                    if (formattedData.size() > 0) {
                        callback.onSuccess(null, formattedData, true);
                        return;
                    }
                    callback.onFailure(new IllegalStateException("Empty list"));
                    return;
                }
            }
            callback.onFailure(new NetworkErrorException("Couldn't connect to Haruhichan API"));
        }
    });
}

From source file:pct.droid.base.providers.media.YTSProvider.java

License:Open Source License

/**
 * Fetch the list of movies from YTS//from  w w  w. jav  a 2s . c o  m
 *
 * @param currentList    Current shown list to be extended
 * @param requestBuilder Request to be executed
 * @param callback       Network callback
 * @return Call
 */
private Call fetchList(final ArrayList<Media> currentList, final Request.Builder requestBuilder,
        final Filters filters, final Callback callback) {
    requestBuilder.addHeader("Host", "xor.image.yt");
    return enqueue(requestBuilder.build(), new com.squareup.okhttp.Callback() {
        @Override
        public void onFailure(Request request, IOException e) {
            if (generateFallback(requestBuilder)) {
                fetchList(currentList, requestBuilder, filters, callback);
            } else {
                callback.onFailure(e);
            }
        }

        @Override
        public void onResponse(Response response) throws IOException {
            if (response.isSuccessful()) {
                String responseStr;
                try {
                    responseStr = response.body().string();
                } catch (SocketException e) {
                    onFailure(response.request(), new IOException("Socket failed"));
                    return;
                }

                YTSReponse result;
                try {
                    result = mGson.fromJson(responseStr, YTSReponse.class);
                } catch (IllegalStateException e) {
                    onFailure(response.request(), new IOException("JSON Failed"));
                    return;
                } catch (JsonSyntaxException e) {
                    onFailure(response.request(), new IOException("JSON Failed"));
                    return;
                }

                if (result.status != null && result.status.equals("error")) {
                    callback.onFailure(new NetworkErrorException(result.status_message));
                } else if (result.data != null && ((result.data.get("movies") != null
                        && ((ArrayList<LinkedTreeMap<String, Object>>) result.data.get("movies")).size() <= 0)
                        || ((Double) result.data.get("movie_count")).intValue() <= currentList.size())) {
                    callback.onFailure(new NetworkErrorException("No movies found"));
                } else {
                    ArrayList<Media> formattedData = result.formatForPopcorn(currentList);
                    callback.onSuccess(filters, formattedData, true);
                    return;
                }
            }
            onFailure(response.request(), new IOException("Couldn't connect to YTS"));
        }
    });
}

From source file:pct.droid.base.providers.media.YTSProvider.java

License:Open Source License

private Call fetchDetail(final Request.Builder requestBuilder, final Callback callback) {
    return enqueue(requestBuilder.build(), new com.squareup.okhttp.Callback() {
        @Override/*  w w  w . j  a  v a  2  s .com*/
        public void onFailure(Request request, IOException e) {
            if (generateFallback(requestBuilder)) {
                fetchDetail(requestBuilder, callback);
            } else {
                callback.onFailure(e);
            }
        }

        @Override
        public void onResponse(Response response) throws IOException {
            if (response.isSuccessful()) {
                String responseStr;
                try {
                    responseStr = response.body().string();
                } catch (SocketException e) {
                    onFailure(response.request(), new IOException("Socket failed"));
                    return;
                }

                YTSReponse result;
                try {
                    result = mGson.fromJson(responseStr, YTSReponse.class);
                } catch (IllegalStateException e) {
                    onFailure(response.request(), new IOException("JSON Failed"));
                    return;
                } catch (JsonSyntaxException e) {
                    onFailure(response.request(), new IOException("JSON Failed"));
                    return;
                }

                if (result.status != null && result.status.equals("error")) {
                    callback.onFailure(new NetworkErrorException(result.status_message));
                } else {
                    final Movie movie = result.formatDetailForPopcorn();

                    TraktProvider traktProvider = new TraktProvider();

                    traktProvider.getMovieMeta(movie.imdbId, new MetaProvider.Callback() {
                        @Override
                        public void onResult(MetaProvider.MetaData metaData, Exception e) {
                            if (e == null) {
                                if (metaData.trailer != null) {
                                    movie.trailer = metaData.trailer;
                                }

                                if (metaData.certification != null) {
                                    movie.certification = metaData.certification;
                                }
                            }

                            final ArrayList<Media> returnData = new ArrayList<>();
                            returnData.add(movie);
                            callback.onSuccess(null, returnData, true);
                        }
                    });

                    return;
                }
            }
            onFailure(response.request(), new IOException("Couldn't connect to YTS"));
        }
    });
}

From source file:pct.droid.base.providers.subs.SubsProvider.java

License:Open Source License

/**
 * @param context      Context/*from  w  ww . j a  va 2 s .c o m*/
 * @param media        Media data
 * @param languageCode Code of language
 * @param callback     Network callback
 * @return Call
 */
public static Call download(final Context context, final Media media, final String languageCode,
        final com.squareup.okhttp.Callback callback) {
    OkHttpClient client = PopcornApplication.getHttpClient();
    if (media.subtitles != null && media.subtitles.containsKey(languageCode)) {
        try {
            Request request = new Request.Builder().url(media.subtitles.get(languageCode)).build();
            Call call = client.newCall(request);

            final File subsDirectory = getStorageLocation(context);
            final String fileName = media.videoId + "-" + languageCode;
            final File srtPath = new File(subsDirectory, fileName + ".srt");

            if (srtPath.exists()) {
                callback.onResponse(null);
                return call;
            }

            call.enqueue(new com.squareup.okhttp.Callback() {
                @Override
                public void onFailure(Request request, IOException e) {
                    callback.onFailure(request, e);
                }

                @Override
                public void onResponse(Response response) throws IOException {
                    if (response.isSuccessful()) {
                        InputStream inputStream = null;
                        boolean failure = false;
                        try {

                            subsDirectory.mkdirs();
                            if (srtPath.exists()) {
                                File to = new File(subsDirectory, "temp" + System.currentTimeMillis());
                                srtPath.renameTo(to);
                                to.delete();
                            }

                            inputStream = response.body().byteStream();
                            String urlString = response.request().urlString();

                            if (urlString.contains(".zip") || urlString.contains(".gz")) {
                                SubsProvider.unpack(inputStream, srtPath, languageCode);
                            } else if (SubsProvider.isSubFormat(urlString)) {
                                parseFormatAndSave(urlString, srtPath, languageCode, inputStream);
                            } else {
                                callback.onFailure(response.request(),
                                        new IOException("FatalParsingException"));
                                failure = true;
                            }
                        } catch (FatalParsingException e) {
                            e.printStackTrace();
                            callback.onFailure(response.request(), new IOException("FatalParsingException"));
                            failure = true;
                        } catch (FileNotFoundException e) {
                            e.printStackTrace();
                            callback.onFailure(response.request(), e);
                            failure = true;
                        } catch (IOException e) {
                            e.printStackTrace();
                            callback.onFailure(response.request(), e);
                            failure = true;
                        } finally {
                            if (inputStream != null)
                                inputStream.close();

                            if (!failure)
                                callback.onResponse(response);
                        }
                    } else {
                        callback.onFailure(response.request(), new IOException("Unknown error"));
                    }
                }
            });

            return call;
        } catch (RuntimeException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    callback.onFailure(null, new IOException("Wrong media"));
    return null;
}

From source file:pct.droid.base.updater.PopcornUpdater.java

License:Open Source License

@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public void checkUpdates(boolean forced) {
    long now = System.currentTimeMillis();

    if (!PrefUtils.get(mContext, Prefs.AUTOMATIC_UPDATES, true) && !forced) {
        return;//from  w w w  . j  a v a  2  s  .c om
    }

    PrefUtils.save(mContext, LAST_UPDATE_CHECK, now);

    if (forced || (lastUpdate + UPDATE_INTERVAL) < now) {
        lastUpdate = System.currentTimeMillis();
        PrefUtils.save(mContext, LAST_UPDATE_KEY, lastUpdate);
        setChanged();

        if (BuildConfig.GIT_BRANCH.contains("local"))
            return;

        notifyObservers(STATUS_CHECKING);

        final String abi;
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
            abi = Build.CPU_ABI.toLowerCase(Locale.US);
        } else {
            abi = Build.SUPPORTED_ABIS[0].toLowerCase(Locale.US);
        }

        final String variantStr;
        if (mPackageName.contains("tv")) {
            variantStr = "tv";
        } else {
            variantStr = "mobile";
        }

        final String channelStr;
        if (BuildConfig.BUILD_TYPE.equals("release")) {
            channelStr = "release";
        } else {
            channelStr = BuildConfig.GIT_BRANCH;
        }

        Request request = new Request.Builder().url(DATA_URL + "/" + variantStr).build();

        mHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Request request, IOException e) {
                setChanged();
                notifyObservers(STATUS_NO_UPDATE);
            }

            @Override
            public void onResponse(Response response) {
                try {
                    if (response.isSuccessful()) {
                        UpdaterData data = mGson.fromJson(response.body().string(), UpdaterData.class);
                        Map<String, Map<String, UpdaterData.Arch>> variant;

                        if (variantStr.equals("tv")) {
                            variant = data.tv;
                        } else {
                            variant = data.mobile;
                        }

                        UpdaterData.Arch channel = null;
                        if (variant.containsKey(channelStr) && variant.get(channelStr).containsKey(abi)) {
                            channel = variant.get(channelStr).get(abi);
                        }

                        if (channel == null || channel.checksum.equals(PrefUtils.get(mContext, SHA1_KEY, "0"))
                                || channel.versionCode <= mVersionCode) {
                            setChanged();
                            notifyObservers(STATUS_NO_UPDATE);
                        } else {
                            downloadFile(channel.updateUrl);
                            setChanged();
                            notifyObservers(STATUS_GOT_UPDATE);
                        }
                    } else {
                        setChanged();
                        notifyObservers(STATUS_NO_UPDATE);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }
}