Example usage for com.squareup.okhttp Response message

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

Introduction

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

Prototype

String message

To view the source code for com.squareup.okhttp Response message.

Click Source Link

Usage

From source file:com.rafagarcia.countries.backend.webapi.HttpLoggingInterceptor.java

License:Apache License

@Override
public Response intercept(Chain chain) throws IOException {
    Level level = this.level;

    Request request = chain.request();
    if (level == Level.NONE) {
        return chain.proceed(request);
    }/*from w ww .  j a  v a  2  s  . c o m*/

    boolean logBody = level == Level.BODY;
    boolean logHeaders = logBody || level == Level.HEADERS;

    RequestBody requestBody = request.body();
    boolean hasRequestBody = requestBody != null;

    Connection connection = chain.connection();
    Protocol protocol = connection != null ? connection.getProtocol() : Protocol.HTTP_1_1;
    String requestStartMessage = "--> " + request.method() + ' ' + requestPath(request.httpUrl()) + ' '
            + protocol(protocol);
    if (!logHeaders && hasRequestBody) {
        requestStartMessage += " (" + requestBody.contentLength() + "-byte body)";
    }
    logger.log(requestStartMessage);

    if (logHeaders) {
        Headers headers = request.headers();
        for (int i = 0, count = headers.size(); i < count; i++) {
            logger.log(headers.name(i) + ": " + headers.value(i));
        }

        if (logBody && hasRequestBody) {
            Buffer buffer = new Buffer();
            requestBody.writeTo(buffer);

            Charset charset = UTF8;
            MediaType contentType = requestBody.contentType();
            if (contentType != null) {
                contentType.charset(UTF8);
            }

            logger.log("");
            logger.log(buffer.readString(charset));
        }

        String endMessage = "--> END " + request.method();
        if (logBody && hasRequestBody) {
            endMessage += " (" + requestBody.contentLength() + "-byte body)";
        }
        logger.log(endMessage);
    }

    long startNs = System.nanoTime();
    Response response = chain.proceed(request);
    long tookMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNs);

    ResponseBody responseBody = response.body();
    logger.log("<-- " + protocol(response.protocol()) + ' ' + response.code() + ' ' + response.message() + " ("
            + tookMs + "ms" + (!logHeaders ? ", " + responseBody.contentLength() + "-byte body" : "") + ')');

    if (logHeaders) {
        Headers headers = response.headers();
        for (int i = 0, count = headers.size(); i < count; i++) {
            logger.log(headers.name(i) + ": " + headers.value(i));
        }

        if (logBody) {
            Buffer buffer = new Buffer();
            responseBody.source().readAll(buffer);

            Charset charset = UTF8;
            MediaType contentType = responseBody.contentType();
            if (contentType != null) {
                charset = contentType.charset(UTF8);
            }

            if (responseBody.contentLength() > 0) {
                logger.log("");
                logger.log(buffer.clone().readString(charset));
            }

            // Since we consumed the original, replace the one-shot body in the response with a new one.
            response = response.newBuilder()
                    .body(ResponseBody.create(contentType, responseBody.contentLength(), buffer)).build();
        }

        String endMessage = "<-- END HTTP";
        if (logBody) {
            endMessage += " (" + responseBody.contentLength() + "-byte body)";
        }
        logger.log(endMessage);
    }

    return response;
}

From source file:com.rhc.dynamic.pipeline.DynamicPipelineFactory.java

License:Apache License

public DynamicPipelineFactory withHttpConfiguration(String url) throws IOException {
    Request request = new Request.Builder().url(url).build();
    Response response = client.newCall(request).execute();
    if (response.code() != 200) {
        throw new RuntimeException("The http configuration returned a status code of " + response.code()
                + ". We only support 200. Here is the response message: " + response.message());
    } else {/*  ww  w  . j  a  va  2s.  c om*/
        InputStream is = response.body().byteStream();
        if (is == null) {
            throw new RuntimeException("The http configuration response body is null!");
        }
        this.configFile = IOUtils.toString(is);
        LOGGER.debug(this.configFile);
        engagement = new ObjectMapper().readValue(this.configFile, Engagement.class);
    }
    return this;
}

From source file:com.secupwn.aimsicd.utils.RequestTask.java

