Example usage for org.apache.http.client.protocol HttpClientContext getResponse

List of usage examples for org.apache.http.client.protocol HttpClientContext getResponse

Introduction

In this page you can find the example usage for org.apache.http.client.protocol HttpClientContext getResponse.

Prototype

public HttpResponse getResponse() 

Source Link

Usage

From source file:net.www_eee.portal.channels.ProxyChannel.java

@Override
protected void doViewRequestImpl(final Page.Request pageRequest, final ViewResponse viewResponse)
        throws WWWEEEPortal.Exception, WebApplicationException {
    final HttpClientContext proxyContext = doProxyRequest(pageRequest, Mode.VIEW);

    final @NonNull HttpResponse proxyResponse = proxyContext.getResponse();
    final URL proxiedFileURL = HttpUtil.getRequestTargetURL(proxyContext);

    try (final CloseableHttpClient proxyClient = Objects
            .requireNonNull((CloseableHttpClient) proxyContext.getAttribute(HTTP_CLIENT_CONTEXT_ID))) {

        final MimeType responseContentType = getProxyResponseHeader(pageRequest, proxyResponse, "Content-Type",
                IOUtil::newMimeType);/*from   w ww . java  2s. c o  m*/
        viewResponse.setContentType(
                (responseContentType != null) ? RESTUtil.getMediaType(responseContentType) : null);

        viewResponse.setLastModified(getProxyResponseHeader(pageRequest, proxyResponse, "Last-Modified",
                (s) -> ZonedDateTime.parse(s, DateTimeFormatter.RFC_1123_DATE_TIME).toInstant()));
        viewResponse.setCacheControl(mergeCacheControl(viewResponse.getCacheControl(),
                getProxyResponseHeader(pageRequest, proxyResponse, "Cache-Control", CacheControl::valueOf)));
        viewResponse.setExpires(getProxyResponseHeader(pageRequest, proxyResponse, "Expires",
                (s) -> ZonedDateTime.parse(s, DateTimeFormatter.RFC_1123_DATE_TIME).toInstant()));
        viewResponse
                .setEntityTag(getProxyResponseHeader(pageRequest, proxyResponse, "ETag", EntityTag::valueOf));
        viewResponse.setLocale(getProxyResponseHeader(pageRequest, proxyResponse, "Content-Language",
                (h) -> Locale.forLanguageTag(
                        CollUtil.first(Arrays.asList(StringUtil.COMMA_SEPARATED_PATTERN.split(h))).get())));

        if (isRenderedUsingXMLView(pageRequest, proxyResponse, responseContentType)) {
            renderXMLView(pageRequest, viewResponse, proxyResponse, proxiedFileURL, responseContentType);
        } else if (isRenderedUsingTextView(pageRequest, proxyResponse, responseContentType)) {
            renderTextView(pageRequest, viewResponse, proxyResponse, proxiedFileURL, responseContentType);
        } else {
            renderResourceReferenceView(pageRequest, viewResponse, proxiedFileURL, responseContentType);
        }

    } catch (WWWEEEPortal.Exception wpe) {
        LogAnnotation.annotate(wpe, "ProxyContext", proxyContext, null, false);
        LogAnnotation.annotate(wpe, "ProxyResponse", proxyResponse, null, false);
        LogAnnotation.annotate(wpe, "ProxiedFileURL", proxiedFileURL, null, false); // This wouldn't be necessary if any of the previous annotations could actually toString() themselves usefully.
        throw wpe;
    } catch (IOException ioe) {
        throw new WWWEEEPortal.OperationalException(ioe);
    }

    return;
}

From source file:net.www_eee.portal.channels.ProxyChannel.java

/**
 * Examine the {@linkplain HttpResponse#getStatusLine() status} {@link StatusLine#getStatusCode() code} from the
 * response to the {@linkplain #doProxyRequest(Page.Request, Channel.Mode) proxy request} and throw an exception if
 * something went wrong.//from   w  w  w  .  j ava  2s.c  om
 * 
 * @param proxyContext The {@link HttpClientContext} containing the {@linkplain ExecutionContext#HTTP_RESPONSE
 * response} from the proxied server.
 * @param pageRequest The {@link net.www_eee.portal.Page.Request Request} currently being processed.
 * @param mode The {@link net.www_eee.portal.Channel.Mode Mode} of the request.
 * @return The supplied <code>proxyClientContext</code> argument.
 * @throws WWWEEEPortal.Exception If a problem occurred while determining the result.
 * @throws WebApplicationException If a problem occurred while determining the result.
 * @see #doProxyRequest(Page.Request, Channel.Mode)
 */
