Example usage for com.squareup.okhttp ResponseBody byteStream

List of usage examples for com.squareup.okhttp ResponseBody byteStream

Introduction

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

Prototype

public final InputStream byteStream() throws IOException 

Source Link

Usage

From source file:de.schildbach.wallet.data.DynamicFeeLoader.java

License:Open Source License

private static void fetchDynamicFees(final HttpUrl url, final File tempFile, final File targetFile,
        final String userAgent) {
    final Stopwatch watch = Stopwatch.createStarted();

    final Request.Builder request = new Request.Builder();
    request.url(url);/*from  w  w w.j  a v a 2 s .com*/
    request.header("User-Agent", userAgent);
    if (targetFile.exists())
        request.header("If-Modified-Since", HttpDate.format(new Date(targetFile.lastModified())));

    final OkHttpClient httpClient = Constants.HTTP_CLIENT.clone();
    httpClient.setConnectTimeout(5, TimeUnit.SECONDS);
    httpClient.setWriteTimeout(5, TimeUnit.SECONDS);
    httpClient.setReadTimeout(5, TimeUnit.SECONDS);
    final Call call = httpClient.newCall(request.build());
    try {
        final Response response = call.execute();
        final int status = response.code();
        if (status == HttpURLConnection.HTTP_NOT_MODIFIED) {
            log.info("Dynamic fees not modified at {}, took {}", url, watch);
        } else if (status == HttpURLConnection.HTTP_OK) {
            final ResponseBody body = response.body();
            final FileOutputStream os = new FileOutputStream(tempFile);
            Io.copy(body.byteStream(), os);
            os.close();
            final Date lastModified = response.headers().getDate("Last-Modified");
            if (lastModified != null)
                tempFile.setLastModified(lastModified.getTime());
            body.close();
            if (!tempFile.renameTo(targetFile))
                throw new IllegalStateException("Cannot rename " + tempFile + " to " + targetFile);
            watch.stop();
            log.info("Dynamic fees fetched from {}, took {}", url, watch);
        } else {
            log.warn("HTTP status {} when fetching dynamic fees from {}", response.code(), url);
        }
    } catch (final Exception x) {
        log.warn("Problem when fetching dynamic fees rates from " + url, x);
    }
}

From source file:de.umass.lastfm.AlbumConverter.java

License:Open Source License

@Override
public Album convert(ResponseBody responseBody) throws IOException {
    InputStream bis = responseBody.byteStream();
    try {//from  ww w  .j  a va  2s. co  m
        Result res = createResultFromInputStream(bis);
        return ResponseBuilder.buildItem(res, Album.class);
    } catch (SAXException e) {
        return null;
    } finally {
        closeQuietly(bis);
    }
}

From source file:de.umass.lastfm.ArtistConverter.java

License:Open Source License

@Override
public Artist convert(ResponseBody responseBody) throws IOException {
    InputStream bis = responseBody.byteStream();
    try {//from   w  ww  .  j av a 2 s .com
        Result res = createResultFromInputStream(bis);
        return ResponseBuilder.buildItem(res, Artist.class);
    } catch (SAXException e) {
        return null;
    } finally {
        closeQuietly(bis);
    }
}

From source file:feign.okhttp.OkHttpClient.java

License:Apache License

private static feign.Response.Body toBody(final ResponseBody input) {
    if (input == null || input.contentLength() == 0) {
        return null;
    }// w  ww .  ja v a  2 s .com
    if (input.contentLength() > Integer.MAX_VALUE) {
        throw new UnsupportedOperationException("Length too long " + input.contentLength());
    }
    final Integer length = input.contentLength() != -1 ? (int) input.contentLength() : null;

    return new feign.Response.Body() {

        @Override
        public void close() throws IOException {
            input.close();
        }

        @Override
        public Integer length() {
            return length;
        }

        @Override
        public boolean isRepeatable() {
            return false;
        }

        @Override
        public InputStream asInputStream() throws IOException {
            return input.byteStream();
        }

        @Override
        public Reader asReader() throws IOException {
            return input.charStream();
        }
    };
}

From source file:io.fabric8.kubernetes.client.dsl.internal.WatchConnectionManager.java

License:Apache License