@Override
protected String doInBackground(String... commandString) {

    // We need to create a separate case for UPLOADING to DBe (OCID, MLS etc)
    switch (mType) {
    // OCID upload request from "APPLICATION" drawer title
    case DBE_UPLOAD_REQUEST:
        try {//from   w ww.jav a2s  .  c om
            @Cleanup
            Realm realm = Realm.getDefaultInstance();
            boolean prepared = mDbAdapter.prepareOpenCellUploadData(realm);

            log.info("OCID upload data prepared - " + String.valueOf(prepared));
            if (prepared) {
                File file = new File((mAppContext.getExternalFilesDir(null) + File.separator)
                        + "OpenCellID/aimsicd-ocid-data.csv");
                publishProgress(25, 100);

                RequestBody requestBody = new MultipartBuilder().type(MultipartBuilder.FORM)
                        .addFormDataPart("key", CellTracker.OCID_API_KEY).addFormDataPart("datafile",
                                "aimsicd-ocid-data.csv", RequestBody.create(MediaType.parse("text/csv"), file))
                        .build();

                Request request = new Request.Builder().url("http://www.opencellid.org/measure/uploadCsv")
                        .post(requestBody).build();

                publishProgress(60, 100);

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

                publishProgress(80, 100);
                if (response != null) {
                    log.info("OCID Upload Response: " + response.code() + " - " + response.message());
                    if (response.code() == 200) {
                        Realm.Transaction transaction = mDbAdapter.ocidProcessed();
                        realm.executeTransaction(transaction);
                    }
                    publishProgress(95, 100);
                }
                return "Successful";
            } else {
                Helpers.msgLong(mAppContext, mAppContext.getString(R.string.no_data_for_publishing));
                return null;
            }

            // all caused by httpclient.execute(httppost);
        } catch (UnsupportedEncodingException e) {
            log.error("Upload OpenCellID data Exception", e);
        } catch (FileNotFoundException e) {
            log.error("Upload OpenCellID data Exception", e);
        } catch (IOException e) {
            log.error("Upload OpenCellID data Exception", e);
        } catch (Exception e) {
            log.error("Upload OpenCellID data Exception", e);
        }

        // DOWNLOADING...
    case DBE_DOWNLOAD_REQUEST: // OCID download request from "APPLICATION" drawer title
        mTimeOut = REQUEST_TIMEOUT_MENU;
    case DBE_DOWNLOAD_REQUEST_FROM_MAP: // OCID download request from "Antenna Map Viewer"
        int count;
        try {
            long total;
            int progress = 0;
            String dirName = getOCDBDownloadDirectoryPath(mAppContext);
            File dir = new File(dirName);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            File file = new File(dir, OCDB_File_Name);
            log.info("DBE_DOWNLOAD_REQUEST write to: " + dirName + OCDB_File_Name);

            Request request = new Request.Builder().url(commandString[0]).get().build();

            Response response;
            try {
                // OCID's API can be slow. Give it up to a minute to do its job. Since this
                // is a backgrounded task, it's ok to wait for a while.
                okHttpClient.setReadTimeout(60, TimeUnit.SECONDS);
                response = okHttpClient.newCall(request).execute();
                okHttpClient.setReadTimeout(10, TimeUnit.SECONDS); // Restore back to default
            } catch (SocketTimeoutException e) {
                log.warn("Trying to talk to OCID timed out after 60 seconds. API is slammed? Throttled?");
                return "Timeout";
            }

            if (response.code() != 200) {
                try {
                    String error = response.body().string();
                    Helpers.msgLong(mAppContext, mAppContext.getString(R.string.download_error) + " " + error);
                    log.error("Download OCID data error: " + error);
                } catch (Exception e) {
                    Helpers.msgLong(mAppContext, mAppContext.getString(R.string.download_error) + " "
                            + e.getClass().getName() + " - " + e.getMessage());
                    log.error("Download OCID exception: ", e);
                }
                return "Error";
            } else {
                // This returns "-1" for streamed response (Chunked Transfer Encoding)
                total = response.body().contentLength();
                if (total == -1) {
                    log.debug("doInBackground DBE_DOWNLOAD_REQUEST total not returned!");
                    total = 1024; // Let's set it arbitrarily to something other than "-1"
                } else {
                    log.debug("doInBackground DBE_DOWNLOAD_REQUEST total: " + total);
                    publishProgress((int) (0.25 * total), (int) total); // Let's show something!
                }

                FileOutputStream output = new FileOutputStream(file, false);
                InputStream input = new BufferedInputStream(response.body().byteStream());

                byte[] data = new byte[1024];
                while ((count = input.read(data)) > 0) {
                    // writing data to file
                    output.write(data, 0, count);
                    progress += count;
                    publishProgress(progress, (int) total);
                }
                input.close();
                // flushing output
                output.flush();
                output.close();
            }
            return "Successful";

        } catch (IOException e) {
            log.warn("Problem reading data from steam", e);
            return null;
        }
    }

    return null;
}

From source file:com.shopify.buy.data.MockResponseGenerator.java

License:Open Source License

