Example usage for com.squareup.okhttp ResponseBody contentType

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

Introduction

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

Prototype

public abstract MediaType contentType();

Source Link

Usage

From source file:com.taobao.weex.devtools.inspector.network.OkHttpInterceptor.java

License:Open Source License

@Override
public Response intercept(Chain chain) throws IOException {
    String requestId = String.valueOf(mNextRequestId.getAndIncrement());

    Request request = chain.request();

    RequestBodyHelper requestBodyHelper = null;
    if (mEventReporter.isEnabled()) {
        requestBodyHelper = new RequestBodyHelper(mEventReporter, requestId);
        OkHttpInspectorRequest inspectorRequest = new OkHttpInspectorRequest(requestId, request,
                requestBodyHelper);//from w w w  .j av  a  2  s. c o m
        mEventReporter.requestWillBeSent(inspectorRequest);
    }

    Response response;
    try {
        response = chain.proceed(request);
    } catch (IOException e) {
        if (mEventReporter.isEnabled()) {
            mEventReporter.httpExchangeFailed(requestId, e.toString());
        }
        throw e;
    }

    if (mEventReporter.isEnabled()) {
        if (requestBodyHelper != null && requestBodyHelper.hasBody()) {
            requestBodyHelper.reportDataSent();
        }

        Connection connection = chain.connection();
        mEventReporter
                .responseHeadersReceived(new OkHttpInspectorResponse(requestId, request, response, connection));

        ResponseBody body = response.body();
        MediaType contentType = null;
        InputStream responseStream = null;
        if (body != null) {
            contentType = body.contentType();
            responseStream = body.byteStream();
        }

        responseStream = mEventReporter.interpretResponseStream(requestId,
                contentType != null ? contentType.toString() : null, response.header("Content-Encoding"),
                responseStream, new DefaultResponseHandler(mEventReporter, requestId));
        if (responseStream != null) {
            response = response.newBuilder().body(new ForwardingResponseBody(body, responseStream)).build();
        }
    }

    return response;
}

From source file:com.xing.api.CallSpec.java

License:Apache License

/** Parsers the OkHttp raw response and returns an response ready to be consumed by the caller. */
@SuppressWarnings("MagicNumber") // These codes are specific to this method and to the http protocol.
private Response<RT, ET> parseResponse(com.squareup.okhttp.Response rawResponse) throws IOException {
    ResponseBody rawBody = rawResponse.body();

    // Remove the body's source (the only stateful object) so we can pass the response along.
    rawResponse = rawResponse.newBuilder()
            .body(new NoContentResponseBody(rawBody.contentType(), rawBody.contentLength())).build();

    ExceptionCatchingRequestBody catchingBody = new ExceptionCatchingRequestBody(rawBody);
    int code = rawResponse.code();
    if (code < 200 || code >= 300) {
        try {//from www. ja  v a  2 s. com
            // Buffer the entire body to avoid future I/O.
            ET errorBody = parseBody(errorType, catchingBody);
            return Response.error(errorBody, rawResponse);
        } catch (RuntimeException e) {
            // If the underlying source threw an exception, propagate that, rather than indicating it was
            // a runtime exception.
            catchingBody.throwIfCaught();
            throw e;
        } finally {
            closeQuietly(catchingBody);
        }
    }

    // No need to parse the response body since the response should not contain a body.
    if (code == 204 || code == 205) {
        return Response.success(null, rawResponse);
    }

    try {
        RT body = parseBody(responseType, catchingBody);
        return Response.success(body, rawResponse);
    } catch (RuntimeException e) {
        // If the underlying source threw an exception, propagate that, rather than indicating it was
        // a runtime exception.
        catchingBody.throwIfCaught();
        throw e;
    } finally {
        closeQuietly(catchingBody);
    }
}

From source file:com.xing.api.CallSpecTest.java

License:Apache License

