Example usage for com.squareup.okhttp Callback Callback

List of usage examples for com.squareup.okhttp Callback Callback

Introduction

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

Prototype

Callback

Source Link

Usage

From source file:org.hawkular.agent.monitor.storage.MetricsOnlyStorageAdapter.java

License:Apache License

@Override
public void store(MetricDataPayloadBuilder payloadBuilder) {
    String jsonPayload = "?";

    try {/*from  w w w .j a v  a2s  .co  m*/
        // get the payload in JSON format
        jsonPayload = payloadBuilder.toPayload().toString();

        // build the REST URL...
        StringBuilder url = Util.getContextUrlString(config.getUrl(), config.getMetricsContext());
        url.append("metrics/data");

        // now send the REST request
        Request request = this.httpClientBuilder.buildJsonPostRequest(url.toString(),
                Collections.singletonMap("Hawkular-Tenant", config.getTenantId()), jsonPayload);

        final String jsonPayloadFinal = jsonPayload;
        this.httpClientBuilder.getHttpClient().newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Request request, IOException e) {
                log.errorFailedToStoreMetricData(e, jsonPayloadFinal);
                diagnostics.getStorageErrorRate().mark(1);
            }

            @Override
            public void onResponse(Response response) throws IOException {
                // HTTP status of 200 means success; anything else is an error
                if (response.code() != 200) {
                    IOException e = new IOException("status-code=[" + response.code() + "], reason=["
                            + response.message() + "], url=[" + request.urlString() + "]");
                    log.errorFailedToStoreMetricData(e, jsonPayloadFinal);
                    diagnostics.getStorageErrorRate().mark(1);
                    throw e;
                }

                // looks like everything stored successfully
                diagnostics.getMetricRate().mark(payloadBuilder.getNumberDataPoints());

            }
        });

    } catch (Throwable t) {
        log.errorFailedToStoreMetricData(t, jsonPayload);
        diagnostics.getStorageErrorRate().mark(1);
    }
}

From source file:org.hawkular.agent.monitor.storage.MetricsOnlyStorageAdapter.java

License:Apache License

@Override
public void store(AvailDataPayloadBuilder payloadBuilder) {
    String jsonPayload = "?";

    try {//from w  ww .j  a  va 2  s . c o  m
        // get the payload in JSON format
        jsonPayload = payloadBuilder.toPayload().toString();

        // build the REST URL...
        StringBuilder url = Util.getContextUrlString(config.getUrl(), config.getMetricsContext());
        url.append("availability/data");

        // now send the REST request
        Request request = this.httpClientBuilder.buildJsonPostRequest(url.toString(),
                Collections.singletonMap("Hawkular-Tenant", config.getTenantId()), jsonPayload);

        final String jsonPayloadFinal = jsonPayload;
        this.httpClientBuilder.getHttpClient().newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Request request, IOException e) {
                log.errorFailedToStoreAvailData(e, jsonPayloadFinal);
                diagnostics.getStorageErrorRate().mark(1);
            }

            @Override
            public void onResponse(Response response) throws IOException {
                // HTTP status of 200 means success; anything else is an error
                if (response.code() != 200) {
                    IOException e = new IOException("status-code=[" + response.code() + "], reason=["
                            + response.message() + "], url=[" + request.urlString() + "]");
                    log.errorFailedToStoreAvailData(e, jsonPayloadFinal);
                    diagnostics.getStorageErrorRate().mark(1);
                    throw e;
                }

                // looks like everything stored successfully
                diagnostics.getAvailRate().mark(payloadBuilder.getNumberDataPoints());

            }
        });

    } catch (Throwable t) {
        log.errorFailedToStoreAvailData(t, jsonPayload);
        diagnostics.getStorageErrorRate().mark(1);
    }
}

From source file:org.openhab.binding.mart.handler.MartHandler.java

License:Open Source License

public void oktrial() {
    Request request = new Request.Builder().url("http://publicobject.com/helloworld.txt").build();

    client.newCall(request).enqueue(new Callback() {

        @Override/*from  w w w  .jav  a  2s.  co  m*/
        public void onResponse(Response arg0) throws IOException {
            // TODO Auto-generated method stub
            if (arg0.isSuccessful()) {
                String resp = arg0.body().string();
                ByteBuffer byteBuffer = ByteBuffer.allocate(resp.getBytes().length);
                writer(byteBuffer, datagramChannel);
                logger.debug(resp);
            }
        }

        @Override
        public void onFailure(Request arg0, IOException arg1) {
            // TODO Auto-generated method stub

        }
    });
}