private final void runWatch() throws MalformedURLException, ExecutionException, InterruptedException {
    URL requestUrl = baseOperation.getNamespacedUrl();

    HttpUrl.Builder httpUrlBuilder = HttpUrl.get(requestUrl).newBuilder();

    String labelQueryParam = baseOperation.getLabelQueryParam();
    if (labelQueryParam.length() > 0) {
        httpUrlBuilder.addQueryParameter("labelSelector", labelQueryParam);
    }/*from  w ww.  ja va2  s.  c  o m*/

    String fieldQueryString = baseOperation.getFieldQueryParam();
    String name = baseOperation.getName();
    if (name != null && name.length() > 0) {
        if (fieldQueryString.length() > 0) {
            fieldQueryString += ",";
        }
        fieldQueryString += "metadata.name=" + name;
    }
    httpUrlBuilder.addQueryParameter("fieldSelector", fieldQueryString);

    httpUrlBuilder.addQueryParameter("resourceVersion", this.resourceVersion.get()).addQueryParameter("watch",
            "true");

    Request request = new Request.Builder().get().url(httpUrlBuilder.build())
            .addHeader("Origin",
                    requestUrl.getProtocol() + "://" + requestUrl.getHost() + ":" + requestUrl.getPort())
            .build();
    clonedClient.setReadTimeout(0, TimeUnit.MILLISECONDS);

    webSocketCall = WebSocketCall.create(clonedClient, request);
    webSocketCall.enqueue(new WebSocketListener() {
        private final Logger logger = LoggerFactory.getLogger(this.getClass());

        @Override
        public void onOpen(WebSocket webSocket, Response response) {
            webSocketRef.set(webSocket);
            currentReconnectAttempt.set(0);
        }

        @Override
        public void onFailure(IOException e, Response response) {
            e.printStackTrace();
            try {
                if (response != null && response.body() != null) {
                    response.body().close();
                }
            } catch (IOException e1) {
                e1.printStackTrace();
            }

            if (forceClosed.get()) {
                executor.shutdownNow();
                watcher.onClose(null);
                return;
            }

            onClose(4000, "Connection unexpectedly closed");
        }

        @Override
        public void onMessage(ResponseBody message) throws IOException {
            try {
                WatchEvent event = mapper.readValue(message.byteStream(), WatchEvent.class);
                T obj = (T) event.getObject();
                //Dirty cast - should always be valid though
                String currentResourceVersion = resourceVersion.get();
                String newResourceVersion = ((HasMetadata) obj).getMetadata().getResourceVersion();
                if (currentResourceVersion.compareTo(newResourceVersion) < 0) {
                    resourceVersion.compareAndSet(currentResourceVersion, newResourceVersion);
                }
                Watcher.Action action = Watcher.Action.valueOf(event.getType());
                watcher.eventReceived(action, obj);
            } catch (IOException e) {
                logger.error("Could not deserialize watch event: {}", message.source().readUtf8(), e);
            } catch (ClassCastException e) {
                logger.error("Received wrong type of object for watch", e);
            } catch (IllegalArgumentException e) {
                logger.error("Invalid event type", e);
            } finally {
                message.close();
            }
        }

        @Override
        public void onPong(Buffer buffer) {

        }

        @Override
        public void onClose(final int code, final String reason) {
            if (forceClosed.get()) {
                executor.shutdownNow();
                watcher.onClose(null);
                return;
            }
            executor.submit(new Runnable() {
                @Override
                public void run() {
                    try {
                        runWatch();
                    } catch (ExecutionException e) {
                        if (e.getCause() != null && e.getCause().getCause() != null
                                && e.getCause().getCause() instanceof ConnectException) {
                            if (reconnectLimit >= 0
                                    && currentReconnectAttempt.getAndIncrement() >= reconnectLimit) {
                                watcher.onClose(
                                        new KubernetesClientException("Connection unexpectedly closed", e));
                                return;
                            }
                            try {
                                TimeUnit.MILLISECONDS.sleep(reconnectInterval);
                            } catch (InterruptedException e1) {
                                watcher.onClose(
                                        new KubernetesClientException("Connection unexpectedly closed", e1));
                                return;
                            }
                            onClose(code, reason);
                        }
                    } catch (MalformedURLException | InterruptedException e) {
                        throw KubernetesClientException.launderThrowable(e);
                    }
                }
            });
        }
    });
}

From source file:net.qiujuer.common.okhttp.core.HttpCore.java

License:Apache License