protected HttpClientContext validateProxyResponse(final HttpClientContext proxyContext,
        final Page.Request pageRequest, final Mode mode)
        throws WWWEEEPortal.Exception, WebApplicationException {
    final HttpResponse proxyResponse = proxyContext.getResponse();
    final int responseCode = proxyResponse.getStatusLine().getStatusCode();
    if (responseCode == Response.Status.OK.getStatusCode())
        return proxyContext;
    try {
        if (responseCode == Response.Status.NOT_MODIFIED.getStatusCode()) {
            throw new WebApplicationException(Response.Status.NOT_MODIFIED);
        } else if (((responseCode >= Response.Status.MOVED_PERMANENTLY.getStatusCode())
                && (responseCode <= Response.Status.SEE_OTHER.getStatusCode()))
                || (responseCode == Response.Status.TEMPORARY_REDIRECT.getStatusCode())) { // Moved Permanently, Found, See Other, Temporary Redirect
            if (pageRequest.isMaximized(this)) {
                final URI fixedLocation;
                try {
                    final Optional<URI> locationURI = HttpUtil.getValue(proxyResponse.getLastHeader("Location"),
                            URI::create);
                    final URL proxiedFileURL = HttpUtil.getRequestTargetURL(proxyContext);
                    fixedLocation = rewriteProxiedFileLink(pageRequest, proxiedFileURL,
                            locationURI.orElse(null), Mode.VIEW.equals(mode), true).getKey();
                } catch (Exception e) {
                    throw new ContentManager.ContentException("Error rewriting 'Location' header", e);
                }
                throw new WebApplicationException(
                        Response.status(RESTUtil.Response.Status.fromStatusCode(responseCode))
                                .location(fixedLocation).build());
            }
        } else if (responseCode == Response.Status.UNAUTHORIZED.getStatusCode()) {
            if (pageRequest.isMaximized(this)) {
                throw new WebApplicationException(Response.status(Response.Status.UNAUTHORIZED)
                        .header("WWW-Authenticate", HttpUtil
                                .getValue(proxyResponse.getLastHeader("WWW-Authenticate"), Function.identity())
                                .orElse(null))
                        .build());
            }
        } else if ((responseCode == Response.Status.NOT_FOUND.getStatusCode())
                || (responseCode == Response.Status.GONE.getStatusCode())) {
            final URI channelLocalPath = pageRequest.getChannelLocalPath(this);
            if (channelLocalPath != null) {
                throw new WebApplicationException(Response.Status.fromStatusCode(responseCode));
            }
        } else if (responseCode == RESTUtil.Response.Status.METHOD_NOT_ALLOWED.getStatusCode()) {
            final URI channelLocalPath = pageRequest.getChannelLocalPath(this);
            if (channelLocalPath != null) {
                throw new WebApplicationException(
                        Response.status(RESTUtil.Response.Status.METHOD_NOT_ALLOWED)
                                .header("Allow", HttpUtil
                                        .getValue(proxyResponse.getLastHeader("Allow"), Function.identity())
                                        .orElse(null))
                                .build());
            }
        } else if (responseCode == RESTUtil.Response.Status.REQUEST_TIMEOUT.getStatusCode()) { // we didn't send it to the proxied server fast enough!?
            throw new WWWEEEPortal.OperationalException(new WebApplicationException(responseCode));
        } else if (responseCode == Response.Status.BAD_REQUEST.getStatusCode()) {
            throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST).build());
        } else if ((responseCode >= 400) && (responseCode < 500)) { // All other 4XX errors
            if (pageRequest.isMaximized(this)) {
                throw new WebApplicationException(
                        Response.status(RESTUtil.Response.Status.fromStatusCode(responseCode)).build());
            }
        } else if ((responseCode >= RESTUtil.Response.Status.BAD_GATEWAY.getStatusCode())
                && (responseCode <= RESTUtil.Response.Status.GATEWAY_TIMEOUT.getStatusCode())) { // Bad Gateway, Service Unavailable, Gateway Timeout
            throw new WWWEEEPortal.OperationalException(new WebApplicationException(responseCode));
        }
        final Response.StatusType statusType = RESTUtil.Response.Status.fromStatusCode(responseCode);
        final String codePhrase = (statusType != null) ? " (" + statusType.getReasonPhrase() + ")" : "";
        final String responsePhrase = (proxyResponse.getStatusLine().getReasonPhrase() != null)
                ? ": " + proxyResponse.getStatusLine().getReasonPhrase()
                : "";
        final ConfigManager.ConfigException configurationException = new ConfigManager.ConfigException(
                "The proxied file server returned code '" + responseCode + "'" + codePhrase + responsePhrase,
                null);
        if (getLogger().isLoggable(Level.FINE)) {
            try {
                final Reader reader = createProxiedFileReader(proxyResponse, getProxyResponseHeader(pageRequest,
                        proxyResponse, "Content-Type", IOUtil::newMimeType));
                LogAnnotation.annotate(configurationException, "ProxiedFileResponseContent",
                        (reader != null) ? IOUtil.toString(reader) : null, Level.FINE, false);
            } catch (Exception e) {
            }
        }
        throw configurationException;
    } catch (WWWEEEPortal.Exception wpe) {
        try {
            LogAnnotation.annotate(wpe, "ProxiedFileURL", HttpUtil.getRequestTargetURL(proxyContext), null,
                    false);
        } catch (Exception e) {
        }
        LogAnnotation.annotate(wpe, "ProxiedFileResponseCode", responseCode, null, false);
        LogAnnotation.annotate(wpe, "ProxiedFileResponseCodeReasonPhrase",
                RESTUtil.Response.Status.fromStatusCode(responseCode), null, false);
        LogAnnotation.annotate(wpe, "ProxiedFileResponseReasonPhrase",
                proxyResponse.getStatusLine().getReasonPhrase(), null, false);
        throw wpe;
    }
}