From source file:org.robovm.store.util.ImageCache.java

License:Apache License

private void downloadImage(String url, Action<File> completion, boolean retryOnFail) {
    Objects.requireNonNull(saveLocation, "Must specify a save location!");
    Objects.requireNonNull(url, "url");
    Objects.requireNonNull(completion, "completion");

    File destination = new File(saveLocation, FilenameUtils.getName(url));
    if (destination.exists()) {
        ActionWrapper.WRAPPER.invoke(completion, destination);
        return;// ww  w.j a v a  2  s .c  o m
    }

    Request request = new Request.Builder().url(url).build();

    client.newCall(request).enqueue(new Callback() {
        @Override
        public void onResponse(Response response) throws IOException {
            int code = response.code();
            if (code >= 200 && code < 300) { // Success
                InputStream in = response.body().byteStream();
                FileUtils.copyInputStreamToFile(in, destination);
                ActionWrapper.WRAPPER.invoke(completion, destination);
            } else if (retryOnFail) { // Error
                downloadImage(PLACEHOLDER_URL, completion, false);
            } else {
                ActionWrapper.WRAPPER.invoke(completion, null);
            }
        }

        @Override
        public void onFailure(Request request, IOException e) {
            System.err.println("file download failed: " + e.getMessage());
            if (retryOnFail) {
                downloadImage(PLACEHOLDER_URL, completion, false);
            } else {
                ActionWrapper.WRAPPER.invoke(completion, null);
            }
        }
    });
}

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

License:Apache License

/**
 * Method to fetch the movie details from server.
 *
 * @param pSortOrder : user preferred order for movie display.
 * @param pPageNo    : page number to fetch the record.
 *///w w w.j a  v a2s  .c  o  m

private void fetchMdbMovie(String pSortOrder, int pPageNo) {
    OkHttpClient client = new OkHttpClient();
    String movieURL = UrlFormatter(pSortOrder, pPageNo);
    Log.v(LOG_TAG, "URL:" + movieURL);
    Request request = new Request.Builder().url(movieURL).build();
    client.newCall(request).enqueue(new Callback() {
        @Override
        public void onFailure(Request request, IOException e) {
            Log.e(LOG_TAG, "==onFailure[fetchMdbMovie]:", e);
            return;
        }

        @Override
        public void onResponse(Response response) throws IOException {
            try {
                String jsonData = response.body().string();
                if (response.isSuccessful()) {
                    insertMovieContentValues(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.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 a2s . c  om
    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   w ww.  j  a va  2s.com*/

    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.activities.MainActivity.java

License:Open Source License

private void openPlayerTestDialog() {
    AlertDialog.Builder builder = new AlertDialog.Builder(this);

    final String[] file_types = getResources().getStringArray(R.array.file_types);
    final String[] files = getResources().getStringArray(R.array.files);

    builder.setTitle("Player Tests").setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
        @Override//from w  w w.  jav a2  s  . co m
        public void onClick(DialogInterface dialogInterface, int i) {
            dialogInterface.dismiss();
        }
    }).setSingleChoiceItems(file_types, -1, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialogInterface, int index) {
            dialogInterface.dismiss();
            final String location = files[index];
            if (location.equals("dialog")) {
                final EditText dialogInput = new EditText(MainActivity.this);
                dialogInput.setText(
                        "http://download.wavetlan.com/SVV/Media/HTTP/MP4/ConvertedFiles/QuickTime/QuickTime_test13_5m19s_AVC_VBR_324kbps_640x480_25fps_AAC-LCv4_CBR_93.4kbps_Stereo_44100Hz.mp4");
                AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this).setView(dialogInput)
                        .setPositiveButton("Start", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                Movie media = new Movie(new YTSProvider(), new YSubsProvider());

                                media.videoId = "dialogtestvideo";
                                media.title = "User input test video";

                                String location = dialogInput.getText().toString();

                                BeamManager bm = BeamManager.getInstance(MainActivity.this);
                                if (bm.isConnected()) {
                                    BeamPlayerActivity.startActivity(MainActivity.this,
                                            new StreamInfo(media, null, null, null, null, location), 0);
                                } else {
                                    VideoPlayerActivity.startActivity(MainActivity.this,
                                            new StreamInfo(media, null, null, null, null, location), 0);
                                }
                            }
                        });
                builder.show();
            } else if (YouTubeData.isYouTubeUrl(location)) {
                Intent i = new Intent(MainActivity.this, TrailerPlayerActivity.class);
                Movie media = new Movie(new YTSProvider(), new YSubsProvider());
                media.title = file_types[index];
                i.putExtra(TrailerPlayerActivity.DATA, media);
                i.putExtra(TrailerPlayerActivity.LOCATION, location);
                startActivity(i);
            } else {
                final Movie media = new Movie(new YTSProvider(), new YSubsProvider());
                media.videoId = "bigbucksbunny";
                media.title = file_types[index];
                media.subtitles = new HashMap<>();
                media.subtitles.put("en", "http://sv244.cf/bbb-subs.srt");

                SubsProvider.download(MainActivity.this, media, "en", new Callback() {
                    @Override
                    public void onFailure(Request request, IOException e) {
                        BeamManager bm = BeamManager.getInstance(MainActivity.this);

                        if (bm.isConnected()) {
                            BeamPlayerActivity.startActivity(MainActivity.this,
                                    new StreamInfo(media, null, null, null, null, location), 0);
                        } else {
                            VideoPlayerActivity.startActivity(MainActivity.this,
                                    new StreamInfo(media, null, null, null, null, location), 0);
                        }
                    }

                    @Override
                    public void onResponse(Response response) throws IOException {
                        BeamManager bm = BeamManager.getInstance(MainActivity.this);
                        if (bm.isConnected()) {
                            BeamPlayerActivity.startActivity(MainActivity.this,
                                    new StreamInfo(media, null, null, "en", null, location), 0);
                        } else {
                            VideoPlayerActivity.startActivity(MainActivity.this,
                                    new StreamInfo(media, null, null, "en", null, location), 0);
                        }
                    }
                });
            }
        }
    });

    builder.show();
}