protected void deliveryAsyncResult(final Request request, final StreamCall call,
        final HttpCallback<?> callback) {
    Util.log("onDelivery:" + request.url().toString());
    final HttpCallback<?> resCallBack = callback == null ? new DefaultCallback() : callback;

    //Call start/*from   w w  w  .  j av  a2s  .  c  om*/
    callStart(resCallBack, request);

    mOkHttpClient.newCall(request).enqueue(new Callback() {
        @Override
        public void onFailure(final Request request, final IOException e) {
            Util.log("onFailure:" + request.toString());
            callFailure(resCallBack, request, null, e);
            callFinish(resCallBack);
        }

        @Override
        public void onResponse(final Response response) {
            OutputStream out = call.getOutputStream();
            InputStream in = null;
            byte[] buf = new byte[mBufferSize];
            try {
                Util.log("onResponse:Code:%d Stream.", response.code());

                ResponseBody body = response.body();
                bindResponseProgressCallback(request.body(), body, callback);

                in = body.byteStream();

                int size;
                while ((size = in.read(buf)) != -1) {
                    out.write(buf, 0, size);
                    out.flush();
                }
                // On success
                call.onSuccess(response.code());
            } catch (Exception e) {
                Util.log("onResponse Failure:" + response.request().toString());
                callFailure(resCallBack, response.request(), response, e);
            } finally {
                com.squareup.okhttp.internal.Util.closeQuietly(in);
                com.squareup.okhttp.internal.Util.closeQuietly(out);
            }
            callFinish(resCallBack);
        }
    });
}

From source file:org.apache.nifi.processors.standard.InvokeHTTP.java

License:Apache License