@Override
public Response intercept(Chain chain) throws IOException {
    File file = new File(context.getExternalFilesDir(null), "MobileBuy.json");

    if (file == null) {
        return chain.proceed(chain.request());
    }//w w w  .ja  v  a2 s .c om

    if (!file.exists()) {
        file.createNewFile();
    }

    String jsonKey = currentTestName.get() + '_' + Integer.toString(currentTestRequestIndex.getAndIncrement());

    Request request = chain.request();
    Response response = chain.proceed(request);
    String bodyString = response.body().string();

    JsonObject jsonValue = new JsonObject();
    jsonValue.addProperty(MockResponder.KEY_BODY, bodyString);
    jsonValue.addProperty(MockResponder.KEY_CODE, response.code());
    jsonValue.addProperty(MockResponder.KEY_MESSAGE, response.message());

    FileOutputStream fOut = new FileOutputStream(file, true);
    PrintWriter writer = new PrintWriter(new OutputStreamWriter(fOut));
    writer.println("\"" + jsonKey + "\":" + jsonValue.toString() + ",");

    if (!isPartialAddressTestAdded.getAndSet(true)) {
        writer.println(TEST_WITH_PARTIAL_ADDRESS_RESPONSE);
    }

    writer.flush();
    fOut.flush();
    writer.close();
    fOut.close();

    MediaType contentType = response.body().contentType();
    return response.newBuilder().body(ResponseBody.create(contentType, bodyString)).build();
}

From source file:com.squareup.picasso252.OkHttpDownloader.java

License:Apache License

@Override
public Response load(@NonNull Uri uri, int networkPolicy) throws IOException {
    CacheControl cacheControl = null;// w  ww .j  a  va2  s  .  com
    if (networkPolicy != 0) {
        if (NetworkPolicy.isOfflineOnly(networkPolicy)) {
            cacheControl = CacheControl.FORCE_CACHE;
        } else {
            CacheControl.Builder builder = new CacheControl.Builder();
            if (!NetworkPolicy.shouldReadFromDiskCache(networkPolicy)) {
                builder.noCache();
            }
            if (!NetworkPolicy.shouldWriteToDiskCache(networkPolicy)) {
                builder.noStore();
            }
            cacheControl = builder.build();
        }
    }

    Request.Builder builder = new Request.Builder().url(uri.toString());
    if (cacheControl != null) {
        builder.cacheControl(cacheControl);
    }

    com.squareup.okhttp.Response response = client.newCall(builder.build()).execute();
    int responseCode = response.code();
    if (responseCode >= 300) {
        response.body().close();
        throw new ResponseException(responseCode + " " + response.message(), networkPolicy, responseCode);
    }

    boolean fromCache = response.cacheResponse() != null;

    ResponseBody responseBody = response.body();
    return new Response(responseBody.byteStream(), fromCache, responseBody.contentLength());
}

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/* w  w  w  . j  a  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();
                            }/*from  ww w.ja  v  a2s .co  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.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  a 2  s  . c  om*/

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

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

License:Open Source License

boolean deleteStatefulSet() {
    try {/*from  w ww . j a  va2s. co  m*/
        final V1DeleteOptions options = new V1DeleteOptions();
        options.setGracePeriodSeconds(0L);
        options.setPropagationPolicy(KubernetesConstants.DELETE_OPTIONS_PROPAGATION_POLICY);
        final Response response = client.deleteNamespacedStatefulSetCall(getTopologyName(), getNamespace(),
                options, null, null, null, null, null, null).execute();

        if (!response.isSuccessful()) {
            LOG.log(Level.SEVERE, "Error killing topology message: " + response.message());
            KubernetesUtils.logResponseBodyIfPresent(LOG, response);

            throw new TopologyRuntimeManagementException(KubernetesUtils.errorMessageFromResponse(response));
        }
    } catch (IOException | ApiException e) {
        KubernetesUtils.logExceptionWithDetails(LOG, "Error deleting topology", e);
        return false;
    }

    return true;
}

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

License:Open Source License

boolean killTopology(String kubernetesUri, String topology, String namespace) {
    final CoreV1Api client = new CoreV1Api(new ApiClient().setBasePath(kubernetesUri));

    // old version deployed topologies as naked pods
    try {//from   ww  w .j av a  2s. co  m
        final String labelSelector = KubernetesConstants.LABEL_TOPOLOGY + "=" + topology;
        final Response response = client.deleteCollectionNamespacedPodCall(namespace, null, null, null, null,
                labelSelector, null, null, null, null, null, null).execute();
        if (!response.isSuccessful()) {
            LOG.log(Level.SEVERE, "Error killing topology message: " + response.message());
            KubernetesUtils.logResponseBodyIfPresent(LOG, response);

            throw new TopologyRuntimeManagementException(KubernetesUtils.errorMessageFromResponse(response));
        }
    } catch (IOException | ApiException e) {
        LOG.log(Level.SEVERE, "Error killing topology " + e.getMessage());
        if (e instanceof ApiException) {
            LOG.log(Level.SEVERE, "Error details:\n" + ((ApiException) e).getResponseBody());
        }
        return false;
    }

    return true;
}