javax.ws.rs.client.ClientResponseContext Java Examples

The following examples show how to use javax.ws.rs.client.ClientResponseContext. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: JweJsonClientResponseFilter.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Override
public void filter(ClientRequestContext req, ClientResponseContext res) throws IOException {
    if (isMethodWithNoContent(req.getMethod())
        || isStatusCodeWithNoContent(res.getStatus())
        || isCheckEmptyStream() && !res.hasEntity()) {
        return;
    }
    final byte[] encryptedContent = IOUtils.readBytesFromStream(res.getEntityStream());
    if (encryptedContent.length == 0) {
        return;
    }
    JweDecryptionOutput out = decrypt(encryptedContent);
    byte[] bytes = out.getContent();
    res.setEntityStream(new ByteArrayInputStream(bytes));
    res.getHeaders().putSingle("Content-Length", Integer.toString(bytes.length));
    String ct = JoseUtils.checkContentType(out.getHeaders().getContentType(), getDefaultMediaType());
    if (ct != null) {
        res.getHeaders().putSingle("Content-Type", ct);
    }
    if (super.isValidateHttpHeaders()) {
        super.validateHttpHeadersIfNeeded(res.getHeaders(), out.getHeaders());
    }
}
 
Example #2
Source File: ClientTracingFilter.java    From java-jaxrs with Apache License 2.0 6 votes vote down vote up
@Override
public void filter(ClientRequestContext requestContext, ClientResponseContext responseContext) throws IOException {
    SpanWrapper spanWrapper = CastUtils
            .cast(requestContext.getProperty(PROPERTY_NAME), SpanWrapper.class);
    if (spanWrapper != null && !spanWrapper.isFinished()) {
        log.finest("Finishing client span");

        if (spanDecorators != null) {
            for (ClientSpanDecorator decorator: spanDecorators) {
                decorator.decorateResponse(responseContext, spanWrapper.get());
            }
        }

        spanWrapper.finish();
    }
}
 
Example #3
Source File: LoggingFilter.java    From ameba with MIT License 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public void filter(final ClientRequestContext requestContext, final ClientResponseContext responseContext)
        throws IOException {
    final Object requestId = requestContext.getProperty(LOGGING_ID_PROPERTY);
    final long id = requestId != null ? (Long) requestId : _id.incrementAndGet();

    StringBuilder b = (StringBuilder) requestContext.getProperty(LOGGER_BUFFER_PROPERTY);
    if (b == null) {
        b = new StringBuilder();
        requestContext.setProperty(LOGGER_BUFFER_PROPERTY, b);
    }

    printResponseLine(b, "Client response received", id, responseContext.getStatus());
    printPrefixedHeaders(b, id, RESPONSE_PREFIX, responseContext.getHeaders());

    if (printEntity && responseContext.hasEntity() && isSupportPrintType(responseContext.getMediaType())) {
        responseContext.setEntityStream(logInboundEntity(b, responseContext.getEntityStream(),
                MessageUtils.getCharset(responseContext.getMediaType())));
    }

    log(b);
}
 
Example #4
Source File: JwsJsonClientResponseFilter.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Override
public void filter(ClientRequestContext req, ClientResponseContext res) throws IOException {
    if (isMethodWithNoContent(req.getMethod())
        || isStatusCodeWithNoContent(res.getStatus())
        || isCheckEmptyStream() && !res.hasEntity()) {
        return;
    }
    final String content = IOUtils.readStringFromStream(res.getEntityStream());
    if (StringUtils.isEmpty(content)) {
        return;
    }
    JwsSignatureVerifier theSigVerifier = getInitializedSigVerifier();
    JwsJsonConsumer c = new JwsJsonConsumer(content);
    validate(c, theSigVerifier);
    byte[] bytes = c.getDecodedJwsPayloadBytes();
    res.setEntityStream(new ByteArrayInputStream(bytes));
    res.getHeaders().putSingle("Content-Length", Integer.toString(bytes.length));

    // the list is guaranteed to be non-empty
    JwsJsonSignatureEntry sigEntry = c.getSignatureEntries().get(0);
    String ct = JoseUtils.checkContentType(sigEntry.getUnionHeader().getContentType(), getDefaultMediaType());
    if (ct != null) {
        res.getHeaders().putSingle("Content-Type", ct);
    }
}
 