@Test
public void exceptionCatchingBodyThrows() throws Exception {
    ResponseBody throwingBody = new ResponseBody() {
        @Override// w w w  .  ja v  a2  s .c o m
        public MediaType contentType() {
            //noinspection ConstantConditions
            return MediaType.parse("application/h");
        }

        @Override
        public long contentLength() throws IOException {
            throw new IOException("Broken body!");
        }

        @Override
        public BufferedSource source() throws IOException {
            throw new IOException("Broken body!");
        }
    };

    // Test content length throws
    ExceptionCatchingRequestBody body = new ExceptionCatchingRequestBody(throwingBody);
    assertThat(body.contentType()).isEqualTo(throwingBody.contentType());
    try {
        body.contentLength();
    } catch (IOException ignored) {
    }
    try {
        body.throwIfCaught();
    } catch (IOException e) {
        assertThat(e.getMessage()).isEqualTo("Broken body!");
    }

    // Test source throws, here we need new object
    body = new ExceptionCatchingRequestBody(throwingBody);
    assertThat(body.contentType()).isEqualTo(throwingBody.contentType());
    try {
        body.source();
    } catch (IOException ignored) {
    }
    try {
        body.throwIfCaught();
    } catch (IOException e) {
        assertThat(e.getMessage()).isEqualTo("Broken body!");
    }
}

From source file:com.xing.api.CallSpecTest.java

License:Apache License

private static void assertNoBodySuccessResponse(Response response, int code) throws IOException {
    assertThat(response.code()).isEqualTo(code);
    assertThat(response.error()).isNull();
    assertThat(response.body()).isNull();
    assertThat(response.isSuccess()).isTrue();

    ResponseBody body = response.raw().body();
    assertThat(body).isNotNull();//from www .  ja v  a  2  s  . com
    // User may want to ignore the content of another response.
    if (code == 204 || code == 205)
        assertThat(body.contentLength()).isEqualTo(0L);
    assertThat(body.contentType()).isNull();

    try {
        body.source();
    } catch (IllegalStateException e) {
        assertThat(e.getMessage()).isEqualTo("Cannot read raw response body of a parsed body.");
    }
}

From source file:com.yandex.disk.rest.LoggingInterceptor.java

License:Apache License

@Override
public Response intercept(Chain chain) throws IOException {
    Request request = chain.request();
    String hash = Integer.toHexString(chain.hashCode());
    String sendPrefix = hash + SEND_PREFIX;
    String receivePrefix = hash + RECEIVE_PREFIX;

    if (logWire) {
        RequestBody requestBody = request.body();
        if (requestBody != null) {
            logger.info(sendPrefix + "request: " + requestBody);
            Buffer buffer = new Buffer();
            requestBody.writeTo(buffer);
            byte[] requestBuffer = ByteStreams.toByteArray(buffer.inputStream());
            logBuffer(sendPrefix, requestBuffer);
        }/*from   ww w . j av  a 2 s. c o m*/
        request = request.newBuilder().removeHeader("Accept-Encoding").addHeader("Accept-Encoding", "").build();
    }

    logger.info(sendPrefix + request.method() + " " + request.url());
    logger.info(sendPrefix + "on " + chain.connection());
    logHeaders(sendPrefix, request.headers());

    Response response = chain.proceed(request);
    logger.info(receivePrefix + response.protocol() + " " + response.code() + " " + response.message());
    logHeaders(receivePrefix, response.headers());

    if (logWire) {
        ResponseBody body = response.body();
        byte[] responseBuffer = ByteStreams.toByteArray(body.byteStream());
        response = response.newBuilder().body(ResponseBody.create(body.contentType(), responseBuffer)).build();
        logBuffer(receivePrefix, responseBuffer);
    }

    return response;
}

From source file:com.yandex.disk.rest.RestClientIO.java

License:Apache License

