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 Project: allure-java   Author: allure-framework   File: AllureJaxRs.java    License: 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 #2
Source Project: cxf   Author: apache   File: JweClientResponseFilter.java    License: 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 #3
Source Project: cxf   Author: apache   File: JwsJsonClientResponseFilter.java    License: 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 #4
Source Project: robozonky   Author: RoboZonky   File: RoboZonkyFilter.java    License: 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 #5
Source Project: robozonky   Author: RoboZonky   File: AbstractCommonFilterTest.java    License: 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 #6
Source Project: opencensus-java   Author: census-instrumentation   File: JaxrsClientFilterTest.java    License: 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 #7
Source Project: opencensus-java   Author: census-instrumentation   File: JaxrsClientExtractorTest.java    License: 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 Project: java-jaxrs   Author: opentracing-contrib   File: ClientTracingFilter.java    License: 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 #9
Source Project: msf4j   Author: wso2   File: MSF4JClientTracingFilter.java    License: 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 #10
Source Project: ameba   Author: icode   File: LoggingFilter.java    License: 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 #11
Source Project: gitlab4j-api   Author: gitlab4j   File: MaskingLoggingFilter.java    License: 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 #12
Source Project: cxf   Author: apache   File: JweJsonClientResponseFilter.java    License: 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 #13
Source Project: docker-java   Author: docker-java   File: ResponseStatusExceptionFilter.java    License: 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 Project: quarkus   Author: quarkusio   File: LoggingFilter.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void filter(ClientRequestContext requestContext, ClientResponseContext responseContext)
        throws IOException {
    CALL_COUNT++;
    log.info("<< {} {}", responseContext.getStatusInfo().getStatusCode(),
            responseContext.getStatusInfo().getReasonPhrase());
}
 
Example #15
Source Project: sofa-rpc   Author: sofastack   File: TraceClientResponseFilter.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void filter(ClientRequestContext requestContext, ClientResponseContext responseContext) throws IOException {
    if (RpcInternalContext.isAttachmentEnable()) {
        // 补充客户端response长度
        RpcInternalContext context = RpcInternalContext.getContext();
        context.setAttachment(RpcConstants.INTERNAL_KEY_RESP_SIZE, responseContext.getLength());
    }
    RestTracerAdapter.clientReceived(responseContext);
}
 
Example #16
Source Project: cxf   Author: apache   File: VerifySignatureClientFilter.java    License: 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 #17
Source Project: allure-java   Author: allure-framework   File: AllureJaxRs.java    License: 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 #18
Source Project: newrelic-alerts-configurator   Author: ocadotechnology   File: NewRelicClientInterceptor.java    License: 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 Project: newrelic-alerts-configurator   Author: ocadotechnology   File: NewRelicClientInterceptor.java    License: Apache License 2.0 5 votes vote down vote up
private void logResponse(ClientRequestContext request, ClientResponseContext response) {
    LOG.info("{} {}: {} {}",
            request.getMethod(),
            request.getUri(),
            response.getStatus(),
            response.getStatusInfo().getReasonPhrase());
}
 
Example #20
Source Project: tracee   Author: tracee   File: TraceeClientFilter.java    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * This method handles the incoming response
 */
@Override
public void filter(final ClientRequestContext requestContext, final ClientResponseContext responseContext) {
	final List<String> serializedHeaders = responseContext.getHeaders().get(TraceeConstants.TPIC_HEADER);
	if (serializedHeaders != null && backend.getConfiguration().shouldProcessContext(IncomingResponse)) {
		final Map<String, String> parsed = transportSerialization.parse(serializedHeaders);
		backend.putAll(backend.getConfiguration().filterDeniedParams(parsed, IncomingResponse));
	}
}
 
Example #21
Source Project: newrelic-alerts-configurator   Author: ocadotechnology   File: NewRelicClientException.java    License: Apache License 2.0 5 votes vote down vote up
private static String formatMessage(ClientRequestContext request, ClientResponseContext response) {
    String method = request.getMethod();
    String url = request.getUri().toString();
    int statusCode = response.getStatus();
    String statusText = response.getStatusInfo().getReasonPhrase();
    return String.format("%s %s: %d %s", method, url, statusCode, statusText);
}
 
Example #22
Source Project: microprofile-rest-client   Author: eclipse   File: ThreadedClientResponseFilter.java    License: 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 #23
Source Project: robozonky   Author: RoboZonky   File: RoboZonkyFilter.java    License: 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 Project: robozonky   Author: RoboZonky   File: AuthenticatedFilterTest.java    License: 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 Project: tutorials   Author: eugenp   File: ResponseClientFilter.java    License: 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 #26
@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 #27
Source Project: cxf   Author: apache   File: JAXRS20ClientServerBookTest.java    License: 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");

}
 
Example #28
Source Project: cxf   Author: apache   File: ClientResponseFilterInterceptor.java    License: 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 Project: logbook   Author: zalando   File: LogbookClientFilter.java    License: 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 #30
Source Project: pay-publicapi   Author: alphagov   File: RestClientLoggingFilter.java    License: 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();
}