Example #5
Source File: JweClientResponseFilter.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Override
public void filter(ClientRequestContext req, ClientResponseContext res) throws IOException {
    if (isMethodWithNoContent(req.getMethod())
            || isStatusCodeWithNoContent(res.getStatus())
            || isCheckEmptyStream() && !res.hasEntity()) {
        return;
    }
    final byte[] encryptedContent = IOUtils.readBytesFromStream(res.getEntityStream());
    if (encryptedContent.length == 0) {
        return;
    }
    JweDecryptionOutput out = decrypt(encryptedContent);
    byte[] bytes = out.getContent();
    res.setEntityStream(new ByteArrayInputStream(bytes));
    res.getHeaders().putSingle("Content-Length", Integer.toString(bytes.length));
    String ct = JoseUtils.checkContentType(out.getHeaders().getContentType(), getDefaultMediaType());
    if (ct != null) {
        res.getHeaders().putSingle("Content-Type", ct);
    }
    if (super.isValidateHttpHeaders()) {
        super.validateHttpHeadersIfNeeded(res.getHeaders(), out.getHeaders());
    }
}
 
Example #6
Source File: RoboZonkyFilter.java    From robozonky with Apache License 2.0 6 votes vote down vote up
@Override
public void filter(final ClientRequestContext clientRequestContext,
        final ClientResponseContext clientResponseContext) throws IOException {
    logger.debug("HTTP {} Response from {}: {} {}.", clientRequestContext.getMethod(),
            clientRequestContext.getUri(), clientResponseContext.getStatus(),
            clientResponseContext.getStatusInfo()
                .getReasonPhrase());
    final String responseEntity = getResponseEntity(clientResponseContext);
    if (clientResponseContext.getStatus() == 400 && responseEntity.contains("invalid_token")) {
        // Zonky is dumb and throws 400 when it should throw 401
        clientResponseContext.setStatus(401);
    }
    responseHeaders = clientResponseContext.getHeaders()
        .entrySet()
        .stream()
        .filter(e -> !e.getValue()
            .isEmpty())
        .collect(Collectors.toMap(Map.Entry::getKey, e -> e.getValue()
            .get(0), (a, b) -> a, TreeMap::new));
}
 
Example #7
Source File: JaxrsClientExtractorTest.java    From opencensus-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testExtraction() {
  URI uri = URI.create("https://myhost/resource");

  ClientRequestContext requestContext = mock(ClientRequestContext.class);
  when(requestContext.getUri()).thenReturn(uri);
  when(requestContext.getMethod()).thenReturn("GET");
  when(requestContext.getHeaderString("user-agent")).thenReturn("java/1.8");

  ClientResponseContext responseContext = mock(ClientResponseContext.class);
  when(responseContext.getStatus()).thenReturn(200);

  JaxrsClientExtractor extractor = new JaxrsClientExtractor();
  assertEquals("myhost", extractor.getHost(requestContext));
  assertEquals("GET", extractor.getMethod(requestContext));
  assertEquals("/resource", extractor.getPath(requestContext));
  assertNull(extractor.getRoute(requestContext));
  assertEquals("https://myhost/resource", extractor.getUrl(requestContext));
  assertEquals("java/1.8", extractor.getUserAgent(requestContext));
  assertEquals(200, extractor.getStatusCode(responseContext));
}
 
Example #8
Source File: JaxrsClientFilterTest.java    From opencensus-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testResponseFilter() throws Exception {
  Span span = new FakeSpan(SpanContext.INVALID, null);
  TagContext tagContext = mock(TagContext.class);

  HttpRequestContext context = createHttpRequestContext(span, tagContext);

  ClientRequestContext requestContext = mock(ClientRequestContext.class);
  when(requestContext.getProperty("opencensus.context")).thenReturn(context);

  ClientResponseContext responseContext = mock(ClientResponseContext.class);

  filter.filter(requestContext, responseContext);

  verify(requestContext).getProperty("opencensus.context");
  verify(responseContext, times(1)).getStatus();
}
 
Example #9
Source File: AllureJaxRs.java    From allure-java with Apache License 2.0 6 votes vote down vote up
@Override
public void filter(final ClientRequestContext requestContext,
                   final ClientResponseContext responseContext) throws IOException {

    final HttpResponseAttachment.Builder responseAttachmentBuilder = HttpResponseAttachment.Builder
            .create("Response")
            .setResponseCode(responseContext.getStatus())
            .setHeaders(toMapConverter(requestContext.getHeaders()));

    if (Objects.nonNull(responseContext.getEntityStream())) {
        responseAttachmentBuilder.setBody(getBody(responseContext));
    }

    final HttpResponseAttachment responseAttachment = responseAttachmentBuilder.build();
    processor.addAttachment(responseAttachment, responseRenderer);
}
 