void downloadUrl(final String url, final DownloadListener downloadListener)
        throws IOException, CancelledDownloadException, DownloadNoSpaceAvailableException, HttpCodeException {

    Request.Builder req = buildRequest().url(url);

    long length = downloadListener.getLocalLength();
    String ifTag = "If-None-Match";
    if (length >= 0) {
        ifTag = "If-Range";
        StringBuilder contentRange = new StringBuilder();
        contentRange.append("bytes=").append(length).append("-");
        logger.debug("Range: " + contentRange);
        req.addHeader("Range", contentRange.toString());
    }/*from  w ww . j  a  va 2  s  .  c  o m*/

    String etag = downloadListener.getETag();
    if (etag != null) {
        logger.debug(ifTag + ": " + etag);
        req.addHeader(ifTag, etag);
    }

    Request request = req.build();
    Response response = client.newCall(request).execute();

    boolean partialContent = false;
    int code = response.code();
    switch (code) {
    case 200:
        // OK
        break;
    case 206:
        partialContent = true;
        break;
    case 304:
        throw new FileNotModifiedException(code);
    case 404:
        throw new NotFoundException(code);
    case 416:
        throw new RangeNotSatisfiableException(code);
    default:
        throw new HttpCodeException(code);
    }

    ResponseBody responseBody = response.body();
    long contentLength = responseBody.contentLength();
    logger.debug("download: contentLength=" + contentLength);

    long loaded;
    if (partialContent) {
        ContentRangeResponse contentRangeResponse = parseContentRangeHeader(response.header("Content-Range"));
        logger.debug("download: contentRangeResponse=" + contentRangeResponse);
        if (contentRangeResponse != null) {
            loaded = contentRangeResponse.getStart();
            contentLength = contentRangeResponse.getSize();
        } else {
            loaded = length;
        }
    } else {
        loaded = 0;
        if (contentLength < 0) {
            contentLength = 0;
        }
    }

    OutputStream os = null;
    try {
        downloadListener.setStartPosition(loaded);
        MediaType contentTypeHeader = responseBody.contentType();
        if (contentTypeHeader != null) {
            downloadListener.setContentType(contentTypeHeader.toString());
        }
        downloadListener.setContentLength(contentLength);

        int count;
        InputStream content = responseBody.byteStream();
        os = downloadListener.getOutputStream(partialContent);
        final byte[] downloadBuffer = new byte[1024];
        while ((count = content.read(downloadBuffer)) != -1) {
            if (downloadListener.hasCancelled()) {
                logger.info("Downloading " + url + " canceled");
                client.cancel(request.tag());
                throw new CancelledDownloadException();
            }
            os.write(downloadBuffer, 0, count);
            loaded += count;
            downloadListener.updateProgress(loaded, contentLength);
        }
    } catch (CancelledDownloadException ex) {
        throw ex;
    } catch (Exception e) {
        logger.warn(e.getMessage(), e);
        client.cancel(request.tag());
        if (e instanceof IOException) {
            throw (IOException) e;
        } else if (e instanceof RuntimeException) {
            throw (RuntimeException) e;
        } else if (e instanceof DownloadNoSpaceAvailableException) {
            throw (DownloadNoSpaceAvailableException) e;
        } else {
            // never happen
            throw new RuntimeException(e);
        }
    } finally {
        try {
            if (os != null) {
                os.close();
            }
        } catch (IOException ex) {
            // nothing
        }
        try {
            response.body().close();
        } catch (IOException | NullPointerException ex) {
            logger.warn(ex.getMessage(), ex);
        }
    }
}

From source file:io.macgyver.core.okhttp.LoggingInterceptor.java

License:Apache License