From source file:pct.droid.base.fragments.BaseStreamLoadingFragment.java

License:Open Source License

/**
 * Downloads the subs file/*from   w  w  w. j  ava  2 s.  c om*/
 */
private void loadSubs() {
    final Media data = mStreamInfo.getMedia();
    if (null != data) {

        //if there are no subtitles specified, try to use the default subs
        if (mStreamInfo.getSubtitleLanguage() == null && data.subtitles != null && data.subtitles.size() > 0) {
            if (data.subtitles.containsKey(PrefUtils.get(getActivity(), Prefs.SUBTITLE_DEFAULT, "no-subs"))) {
                mStreamInfo
                        .setSubtitleLanguage(PrefUtils.get(getActivity(), Prefs.SUBTITLE_DEFAULT, "no-subs"));
            }
        }

        //todo: tidy up
        mSubsStatus = SubsStatus.SUCCESS;

        //load subtitles
        if (data.subtitles != null && data.subtitles.size() > 0 && mStreamInfo.getSubtitleLanguage() != null) {
            mHasSubs = true;
            mSubtitleLanguage = mStreamInfo.getSubtitleLanguage();
            if (!mSubtitleLanguage.equals("no-subs")) {
                SubsProvider.download(getActivity(), data, mSubtitleLanguage, new Callback() {
                    @Override
                    public void onFailure(Request request, IOException e) {
                        mSubsStatus = SubsStatus.FAILURE;
                    }

                    @Override
                    public void onResponse(Response response) throws IOException {
                        mSubsStatus = SubsStatus.SUCCESS;
                    }
                });
            } else {
                mSubsStatus = SubsStatus.SUCCESS;
            }
        } else {
            mSubsProvider = data.getSubsProvider();
            if (null != mSubsProvider) {
                SubsProvider.Callback subsCallback = new SubsProvider.Callback() {
                    @Override
                    public void onSuccess(Map<String, String> items) {
                        data.subtitles = items;
                        mSubsStatus = SubsStatus.SUCCESS;
                    }

                    @Override
                    public void onFailure(Exception e) {
                        mSubsStatus = SubsStatus.FAILURE;
                    }
                };

                if (mStreamInfo.isShow()) {
                    mSubsProvider.getList((Episode) data, subsCallback);
                } else {
                    mSubsProvider.getList((Movie) data, subsCallback);
                }
            }
        }
    }
}

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 a2 s .  c  o  m*/
    }

    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();
                }
            }
        });
    }
}