Example #10
Source File: MaskingLoggingFilter.java    From gitlab4j-api with MIT License 6 votes vote down vote up
@Override
public void filter(ClientRequestContext requestContext, ClientResponseContext responseContext) throws IOException {

    if (!logger.isLoggable(level)) {
        return;
    }

    final Object requestId = requestContext.getProperty(LOGGING_ID_PROPERTY);
    final long id = requestId != null ? (Long) requestId : _id.incrementAndGet();

    final StringBuilder sb = new StringBuilder();
    printResponseLine(sb, "Received server response", id, responseContext.getStatus());
    printHeaders(sb, id, RESPONSE_PREFIX, responseContext.getHeaders());
 
    if (responseContext.hasEntity() && maxEntitySize > 0) {
        responseContext.setEntityStream(logResponseEntity(sb, responseContext.getEntityStream(), 
                MessageUtils.getCharset(responseContext.getMediaType())));
    }

    log(sb);
}
 
Example #11
Source File: MSF4JClientTracingFilter.java    From msf4j with Apache License 2.0 6 votes vote down vote up
/**
 * Intercepts the client response flow and extract response information
 * to be published to the DAS server for tracing.
 */
@Override
public void filter(ClientRequestContext requestContext, ClientResponseContext responseContext) throws IOException {
    long time = new Date().getTime();
    TraceEvent traceEvent = (TraceEvent) requestContext.getProperty(TRACE_EVENT_ATTRIBUTE);
    if (traceEvent != null) {
        TraceEvent endTraceEvent = new TraceEvent(
                TracingConstants.CLIENT_TRACE_END,
                traceEvent.getTraceId(),
                traceEvent.getOriginId(),
                time
        );
        endTraceEvent.setStatusCode(responseContext.getStatus());
        TracingUtil.pushToDAS(endTraceEvent, dasUrl);
    }
}
 
Example #12
Source File: AbstractCommonFilterTest.java    From robozonky with Apache License 2.0 6 votes vote down vote up
protected static ClientResponseContext mockClientResponseContext(Map<String, Object> headers) {
    final MultivaluedMap<String, String> map = mock(MultivaluedMap.class);
    final Map<String, List<String>> result = new HashMap<>();
    headers.forEach((k, v) -> {
        if (v instanceof Collection) {
            var strings = ((Collection<Object>) v).stream()
                .map(Object::toString)
                .collect(Collectors.toList());
            result.put(k, strings);
        } else {
            result.put(k, Collections.singletonList(v.toString()));
        }
    });
    when(map.entrySet()).thenReturn(result.entrySet());
    final ClientResponseContext ctx = mock(ClientResponseContext.class);
    when(ctx.getHeaders()).thenReturn(map);
    return ctx;
}
 
Example #13
Source File: ResponseStatusExceptionFilter.java    From docker-java with Apache License 2.0 6 votes vote down vote up
@Override
public void filter(ClientRequestContext requestContext, ClientResponseContext responseContext) throws IOException {
    int status = responseContext.getStatus();
    switch (status) {
        case 200:
        case 201:
        case 204:
            return;
        case 304:
            throw new NotModifiedException(getBodyAsMessage(responseContext));
        case 400:
            throw new BadRequestException(getBodyAsMessage(responseContext));
        case 401:
            throw new UnauthorizedException(getBodyAsMessage(responseContext));
        case 404:
            throw new NotFoundException(getBodyAsMessage(responseContext));
        case 406:
            throw new NotAcceptableException(getBodyAsMessage(responseContext));
        case 409:
            throw new ConflictException(getBodyAsMessage(responseContext));
        case 500:
            throw new InternalServerErrorException(getBodyAsMessage(responseContext));
        default:
            throw new DockerException(getBodyAsMessage(responseContext), status);
    }
}
 
Example #14
Source File: FollowRedirectsFilter.java    From docker-java with Apache License 2.0 5 votes vote down vote up
@Override
public void filter(ClientRequestContext requestContext, ClientResponseContext responseContext) throws IOException {
    if (!responseContext.getStatusInfo().getFamily().equals(Response.Status.Family.REDIRECTION)) {
        return;
    }

    Response resp = requestContext.getClient().target(responseContext.getLocation()).request()
            .method(requestContext.getMethod());
    responseContext.setEntityStream((InputStream) resp.getEntity());
    responseContext.setStatusInfo(resp.getStatusInfo());
    responseContext.setStatus(resp.getStatus());
}
 
Example #15
Source File: VerifySignatureClientFilter.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Override
public void filter(ClientRequestContext requestContext, ClientResponseContext responseContext) {
    byte[] messageBody = verifyDigest(responseContext.getHeaders(), responseContext.getEntityStream());
    if (messageBody != null) {
        responseContext.setEntityStream(new ByteArrayInputStream(messageBody));
    }

    verifySignature(responseContext.getHeaders(), "", "");
}
 
