Example usage for com.squareup.okhttp OkHttpClient newCall

List of usage examples for com.squareup.okhttp OkHttpClient newCall

Introduction

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

Prototype

public Call newCall(Request request) 

Source Link

Document

Prepares the request to be executed at some point in the future.

Usage

From source file:com.apothesource.pillfill.service.drug.impl.DefaultDrugAlertServiceImpl.java

License:Open Source License

@Override
public Observable<DrugAlertType> checkForDrugDoseWarnings(Collection<PrescriptionType> activeRxList,
        final float weightInKgs) {
    return subscribeIoObserveImmediate(Observable.create(subscriber -> {
        if (!activeRxList.isEmpty()) {
            final String urlStr = getMrtdUrlString(activeRxList, weightInKgs);
            Optional<String> cachedResponse = cache.getCachedData(urlStr);
            if (cachedResponse.isPresent()) {
                try {
                    List<MRTDCalculation> mrtds = gson.fromJson(cachedResponse.get(), MRTD_LIST_TYPE);
                    Observable.from(getDrugAlertsFromMrtdCalculations(mrtds, weightInKgs))
                            .forEach(subscriber::onNext);
                    subscriber.onCompleted();
                    return;
                } catch (Exception e) {
                    log.warning("Error handling cached MRTD response. Failing back to server.");
                }/*from  ww w .jav  a  2s . com*/
            }

            log.fine("Checking for drug alerts to URL: " + urlStr);
            try {
                OkHttpClient client = PFNetworkManager.getPinnedPFHttpClient();
                Request req = new Request.Builder().url(urlStr).build();
                log.fine("Requesting MRTD calculations from server: " + urlStr);

                String response = client.newCall(req).execute().body().string();
                cache.setCachedData(urlStr, response);
                List<MRTDCalculation> mrtds = gson.fromJson(response, MRTD_LIST_TYPE);
                Observable.from(getDrugAlertsFromMrtdCalculations(mrtds, weightInKgs))
                        .forEach(subscriber::onNext);
                subscriber.onCompleted();
            } catch (IOException e) {
                log.log(Level.WARNING, "Could not retrieve alerts.", e);
                subscriber.onError(e);
            }
        } else {
            subscriber.onCompleted();
        }
    }));
}

From source file:com.apothesource.pillfill.service.drug.impl.DefaultDrugAlertServiceImpl.java

License:Open Source License

@Override
public Observable<DrugAlertType> checkForDrugAlerts(Collection<PrescriptionType> rxList) {
    ArrayList<String> ndcList = new ArrayList<>();
    for (PrescriptionType rx : rxList) {
        if (rx.getNdc() != null)
            ndcList.add(rx.getNdc());/* w  w  w.  j av  a2 s. co m*/
    }

    final String urlParam = Joiner.on(",").join(ndcList);
    return subscribeIoObserveImmediate(Observable.create(subscriber -> {
        try {
            if (ndcList.isEmpty()) {
                subscriber.onCompleted();
            } else {
                String url = String.format(PFServiceEndpoints.DRUG_ALERT_URL, urlParam);
                log.fine(String.format("Checking for drug alerts to URL: %s", url));
                OkHttpClient client = PFNetworkManager.getPinnedPFHttpClient();
                Request req = new Request.Builder().url(url).build();

                String response = client.newCall(req).execute().body().string();
                List<DrugAlertType> alerts = gson.fromJson(response, ALERT_LIST_TYPE);

                Observable.from(alerts).map(alert -> {
                    alert.setKey(alert.getAdditionalInfoUrl());
                    return alert;
                }).forEach(subscriber::onNext);

                subscriber.onCompleted();
            }
        } catch (IOException e) {
            log.log(Level.WARNING, "Could not retrieve alerts.", e);
            subscriber.onError(e);
        }
    }));
}

From source file:com.apothesource.pillfill.service.prescription.impl.DefaultPrescriptionServiceImpl.java

License:Open Source License