@Override
public Response intercept(Chain chain) throws IOException {

    Level level = this.level;

    Request request = chain.request();
    if (level == Level.NONE || (!slf4j.isDebugEnabled())) {
        return chain.proceed(request);
    }/*from   w w  w  .j  a v  a 2 s. c om*/

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

    try {

        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() + ' ' + request.httpUrl() + ' '
                + protocol(protocol);
        if (!logHeaders && hasRequestBody) {
            requestStartMessage += " (" + requestBody.contentLength() + "-byte body)";
        }
        log(requestStartMessage);

        if (logHeaders) {
            if (hasRequestBody) {
                // Request body headers are only present when installed as a
                // network interceptor. Force
                // them to be included (when available) so there values are
                // known.
                if (requestBody.contentType() != null) {
                    log("Content-Type: " + requestBody.contentType());
                }
                if (requestBody.contentLength() != -1) {
                    log("Content-Length: " + requestBody.contentLength());
                }
            }

            Headers headers = request.headers();
            for (int i = 0, count = headers.size(); i < count; i++) {
                String name = headers.name(i);

                if (name.equalsIgnoreCase("authorization")) {
                    log(name + ": ************");
                } else {
                    // Skip headers from the request body as they are
                    // explicitly
                    // logged above.
                    if (!"Content-Type".equalsIgnoreCase(name) && !"Content-Length".equalsIgnoreCase(name)) {
                        log(name + ": " + headers.value(i));
                    }
                }
            }

            if (!logBody || !hasRequestBody) {
                slf4j.debug("--> END " + request.method());
            } else if (bodyEncoded(request.headers())) {
                log("--> END " + request.method() + " (encoded body omitted)");
            } else {
                Buffer buffer = new Buffer();
                requestBody.writeTo(buffer);

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

                log("");
                String body = redactRequestBody(buffer.readString(charset));

                log(body);

                log("--> END " + request.method() + " (" + requestBody.contentLength() + "-byte body)");
            }
        }

    } catch (Exception e) {
        LoggerFactory.getLogger(LoggingInterceptor.class).warn("problem logging request: " + e); // no stack trace
    }
    long startNs = System.nanoTime();
    Response response = chain.proceed(request);
    try {
        long tookMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNs);

        ResponseBody responseBody = response.body();
        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++) {
                log(headers.name(i) + ": " + headers.value(i));
            }

            if (!logBody || !HttpEngine.hasBody(response)) {
                log("<-- END HTTP");
            } else if (!isResponseBodyPrintable(response)) {
                log("<-- END HTTP (body omitted)");
            } else {
                BufferedSource source = responseBody.source();
                source.request(maxPrintableBodySize); // Buffer the entire body.
                Buffer buffer = source.buffer();

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

                if (responseBody.contentLength() != 0) {
                    log("");
                    log(redactResponseBody(buffer.clone().readString(charset)));
                }

                log("<-- END HTTP (" + buffer.size() + "-byte body)");
            }
        }
    } catch (Exception e) {
        LoggerFactory.getLogger(LoggingInterceptor.class).warn("problem logging: " + e.toString());
    }

    return response;
}