Example #16
Source File: BraveClientProvider.java    From cxf with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public void filter(final ClientRequestContext requestContext,
        final ClientResponseContext responseContext) throws IOException {
    final TraceScopeHolder<TraceScope> holder =
        (TraceScopeHolder<TraceScope>)requestContext.getProperty(TRACE_SPAN);
    super.stopTraceSpan(holder, responseContext.getStatus());
}
 
Example #17
Source File: ResourceTestRuleBuilderTest.java    From dropwizard-java8 with Apache License 2.0 5 votes vote down vote up
@Test(expected = javax.ws.rs.NotFoundException.class)
public void testOptionalResponseEmpty() {
    testRule.client()
            .target("/optional/empty")
            .request()
            .get(ClientResponseContext.class);
}
 
Example #18
Source File: NewRelicClientInterceptor.java    From newrelic-alerts-configurator with Apache License 2.0 5 votes vote down vote up
@Override
public void filter(ClientRequestContext request, ClientResponseContext response) throws IOException {
    logResponse(request, response);
    if (!isSuccess(response)) {
        logResponseBody(response);
        throw new NewRelicClientException(request, response);
    }
}
 
Example #19
Source File: AllureJaxRs.java    From allure-java with Apache License 2.0 5 votes vote down vote up
private String getBody(final ClientResponseContext responseContext) throws IOException {
    try (InputStream stream = responseContext.getEntityStream();
         ByteArrayOutputStream result = new ByteArrayOutputStream()) {
        final byte[] buffer = new byte[1024];

        int length = stream.read(buffer);
        while (length != -1) {
            result.write(buffer, 0, length);
            length = stream.read(buffer);
        }
        responseContext.setEntityStream(new ByteArrayInputStream(result.toByteArray()));
        return result.toString(StandardCharsets.UTF_8.toString());
    }
}
 
Example #20
Source File: ThreadedClientResponseFilter.java    From microprofile-rest-client with Apache License 2.0 5 votes vote down vote up
@Override
public void filter(ClientRequestContext clientRequestContext, ClientResponseContext clientResponseContext) throws IOException {
    responseThreadId = "" + Thread.currentThread().getId();
    clientResponseContext.getHeaders().putSingle(RESPONSE_THREAD_ID_HEADER, responseThreadId);
    responseThreadName = Thread.currentThread().getName();
    clientResponseContext.getHeaders().putSingle(RESPONSE_THREAD_NAME_HEADER, responseThreadName);
}
 
Example #21
Source File: ResteasyGitLabClientBuilder.java    From gitlab-plugin with GNU General Public License v2.0 5 votes vote down vote up
private String getResponseBody(ClientResponseContext context) {
    try (InputStream entityStream = context.getEntityStream()) {
        if (entityStream != null) {
            byte[] bytes = IOUtils.toByteArray(entityStream);
            context.setEntityStream(new ByteArrayInputStream(bytes));
            return new String(bytes);
        }
    } catch (IOException e) {
        LOGGER.log(Level.SEVERE, "Failure during reading the response body", e);
        context.setEntityStream(new ByteArrayInputStream(new byte[0]));
    }
    return "";
}
 
Example #22
Source File: ResteasyGitLabClientBuilder.java    From gitlab-plugin with GNU General Public License v2.0 5 votes vote down vote up
private String getPrettyPrintResponseBody(ClientResponseContext responseContext) {
    String responseBody = getResponseBody(responseContext);
    if (StringUtils.isNotEmpty(responseBody) && responseContext.getMediaType().equals(MediaType.APPLICATION_JSON_TYPE)) {
        return JsonUtil.toPrettyPrint(responseBody);
    }
    return responseBody;
}
 
Example #23
Source File: RoboZonkyFilter.java    From robozonky with Apache License 2.0 5 votes vote down vote up
private String getResponseEntity(final ClientResponseContext clientResponseContext) throws IOException {
    if (shouldLogEntity(clientResponseContext)) {
        final InterceptingInputStream s = new InterceptingInputStream(clientResponseContext.getEntityStream());
        clientResponseContext.setEntityStream(s);
        logger.debug("Response body is: {}", s.getContents());
        return s.getContents();
    } else {
        return "";
    }
}
 