@Override
public Observable<PrescriptionType> getPrescriptions(List<String> rxIds) {
    return subscribeIoObserveImmediate(subscriber -> {
        if (rxIds == null || rxIds.isEmpty()) {
            log.warning("Cannot load prescriptions- empty id list");
            subscriber.onCompleted();/*  w  ww .  j  a v  a 2 s.c  o  m*/
        } else {
            int idx = 0;
            while (idx < rxIds.size()) {
                int batchSize = (rxIds.size() - idx > 100) ? 100 : rxIds.size() - idx;
                List<String> reqList = rxIds.subList(idx, idx + batchSize);
                final String url = String.format(PFServiceEndpoints.PRESCRIPTIONS_URL,
                        Joiner.on("%2C").skipNulls().join(reqList));
                log.info(String.format("Requesting url: %s", url));
                try {
                    OkHttpClient connection = PFNetworkManager.getPinnedPFHttpClient();
                    Request request = new Request.Builder().url(url).addHeader("Cache-Control", "no-cache")
                            .build();

                    Response response = connection.newCall(request).execute();

                    if (response.code() != 200) {
                        subscriber.onError(new RuntimeException(
                                String.format("Invalid response code: %d", response.code())));
                        return;
                    } else {
                        Type type = new TypeToken<ArrayList<PrescriptionType>>() {
                        }.getType();
                        ArrayList<PrescriptionType> retList = gson.fromJson(response.body().string(), type);
                        Observable.from(retList).forEach(subscriber::onNext);
                    }
                } catch (Exception e) {
                    subscriber.onError(e);
                    return;
                }
                idx += batchSize;
            }
            subscriber.onCompleted();
        }
    });
}

From source file:com.apothesource.pillfill.service.prescription.impl.DefaultPrescriptionServiceImpl.java

License:Open Source License

@Override
public Observable<AccountAggregationTaskResponse> requestPrescriptionExtraction(
        AccountAggregationTaskRequest request) {
    return subscribeIoObserveImmediate(subscriber -> {
        String responseStr = null;

        try {/*w ww .ja v  a  2  s  . c o  m*/
            OkHttpClient client = PFNetworkManager.getPinnedPFHttpClient();
            Request req = new Request.Builder()
                    .post(RequestBody.create(MediaType.parse(HTTP_CONTENT_TYPE_JSON), gson.toJson(request)))
                    .url(PFServiceEndpoints.RX_REQUEST_EXTRACT_URL).build();

            Response res = client.newCall(req).execute();
            responseStr = res.body().string();
            AccountAggregationTaskResponse response = gson.fromJson(responseStr,
                    AccountAggregationTaskResponse.class);
            subscriber.onNext(response);
            subscriber.onCompleted();
        } catch (IOException e) {
            log.log(Level.SEVERE, "Communication error during extraction request.");
            subscriber.onError(e);
        } catch (JsonSyntaxException e) {
            log.severe(String.format("Error parsing response: %s", responseStr));
            subscriber.onError(e);
        }
    });
}

From source file:com.apothesource.pillfill.service.prescription.impl.DefaultPrescriptionServiceImpl.java

License:Open Source License

@Override
public Observable<AccountAggregationTaskResponse> getExtractResponse(AccountAggregationTaskResponse task) {
    return subscribeIoObserveImmediate(subscriber -> {
        OkHttpClient client = PFNetworkManager.getPinnedPFHttpClient();
        String statusUrl = String.format(PFServiceEndpoints.RX_EXTRACT_STATUS_URL, task.taskId);
        Request req = new Request.Builder().url(statusUrl).build();

        String responseStr = null;
        try {//  w ww.ja va2 s  .  co  m
            Response res = client.newCall(req).execute();
            responseStr = res.body().string();
            AccountAggregationTaskResponse response = gson.fromJson(responseStr,
                    AccountAggregationTaskResponse.class);
            subscriber.onNext(response);
            subscriber.onCompleted();
        } catch (IOException e) {
            Timber.e(e, "Error requesting extract status from server.");
            subscriber.onError(e);
        } catch (JsonParseException e) {
            Timber.e(e, "Unexpected response from the server: %s", responseStr);
            subscriber.onError(e);
        }
    });
}

From source file:com.apothesource.pillfill.service.prescription.impl.DefaultPrescriptionServiceImpl.java

License:Open Source License

@Override
public Observable<PrescriptionType> enrichPrescriptions(List<PrescriptionType> rxList) {
    return subscribeIoObserveImmediate(subscriber -> {
        try {/*  ww  w. j  ava  2  s  .co m*/
            OkHttpClient client = PFNetworkManager.getPinnedPFHttpClient();
            Request req = new Request.Builder()
                    .post(RequestBody.create(MediaType.parse(HTTP_CONTENT_TYPE_JSON), gson.toJson(rxList)))
                    .url(PFServiceEndpoints.RX_ENRICH_URL).build();
            Response res = client.newCall(req).execute();
            List<PrescriptionType> enrichedRxList = gson.fromJson(res.body().charStream(), RX_LIST_TYPE);
            Observable.from(enrichedRxList).forEach(subscriber::onNext);
            subscriber.onCompleted();
        } catch (IOException ex) {
            Logger.getLogger(DefaultPrescriptionServiceImpl.class.getName()).log(Level.SEVERE, null, ex);
            subscriber.onError(ex);
        }
    });
}

From source file:com.appstarter.utils.WebUtils.java

License:Apache License