@Override
public void onTrigger(ProcessContext context, ProcessSession session) throws ProcessException {
    OkHttpClient okHttpClient = okHttpClientAtomicReference.get();

    FlowFile requestFlowFile = session.get();

    // Checking to see if the property to put the body of the response in an attribute was set
    boolean putToAttribute = context.getProperty(PROP_PUT_OUTPUT_IN_ATTRIBUTE).isSet();
    if (requestFlowFile == null) {
        if (context.hasNonLoopConnection()) {
            return;
        }/* w  w  w .j a  v a 2 s.  c o  m*/

        String request = context.getProperty(PROP_METHOD).evaluateAttributeExpressions().getValue()
                .toUpperCase();
        if ("POST".equals(request) || "PUT".equals(request) || "PATCH".equals(request)) {
            return;
        } else if (putToAttribute) {
            requestFlowFile = session.create();
        }
    }

    // Setting some initial variables
    final int maxAttributeSize = context.getProperty(PROP_PUT_ATTRIBUTE_MAX_LENGTH).asInteger();
    final ComponentLog logger = getLogger();

    // Every request/response cycle has a unique transaction id which will be stored as a flowfile attribute.
    final UUID txId = UUID.randomUUID();

    FlowFile responseFlowFile = null;
    try {
        // read the url property from the context
        final String urlstr = trimToEmpty(
                context.getProperty(PROP_URL).evaluateAttributeExpressions(requestFlowFile).getValue());
        final URL url = new URL(urlstr);

        Request httpRequest = configureRequest(context, session, requestFlowFile, url);

        // log request
        logRequest(logger, httpRequest);

        // emit send provenance event if successfully sent to the server
        if (httpRequest.body() != null) {
            session.getProvenanceReporter().send(requestFlowFile, url.toExternalForm(), true);
        }

        final long startNanos = System.nanoTime();
        Response responseHttp = okHttpClient.newCall(httpRequest).execute();

        // output the raw response headers (DEBUG level only)
        logResponse(logger, url, responseHttp);

        // store the status code and message
        int statusCode = responseHttp.code();
        String statusMessage = responseHttp.message();

        if (statusCode == 0) {
            throw new IllegalStateException("Status code unknown, connection hasn't been attempted.");
        }

        // Create a map of the status attributes that are always written to the request and response FlowFiles
        Map<String, String> statusAttributes = new HashMap<>();
        statusAttributes.put(STATUS_CODE, String.valueOf(statusCode));
        statusAttributes.put(STATUS_MESSAGE, statusMessage);
        statusAttributes.put(REQUEST_URL, url.toExternalForm());
        statusAttributes.put(TRANSACTION_ID, txId.toString());

        if (requestFlowFile != null) {
            requestFlowFile = session.putAllAttributes(requestFlowFile, statusAttributes);
        }

        // If the property to add the response headers to the request flowfile is true then add them
        if (context.getProperty(PROP_ADD_HEADERS_TO_REQUEST).asBoolean() && requestFlowFile != null) {
            // write the response headers as attributes
            // this will overwrite any existing flowfile attributes
            requestFlowFile = session.putAllAttributes(requestFlowFile,
                    convertAttributesFromHeaders(url, responseHttp));
        }

        boolean outputBodyToRequestAttribute = (!isSuccess(statusCode) || putToAttribute)
                && requestFlowFile != null;
        boolean outputBodyToResponseContent = (isSuccess(statusCode) && !putToAttribute)
                || context.getProperty(PROP_OUTPUT_RESPONSE_REGARDLESS).asBoolean();
        ResponseBody responseBody = responseHttp.body();
        boolean bodyExists = responseBody != null;

        InputStream responseBodyStream = null;
        SoftLimitBoundedByteArrayOutputStream outputStreamToRequestAttribute = null;
        TeeInputStream teeInputStream = null;
        try {
            responseBodyStream = bodyExists ? responseBody.byteStream() : null;
            if (responseBodyStream != null && outputBodyToRequestAttribute && outputBodyToResponseContent) {
                outputStreamToRequestAttribute = new SoftLimitBoundedByteArrayOutputStream(maxAttributeSize);
                teeInputStream = new TeeInputStream(responseBodyStream, outputStreamToRequestAttribute);
            }

            if (outputBodyToResponseContent) {
                /*
                 * If successful and putting to response flowfile, store the response body as the flowfile payload
                 * we include additional flowfile attributes including the response headers and the status codes.
                 */

                // clone the flowfile to capture the response
                if (requestFlowFile != null) {
                    responseFlowFile = session.create(requestFlowFile);
                } else {
                    responseFlowFile = session.create();
                }

                // write attributes to response flowfile
                responseFlowFile = session.putAllAttributes(responseFlowFile, statusAttributes);

                // write the response headers as attributes
                // this will overwrite any existing flowfile attributes
                responseFlowFile = session.putAllAttributes(responseFlowFile,
                        convertAttributesFromHeaders(url, responseHttp));

                // transfer the message body to the payload
                // can potentially be null in edge cases
                if (bodyExists) {
                    // write content type attribute to response flowfile if it is available
                    if (responseBody.contentType() != null) {
                        responseFlowFile = session.putAttribute(responseFlowFile,
                                CoreAttributes.MIME_TYPE.key(), responseBody.contentType().toString());
                    }
                    if (teeInputStream != null) {
                        responseFlowFile = session.importFrom(teeInputStream, responseFlowFile);
                    } else {
                        responseFlowFile = session.importFrom(responseBodyStream, responseFlowFile);
                    }

                    // emit provenance event
                    final long millis = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNanos);
                    if (requestFlowFile != null) {
                        session.getProvenanceReporter().fetch(responseFlowFile, url.toExternalForm(), millis);
                    } else {
                        session.getProvenanceReporter().receive(responseFlowFile, url.toExternalForm(), millis);
                    }
                }
            }

            // if not successful and request flowfile is not null, store the response body into a flowfile attribute
            if (outputBodyToRequestAttribute && bodyExists) {
                String attributeKey = context.getProperty(PROP_PUT_OUTPUT_IN_ATTRIBUTE)
                        .evaluateAttributeExpressions(requestFlowFile).getValue();
                if (attributeKey == null) {
                    attributeKey = RESPONSE_BODY;
                }
                byte[] outputBuffer;
                int size;

                if (outputStreamToRequestAttribute != null) {
                    outputBuffer = outputStreamToRequestAttribute.getBuffer();
                    size = outputStreamToRequestAttribute.size();
                } else {
                    outputBuffer = new byte[maxAttributeSize];
                    size = StreamUtils.fillBuffer(responseBodyStream, outputBuffer, false);
                }
                String bodyString = new String(outputBuffer, 0, size,
                        getCharsetFromMediaType(responseBody.contentType()));
                requestFlowFile = session.putAttribute(requestFlowFile, attributeKey, bodyString);

                final long millis = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNanos);
                session.getProvenanceReporter().modifyAttributes(requestFlowFile,
                        "The " + attributeKey
                                + " has been added. The value of which is the body of a http call to "
                                + url.toExternalForm() + ". It took " + millis + "millis,");
            }
        } finally {
            if (outputStreamToRequestAttribute != null) {
                outputStreamToRequestAttribute.close();
                outputStreamToRequestAttribute = null;
            }
            if (teeInputStream != null) {
                teeInputStream.close();
                teeInputStream = null;
            } else if (responseBodyStream != null) {
                responseBodyStream.close();
                responseBodyStream = null;
            }
        }

        route(requestFlowFile, responseFlowFile, session, context, statusCode);
    } catch (final Exception e) {
        // penalize or yield
        if (requestFlowFile != null) {
            logger.error("Routing to {} due to exception: {}", new Object[] { REL_FAILURE.getName(), e }, e);
            requestFlowFile = session.penalize(requestFlowFile);
            requestFlowFile = session.putAttribute(requestFlowFile, EXCEPTION_CLASS, e.getClass().getName());
            requestFlowFile = session.putAttribute(requestFlowFile, EXCEPTION_MESSAGE, e.getMessage());
            // transfer original to failure
            session.transfer(requestFlowFile, REL_FAILURE);
        } else {
            logger.error("Yielding processor due to exception encountered as a source processor: {}", e);
            context.yield();
        }

        // cleanup response flowfile, if applicable
        try {
            if (responseFlowFile != null) {
                session.remove(responseFlowFile);
            }
        } catch (final Exception e1) {
            logger.error("Could not cleanup response flowfile due to exception: {}", new Object[] { e1 }, e1);
        }
    }
}