From source file:name.kevinlocke.appveyor.testutils.ConcurrentHttpLoggingInterceptor.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  w  w .  j a v a  2s.  co  m

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

    RequestBody requestBody = request.body();

    Connection connection = chain.connection();
    Protocol protocol = connection != null ? connection.getProtocol() : Protocol.HTTP_1_1;
    UUID requestId = UUID.randomUUID();
    StringBuilder requestMessage = new StringBuilder("--> ").append(requestId).append('\n')
            .append(request.method()).append(' ').append(request.httpUrl()).append(' ').append(protocol);
    if (!logHeaders && requestBody != null) {
        requestMessage.append(" (").append(requestBody.contentLength()).append("-byte body)");
    }
    requestMessage.append('\n');

    if (logHeaders) {
        if (requestBody != null) {
            // Request body headers are only present when installed as a
            // network interceptor. Force
            // them to be included (when available) so there values are
            // known.
            if (requestBody.contentType() != null) {
                requestMessage.append("Content-Type: ").append(requestBody.contentType()).append('\n');
            }
            if (requestBody.contentLength() != -1) {
                requestMessage.append("Content-Length: ").append(requestBody.contentLength()).append('\n');
            }
        }

        Headers headers = request.headers();
        for (int i = 0, count = headers.size(); i < count; i++) {
            String name = headers.name(i);
            if ("Authorization".equalsIgnoreCase(name) || "Proxy-Authenticate".equalsIgnoreCase(name)
                    || "Proxy-Authorization".equalsIgnoreCase(name)
                    || "WWW-Authenticate".equalsIgnoreCase(name)) {
                requestMessage.append(name).append(": *****\n");
            }
            // Skip headers from the request body as they are explicitly
            // logged above.
            else if (!"Content-Type".equalsIgnoreCase(name) && !"Content-Length".equalsIgnoreCase(name)) {
                requestMessage.append(name).append(": ").append(headers.value(i)).append('\n');
            }
        }

        if (!logBody || requestBody == null) {
            requestMessage.append("--> END ").append(requestId).append('\n');
        } else if (bodyEncoded(request.headers())) {
            requestMessage.append("--> END ").append(requestId).append(" (encoded body omitted)").append('\n');
        } else {
            Buffer buffer = new Buffer();
            requestBody.writeTo(buffer);

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

            requestMessage.append('\n');
            if (isPlaintext(buffer)) {
                requestMessage.append(buffer.readString(charset)).append("\n--> END ").append(requestId)
                        .append(" (").append(requestBody.contentLength()).append("-byte body)\n");
            } else {
                requestMessage.append("--> END ").append(requestId).append(" (binary ")
                        .append(requestBody.contentLength()).append("-byte body omitted)\n");
            }
        }
    }

    logger.log(requestMessage.substring(0, requestMessage.length() - 1));

    long startNs = System.nanoTime();
    Response response;
    try {
        response = chain.proceed(request);
    } catch (Exception e) {
        logger.log("<-- " + requestId + "HTTP FAILED: " + e);
        throw e;
    }
    long tookMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNs);

    ResponseBody responseBody = response.body();
    long contentLength = responseBody.contentLength();
    StringBuilder responseMessage = new StringBuilder("<-- ").append(requestId).append(' ')
            .append(response.request().url()).append(" (").append(tookMs).append("ms");
    if (!logHeaders) {
        responseMessage.append(", ");
        if (contentLength != -1) {
            responseMessage.append(contentLength).append("-byte");
        } else {
            responseMessage.append("unknown-length");
        }
        responseMessage.append(" body");
    }
    responseMessage.append(")\n");

    responseMessage.append(response.code()).append(' ').append(response.message()).append('\n');

    if (logHeaders) {
        Headers headers = response.headers();
        for (int i = 0, count = headers.size(); i < count; i++) {
            responseMessage.append(headers.name(i)).append(": ").append(headers.value(i)).append('\n');
        }

        if (!logBody || !HttpEngine.hasBody(response)) {
            responseMessage.append("<-- END HTTP\n");
        } else if (bodyEncoded(response.headers())) {
            responseMessage.append("<-- END HTTP (encoded body omitted)\n");
        } else {
            BufferedSource source = responseBody.source();
            source.request(Long.MAX_VALUE); // Buffer the entire body.
            Buffer buffer = source.buffer();

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

            if (!isPlaintext(buffer)) {
                responseMessage.append('\n').append("<-- END HTTP (binary ").append(buffer.size())
                        .append("-byte body omitted)");
                logger.log(responseMessage.toString());
                return response;
            }

            if (contentLength != 0) {
                responseMessage.append('\n').append(buffer.clone().readString(charset)).append('\n');
            }

            responseMessage.append("<-- END HTTP (").append(buffer.size()).append("-byte body)\n");
        }
    }

    logger.log(responseMessage.substring(0, responseMessage.length() - 1));
    return response;
}

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;
        }/*from  w  w  w  . j  av a  2 s .co  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.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 {/*from w  w w. j  a v 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);
        }
    }
}