public static String doHttpGet(String url) throws AppStarterException {
    if (BuildConfig.DEBUG) {
        Log.d(TAG, "doHttpGet - url: " + url);
    }//from   w w w  . jav a  2 s.c o  m

    String ret = "";

    OkHttpClient client = new OkHttpClient();
    client.setConnectTimeout(15, TimeUnit.SECONDS); // connect timeout
    client.setReadTimeout(15, TimeUnit.SECONDS); // socket timeout

    try {
        Request request = new Request.Builder().url(new URL(url))
                //               .header("User-Agent", "OkHttp Headers.java")
                //               .addHeader("Accept", "application/json; q=0.5")
                .build();

        Response response = client.newCall(request).execute();
        if (!response.isSuccessful()) {
            String debugMessage = "doHttpGet - OkHttp.Response is not successful - " + response.message() + " ("
                    + response.code() + ")";
            throw new AppStarterException(AppStarterException.ERROR_SERVER, debugMessage);
        }
        ret = response.body().string();
    } catch (IOException e) {
        throw new AppStarterException(e, AppStarterException.ERROR_NETWORK_GET);
    }

    return ret;
}

From source file:com.appstarter.utils.WebUtils.java

License:Apache License

public static String doHttpPost(String url, List<NameValuePair> params) throws AppStarterException {
    if (BuildConfig.DEBUG) {
        Log.d(TAG, "doHttpPost - url: " + debugRequest(url, params));
    }/*from  w w w.j a v a2  s.c  o m*/

    String ret = "";

    OkHttpClient client = new OkHttpClient();
    client.setConnectTimeout(15, TimeUnit.SECONDS); // connect timeout
    client.setReadTimeout(15, TimeUnit.SECONDS); // socket timeout

    FormEncodingBuilder builder = new FormEncodingBuilder();
    for (NameValuePair nvp : params) {
        builder.add(nvp.getName(), nvp.getValue());
    }
    RequestBody formBody = builder.build();

    try {
        Request request = new Request.Builder().url(new URL(url))
                //               .header("User-Agent", "OkHttp Headers.java")
                //               .addHeader("Accept", "application/json; q=0.5")
                .post(formBody).build();

        Response response = client.newCall(request).execute();
        if (!response.isSuccessful()) {
            String debugMessage = "doHttpPost - OkHttp.Response is not successful - " + response.message()
                    + " (" + response.code() + ")";
            throw new AppStarterException(AppStarterException.ERROR_SERVER, debugMessage);
        }
        ret = response.body().string();
    } catch (IOException e) {
        throw new AppStarterException(e, AppStarterException.ERROR_NETWORK_GET);
    }

    return ret;
}

From source file:com.ayuget.redface.network.HTTPRedirection.java

License:Apache License

/**
 * Resolves a redirected URL {@code originalUrl} to its final location.
 *
 * If the URL is not really redirected, the original URL is returned.
 *///from  w  w w.  j  a va 2s  .c  o  m
public static Observable<String> resolve(final String originalUrl) {
    return Observable.create(new Observable.OnSubscribe<String>() {
        @Override
        public void call(Subscriber<? super String> subscriber) {
            OkHttpClient httpClient = new OkHttpClient();
            httpClient.setFollowRedirects(false);

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

            try {
                Response response = httpClient.newCall(request).execute();

                if (response.code() == REDIRECTED_STATUS_CODE) {
                    String locationHeader = response.header(LOCATION_HEADER);
                    String targetUrl = locationHeader == null ? originalUrl
                            : "http://" + new URL(originalUrl).getHost() + locationHeader;
                    Timber.d("URL '%s' is redirected to '%s'", originalUrl, targetUrl);
                    subscriber.onNext(targetUrl);
                } else {
                    Timber.w("URL '%s' is not redirected", originalUrl);
                    subscriber.onNext(originalUrl);
                }
            } catch (IOException e) {
                subscriber.onError(e);
            }
        }
    });
}

From source file:com.ayuget.redface.network.PageFetcher.java

License:Apache License

public Observable<String> fetchSource(final User user, final String pageUrl) {
    return Observable.create(new Observable.OnSubscribe<String>() {
        @Override/*from  www.  j ava 2s .  co m*/
        public void call(Subscriber<? super String> subscriber) {
            // Obtain the HttpClient associated with the current User. Having different clients for
            // each user allows us to easily deal with cookies and to support multi-users in the app
            OkHttpClient client = httpClientProvider.getClientForUser(user);

            CacheControl cacheControl = new CacheControl.Builder().noTransform().build();

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

            try {
                Response response = client.newCall(request).execute();
                subscriber.onNext(response.body().string());
                subscriber.onCompleted();
            } catch (IOException e) {
                subscriber.onError(e);
            }
        }
    });
}