From source file:net.www_eee.portal.channels.ProxyChannel.java

@Override
protected Response doResourceRequestImpl(final Page.Request pageRequest)
        throws WWWEEEPortal.Exception, WebApplicationException {
    final HttpClientContext proxyContext = doProxyRequest(pageRequest, Mode.RESOURCE);
    @SuppressWarnings("resource")
    final CloseableHttpClient proxyClient = Objects
            .requireNonNull((CloseableHttpClient) proxyContext.getAttribute(HTTP_CLIENT_CONTEXT_ID));

    final @NonNull HttpResponse proxyResponse = proxyContext.getResponse();

    try {/*from  ww  w  . j  a  v a2 s .c o  m*/

        final Response.ResponseBuilder responseBuilder = Response.ok();

        responseBuilder.lastModified(getProxyResponseHeader(pageRequest, proxyResponse, "Last-Modified",
                (s) -> Date.from(ZonedDateTime.parse(s, DateTimeFormatter.RFC_1123_DATE_TIME).toInstant())));
        final MimeType responseContentType = getProxyResponseHeader(pageRequest, proxyResponse, "Content-Type",
                IOUtil::newMimeType);
        responseBuilder.type((responseContentType != null) ? RESTUtil.getMediaType(responseContentType) : null);
        responseBuilder.cacheControl(mergeCacheControl(getCacheControlDefault().orElse(null),
                getProxyResponseHeader(pageRequest, proxyResponse, "Cache-Control", CacheControl::valueOf)));
        responseBuilder.expires(getProxyResponseHeader(pageRequest, proxyResponse, "Expires",
                (s) -> Date.from(ZonedDateTime.parse(s, DateTimeFormatter.RFC_1123_DATE_TIME).toInstant())));
        responseBuilder.tag(getProxyResponseHeader(pageRequest, proxyResponse, "ETag", EntityTag::valueOf));
        responseBuilder.language(getProxyResponseHeader(pageRequest, proxyResponse, "Content-Language",
                (h) -> Locale.forLanguageTag(StringUtil.COMMA_SEPARATED_PATTERN.split("")[0]).toString()));

        final HttpEntity proxyResponseEntity = proxyResponse.getEntity();
        final Long contentLength = (proxyResponseEntity != null)
                ? Long.valueOf(proxyResponseEntity.getContentLength())
                : null;
        responseBuilder.header("Content-Length", contentLength);

        if (proxyResponseEntity != null) {
            responseBuilder.entity(HttpUtil.getDataSource(proxyResponseEntity, proxyClient));
        } else {
            try {
                proxyClient.close();
            } catch (IOException ioe) {
                throw new WWWEEEPortal.OperationalException(ioe);
            }
        }

        return responseBuilder.build();

    } catch (WWWEEEPortal.Exception wpe) {
        LogAnnotation.annotate(wpe, "ProxyContext", proxyContext, null, false);
        LogAnnotation.annotate(wpe, "ProxyResponse", proxyResponse, null, false);
        try {
            LogAnnotation.annotate(wpe, "ProxiedFileURL", HttpUtil.getRequestTargetURL(proxyContext), null,
                    false); // This wouldn't be necessary if any of the previous annotations could actually toString() themselves usefully.
        } catch (Exception e) {
        }
        throw wpe;
    }
}