Example #24
Source File: AuthenticatedFilterTest.java    From robozonky with Apache License 2.0 5 votes vote down vote up
@Test
void changes400to401() throws IOException, URISyntaxException {
    final int expectedCode = 400;
    final ClientRequestContext ctx = mockClientRequestContext();
    final ClientResponseContext ctx2 = mockClientResponseContext();
    when(ctx2.hasEntity()).thenReturn(true);
    when(ctx2.getEntityStream()).thenReturn(c(TOKEN));
    when(ctx2.getStatusInfo()).thenReturn(Response.Status.fromStatusCode(expectedCode));
    when(ctx2.getStatus()).thenReturn(expectedCode);
    final RoboZonkyFilter filter = getTestedFilter();
    filter.filter(ctx, ctx2);
    verify(ctx2, times(1)).setStatus(401);
}
 
Example #25
Source File: RestClientLoggingFilter.java    From pay-publicapi with MIT License 5 votes vote down vote up
@Override
public void filter(ClientRequestContext requestContext, ClientResponseContext responseContext) {
    long elapsed = timer.get().elapsed(TimeUnit.MILLISECONDS);
    responseContext.getHeaders().add(HEADER_REQUEST_ID, requestId.get());
    logger.info(format("[%s] - %s to %s ended - total time %dms",
            requestId.get(),
            requestContext.getMethod(),
            requestContext.getUri(),
            elapsed));

    requestId.remove();
    timer.get().stop();
    timer.remove();
}
 
Example #26
Source File: ResponseClientFilter.java    From tutorials with MIT License 5 votes vote down vote up
@Override
public void filter(ClientRequestContext requestContext, ClientResponseContext responseContext) throws IOException {
    LOG.info("Response client filter");

    responseContext.getHeaders()
        .add("X-Test-Client", "Test response client filter");
}
 
Example #27
Source File: LogbookClientFilter.java    From logbook with MIT License 5 votes vote down vote up
@Override
public void filter(final ClientRequestContext request, final ClientResponseContext context) {
    read(request::getProperty, "process-response", ResponseProcessingStage.class)
            .ifPresent(throwingConsumer(stage -> {
                final RemoteResponse response = new RemoteResponse(context);
                final ResponseWritingStage write = stage.process(response);
                response.expose();
                write.write();
            }));
}
 
Example #28
Source File: ClientResponseFilterInterceptor.java    From cxf with Apache License 2.0 5 votes vote down vote up
public void handleMessage(Message inMessage) throws Fault {
    ClientProviderFactory pf = ClientProviderFactory.getInstance(inMessage);
    if (pf == null) {
        return;
    }

    List<ProviderInfo<ClientResponseFilter>> filters = pf.getClientResponseFilters();
    if (!filters.isEmpty()) {
        final ClientRequestContext reqContext = new ClientRequestContextImpl(
            inMessage.getExchange().getOutMessage(), true);
        final ResponseImpl response = (ResponseImpl)getResponse(inMessage);
        final ClientResponseContext respContext = new ClientResponseContextImpl(response, inMessage);
        for (ProviderInfo<ClientResponseFilter> filter : filters) {
            InjectionUtils.injectContexts(filter.getProvider(), filter, inMessage);
            try {
                filter.getProvider().filter(reqContext, respContext);
            } catch (RuntimeException | IOException ex) {
                // Complete the IN chain, if we won't set it, the AbstractClient::preProcessResult
                // would be stuck waiting for the IN chain completion.
                if (!inMessage.getExchange().isOneWay()) {
                    synchronized (inMessage.getExchange()) {
                        inMessage.getExchange().put("IN_CHAIN_COMPLETE", Boolean.TRUE);
                    }
                }
                
                // When a provider method throws an exception, the JAX-RS client runtime will map 
                // it to an instance of ResponseProcessingException if thrown while processing 
                // a response (4.5.2 Client Runtime).
                throw new ResponseProcessingException(response, ex);
            }
        }
    }
}
 
Example #29
Source File: RequestMetricsClientResponseFilter.java    From cf-java-logging-support with Apache License 2.0 5 votes vote down vote up
@Override
public void filter(ClientRequestContext requestContext, ClientResponseContext responseContext) throws IOException {
    try {
        handler.handle(new ClientResponseContextAdapter(responseContext), (RequestRecord) requestContext
                                                                                                        .getProperty(REQ_METRICS_KEY));
    } catch (Exception ex) {
        LoggerFactory.getLogger(RequestMetricsClientResponseFilter.class).error("Can't handle client response", ex);
    }
}
 
Example #30
Source File: JAXRS20ClientServerBookTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Override
public void filter(ClientRequestContext reqContext,
                   ClientResponseContext respContext) throws IOException {
    MultivaluedMap<String, String> headers = respContext.getHeaders();
    if (!local) {
        assertEquals(1, headers.get("Date").size());
    }
    headers.putSingle(HttpHeaders.LOCATION, "http://localhost/redirect");

}