From source file:org.bitbucket.ddmytrenko.android.retrofit.converter.msgpack.MsgPackResponseBodyConverter.java

License:Open Source License

@Override
public T convert(final ResponseBody value) throws IOException {
    final InputStream in = value.byteStream();
    return messagePack.createUnpacker(in).read(valueClass);
}

From source file:org.fuse.hawkular.agent.monitor.cmd.FeedCommProcessor.java

License:Apache License

@Override
@SuppressWarnings({ "rawtypes", "unchecked" })
public void onMessage(ResponseBody responseBody) throws IOException {

    BasicMessageWithExtraData<? extends BasicMessage> response;
    String requestClassName = "?";

    try {/*w w w .  jav a2 s  .c om*/
        try {
            BasicMessageWithExtraData<? extends BasicMessage> msgWithData;

            if (responseBody.contentType().equals(WebSocket.TEXT)) {
                String nameAndJsonStr = responseBody.string();
                msgWithData = new ApiDeserializer().deserialize(nameAndJsonStr);
            } else if (responseBody.contentType().equals(WebSocket.BINARY)) {
                InputStream input = responseBody.byteStream();
                msgWithData = new ApiDeserializer().deserialize(input);
            } else {
                throw new IllegalArgumentException(
                        "Unknown mediatype type, please report this bug: " + responseBody.contentType());
            }

            log.debug("Received message from server");

            BasicMessage msg = msgWithData.getBasicMessage();
            requestClassName = msg.getClass().getName();

            Class<? extends Command<?, ?>> commandClass = VALID_COMMANDS.get(requestClassName);
            if (commandClass == null) {
                log.errorInvalidCommandRequestFeed(requestClassName);
                String errorMessage = "Invalid command request: " + requestClassName;
                GenericErrorResponse errorMsg = new GenericErrorResponseBuilder().setErrorMessage(errorMessage)
                        .build();
                response = new BasicMessageWithExtraData<BasicMessage>(errorMsg, null);
            } else {
                Command command = commandClass.newInstance();
                CommandContext context = new CommandContext(this, this.config, this.discoveryService);
                response = command.execute(msgWithData, context);
            }
        } finally {
            // must ensure response is closed; this assumes if it was a stream that the command is finished with it
            responseBody.close();
        }
    } catch (Throwable t) {
        log.errorCommandExecutionFailureFeed(requestClassName, t);
        String errorMessage = "Command failed [" + requestClassName + "]";
        GenericErrorResponse errorMsg = new GenericErrorResponseBuilder().setThrowable(t)
                .setErrorMessage(errorMessage).build();
        response = new BasicMessageWithExtraData<BasicMessage>(errorMsg, null);
    }

    // send the response back to the server
    if (response != null) {
        try {
            sendSync(response);
        } catch (Exception e) {
            log.errorFailedToSendOverFeedComm(response.getClass().getName(), e);
        }
    }
}

From source file:org.hawkular.agent.monitor.dynamicprotocol.prometheus.HawkularPrometheusScraper.java

License:Apache License

@Override
protected OpenConnectionDetails openConnection(URL endpointUrl) throws IOException {
    Configuration.Builder bldr = new Configuration.Builder().useSsl(endpointUrl.getProtocol().equals("https"))
            .sslContext(sslContext).username(endpointConfig.getConnectionData().getUsername())
            .password(endpointConfig.getConnectionData().getPassword());

    BaseHttpClientGenerator httpClientGen = new BaseHttpClientGenerator(bldr.build());
    OkHttpClient httpClient = httpClientGen.getHttpClient();
    Request request = buildGetRequest(endpointUrl, httpClientGen);
    Call call = httpClient.newCall(request);
    Response response = call.execute();
    ResponseBody responseBody = response.body();
    InputStream inputStream = responseBody.byteStream();
    MediaType contentType = responseBody.contentType();

    return new OpenConnectionDetails(inputStream, (contentType != null) ? contentType.toString() : null);
}