Java Code Examples for javax.ws.rs.client.ClientRequestContext

The following examples show how to use javax.ws.rs.client.ClientRequestContext. These examples are extracted from open source projects. 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 want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: etcd-viewer   Source File: EtcdV2ProxyImpl.java    License: Apache License 2.0 6 votes vote down vote up
private WebTarget getWebTarget() {
    if (client == null) {
        client = ClientBuilder.newClient();
        client.register(JacksonJsonProvider.class);

        // register the basic authentication filter if authentication information is provided
        if (authenticationToken != null) {
            client.register(new ClientRequestFilter() {
                @Override
                public void filter(ClientRequestContext requestContext) throws IOException {
                    requestContext.getHeaders().add("Authorization", "Basic " + authenticationToken);
                }
            });
        }

    }

    WebTarget target = client.target(targetUrl);

    return target;
}
 
Example 2
Source Project: sofa-rpc   Source File: TraceClientRequestFilter.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void filter(ClientRequestContext requestContext) throws IOException {
    try {

        if (RpcInternalContext.isAttachmentEnable()) {
            // 补充客户端request长度
            RpcInternalContext context = RpcInternalContext.getContext();
            context.setAttachment(RpcConstants.INTERNAL_KEY_REQ_SIZE,
                requestContext.getHeaderString(HttpHeaders.CONTENT_LENGTH));

        }

        RestTracerAdapter.beforeSend(requestContext);
    } catch (Exception e) {
        logger.error(LogCodes.getLog(LogCodes.ERROR_TRACER_UNKNOWN_EXP, "filter", "rest", "client"), e);
    }
}
 
Example 3
Source Project: cxf   Source File: JAXRS20ClientServerBookTest.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void filter(ClientRequestContext rc) throws IOException {
    String method = rc.getMethod();
    String expectedMethod = null;
    if (rc.getAcceptableMediaTypes().contains(MediaType.valueOf("text/mistypedxml"))
        && rc.getHeaders().getFirst("THEMETHOD") != null) {
        expectedMethod = MediaType.TEXT_XML_TYPE.equals(rc.getMediaType()) ? "DELETE" : "GET";
        rc.setUri(URI.create("http://localhost:" + PORT + "/bookstore/books2"));
        rc.setMethod(rc.getHeaders().getFirst("THEMETHOD").toString());
        if ("GET".equals(expectedMethod)) {
            rc.getHeaders().putSingle("Content-Type", "text/xml");
        }
    } else {
        expectedMethod = "POST";
    }


    if (!expectedMethod.equals(method)) {
        throw new RuntimeException();
    }
    if ("GET".equals(expectedMethod)) {
        rc.setEntity(new Book("book", 560L));
    } else {
        rc.setEntity(new Book("book", ((Book)rc.getEntity()).getId() + 5));
    }
}
 
Example 4
Source Project: cxf   Source File: JAXRS20ClientServerBookTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testGetSetEntityStream() {
    String address = "http://localhost:" + PORT + "/bookstore/entityecho";
    String entity = "BOOKSTORE";

    Client client = ClientBuilder.newClient();
    client.register(new ClientRequestFilter() {
        @Override
        public void filter(ClientRequestContext context) throws IOException {
            context.setEntityStream(new ReplacingOutputStream(
                             context.getEntityStream(), 'X', 'O'));
        }
    });

    WebTarget target = client.target(address);

    Response response = target.request().post(
            Entity.entity(entity.replace('O', 'X'), "text/plain"));
    assertEquals(entity, response.readEntity(String.class));
}
 
Example 5
Source Project: keycloak   Source File: BearerAuthFilter.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void filter(ClientRequestContext requestContext, ClientResponseContext responseContext) throws IOException {
    if (responseContext.getStatus() == 401 && tokenManager != null) {
        List<Object> authHeaders = requestContext.getHeaders().get(HttpHeaders.AUTHORIZATION);
        if (authHeaders == null) {
            return;
        }
        for (Object authHeader : authHeaders) {
            if (authHeader instanceof String) {
                String headerValue = (String) authHeader;
                if (headerValue.startsWith(AUTH_HEADER_PREFIX)) {
                    String token = headerValue.substring( AUTH_HEADER_PREFIX.length() );
                    tokenManager.invalidate( token );
                }
            }
        }
    }
}
 
Example 6
Source Project: SCIM-Client   Source File: AuthorizationInjectionFilter.java    License: Apache License 2.0 6 votes vote down vote up
public void filter(ClientRequestContext context) {

        MultivaluedMap<String, Object> headers = context.getHeaders();
        String authzHeader = ClientMap.getValue(context.getClient());

        if (StringUtils.isNotEmpty(authzHeader)) {   //resteasy client is tied to an authz header
            headers.putSingle("Authorization", authzHeader);
        }
        //Inject custom headers
        Optional.ofNullable(System.getProperty("scim.extraHeaders"))
                .map(str -> Arrays.asList(str.split(",\\s*"))).orElse(Collections.emptyList())
                .forEach(prop ->
                        Optional.ofNullable(System.getProperty("scim.header." + prop))
                                .ifPresent(value -> headers.putSingle(prop,  value))
                );

    }
 
Example 7
Source Project: dubbox-hystrix   Source File: RpcContextFilter.java    License: Apache License 2.0 6 votes vote down vote up
public void filter(ClientRequestContext requestContext) throws IOException {
    int size = 0;
    for (Map.Entry<String, String> entry : RpcContext.getContext().getAttachments().entrySet()) {
        if (entry.getValue().contains(",") || entry.getValue().contains("=")
                || entry.getKey().contains(",") || entry.getKey().contains("=")) {
            throw new IllegalArgumentException("The attachments of " + RpcContext.class.getSimpleName() + " must not contain ',' or '=' when using rest protocol");
        }

        // TODO for now we don't consider the differences of encoding and server limit
        size += entry.getValue().getBytes("UTF-8").length;
        if (size > MAX_HEADER_SIZE) {
            throw new IllegalArgumentException("The attachments of " + RpcContext.class.getSimpleName() + " is too big");
        }

        StringBuilder attachments = new StringBuilder();
        attachments.append(entry.getKey());
        attachments.append("=");
        attachments.append(entry.getValue());
        requestContext.getHeaders().add(DUBBO_ATTACHMENT_HEADER, attachments.toString());
    }
}
 
Example 8
Source Project: docker-java   Source File: LoggingFilter.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void filter(final ClientRequestContext context) throws IOException {
    final long id = aid.incrementAndGet();
    final StringBuilder b = new StringBuilder();

    printRequestLine(b, "Sending client request", id, context.getMethod(), context.getUri());
    printPrefixedHeaders(b, id, REQUEST_PREFIX, context.getStringHeaders());

    if (printEntity && context.hasEntity()) {
        final OutputStream stream = new LoggingStream(b, context.getEntityStream());
        context.setEntityStream(stream);
        context.setProperty(ENTITY_LOGGER_PROPERTY, stream);
        // not calling log(b) here - it will be called by the interceptor
    } else {
        log(b);
    }
}
 
Example 9
Source Project: cxf   Source 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 10
Source Project: ameba   Source 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
@Override
public void filter(ClientRequestContext ctx) throws IOException {
    try {
        Method m = (Method) ctx.getProperty("org.eclipse.microprofile.rest.client.invokedMethod");

        Path path = m.getAnnotation(Path.class);
        ctx.abortWith(Response.ok("OK")
                              .header("ReturnType", m.getReturnType().getName())
                              .header("POST", m.getAnnotation(POST.class) == null ? "null" : "POST")
                              .header("Path", path == null ? "null" : path.value())
                              .build());
    }
    catch (Throwable t) {
        t.printStackTrace();
        ctx.abortWith(Response.serverError().build());
    }
}
 
Example 12
Source Project: ameba   Source File: LoggingFilter.java    License: MIT License 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public void filter(final ClientRequestContext context) throws IOException {
    final long id = _id.incrementAndGet();
    context.setProperty(LOGGING_ID_PROPERTY, id);

    final StringBuilder b = new StringBuilder();

    printRequestLine(b, "Sending client request", id, context.getMethod(), context.getUri());
    printPrefixedHeaders(b, id, REQUEST_PREFIX, context.getStringHeaders());

    if (printEntity && context.hasEntity() && isSupportPrintType(context.getMediaType())) {
        final OutputStream stream = new LoggingStream(b, context.getEntityStream());
        context.setEntityStream(stream);
        context.setProperty(ENTITY_LOGGER_PROPERTY, stream);
        // not calling log(b) here - it will be called by the interceptor
    } else {
        log(b);
    }
}
 
Example 13
Source Project: dubbox   Source File: RpcContextFilter.java    License: Apache License 2.0 6 votes vote down vote up
public void filter(ClientRequestContext requestContext) throws IOException {
    int size = 0;
    for (Map.Entry<String, String> entry : RpcContext.getContext().getAttachments().entrySet()) {
        if (entry.getValue().contains(",") || entry.getValue().contains("=")
                || entry.getKey().contains(",") || entry.getKey().contains("=")) {
            throw new IllegalArgumentException("The attachments of " + RpcContext.class.getSimpleName() + " must not contain ',' or '=' when using rest protocol");
        }

        // TODO for now we don't consider the differences of encoding and server limit
        size += entry.getValue().getBytes("UTF-8").length;
        if (size > MAX_HEADER_SIZE) {
            throw new IllegalArgumentException("The attachments of " + RpcContext.class.getSimpleName() + " is too big");
        }

        StringBuilder attachments = new StringBuilder();
        attachments.append(entry.getKey());
        attachments.append("=");
        attachments.append(entry.getValue());
        requestContext.getHeaders().add(DUBBO_ATTACHMENT_HEADER, attachments.toString());
    }
}
 
Example 14
Source Project: robozonky   Source 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 15
Source Project: robozonky   Source File: AuthenticationFilterTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
void wasAuthorizationAdded() throws URISyntaxException {
    final ClientRequestContext crc = mockClientRequestContext();
    this.getTestedFilter()
        .filter(crc);
    verify(crc.getHeaders()).putSingle(eq("Authorization"), any());
}
 
Example 16
Source Project: robozonky   Source File: AbstractCommonFilterTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
void request() throws URISyntaxException {
    final ClientRequestContext ctx = mockClientRequestContext();
    final RoboZonkyFilter filter = getTestedFilter();
    filter.setQueryParam("something", "value");
    filter.filter(ctx);
    verify(ctx).setUri(new URI("http://localhost?something=value"));
}
 
Example 17
Source Project: FHIR   Source File: FHIRBasicAuthenticator.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * This method is called by the JAX-RS client runtime and will add an Authorization header to the
 * outbound REST API request to supply the necessary basic auth security token.
 */
@Override
public void filter(ClientRequestContext ctxt) throws IOException {
    if (getUsername() != null && !getUsername().isEmpty()) {
        MultivaluedMap<String, Object> headers = ctxt.getHeaders();
        String basicAuthToken = getUsername() + ":" + getPassword();
        String basicAuthString = "Basic " + Base64.getEncoder().encodeToString(basicAuthToken.getBytes());
        headers.add("Authorization", basicAuthString);  
    }
}
 
Example 18
Source Project: FHIR   Source File: FHIRBasicAuthenticator.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * This method is called by the JAX-RS client runtime and will add an Authorization header to the
 * outbound REST API request to supply the necessary basic auth security token.
 */
@Override
public void filter(ClientRequestContext ctxt) throws IOException {
    if (getUsername() != null && !getUsername().isEmpty()) {
        MultivaluedMap<String, Object> headers = ctxt.getHeaders();
        String basicAuthToken = getUsername() + ":" + getPassword();
        String basicAuthString = "Basic " + Base64.getEncoder().encodeToString(basicAuthToken.getBytes());
        headers.add("Authorization", basicAuthString);
    }
}
 
Example 19
/**
 * This method handles the outgoing request
 */
@Override
public void filter(final ClientRequestContext requestContext) {
	if (!backend.isEmpty() && backend.getConfiguration().shouldProcessContext(OutgoingRequest)) {
		final Map<String, String> filtered = backend.getConfiguration().filterDeniedParams(backend.copyToMap(), OutgoingRequest);
		requestContext.getHeaders().putSingle(TraceeConstants.TPIC_HEADER, transportSerialization.render(filtered));
	}
}
 
Example 20
Source Project: cxf   Source File: JAXRS20ClientServerBookTest.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void filter(ClientRequestContext context) throws IOException {
    String opName =
        (String)JAXRSUtils.getCurrentMessage().getExchange().get("org.apache.cxf.resource.operation.name");
    assertFalse(opName.endsWith("?a=b"));
    context.getHeaders().putSingle("Simple", "simple");
    if (context.hasEntity()) {
        context.getHeaders().putSingle("Content-Type", MediaType.APPLICATION_XML_TYPE);
    }
}
 
Example 21
Source Project: cxf   Source File: JwsClientResponseFilter.java    License: Apache License 2.0 5 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;
    }
    JwsCompactConsumer p = new JwsCompactConsumer(content);
    JwsSignatureVerifier theSigVerifier = getInitializedSigVerifier(p.getJwsHeaders());
    if (!p.verifySignatureWith(theSigVerifier)) {
        throw new JwsException(JwsException.Error.INVALID_SIGNATURE);
    }

    byte[] bytes = p.getDecodedJwsPayloadBytes();
    res.setEntityStream(new ByteArrayInputStream(bytes));
    res.getHeaders().putSingle("Content-Length", Integer.toString(bytes.length));
    String ct = JoseUtils.checkContentType(p.getJwsHeaders().getContentType(), getDefaultMediaType());
    if (ct != null) {
        res.getHeaders().putSingle("Content-Type", ct);
    }

    if (super.isValidateHttpHeaders()) {
        super.validateHttpHeadersIfNeeded(res.getHeaders(), p.getJwsHeaders());
    }
}
 
Example 22
Source Project: quarkus   Source File: MyFilter.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void filter(ClientRequestContext requestContext) throws IOException {
    if (requestContext.getUri().toString().contains("/called-from-client?")) {
        // make sure we have a request context
        Assertions.assertTrue(Arc.container().requestContext().isActive());
        // remember which request context for later examination
        collector.setRequestBeanFromFilter(requestBean.getUniqueNumber());
        // make sure we don't inherit the server's resteasy context
        Assertions.assertNull(ResteasyContext.getContextData(String.class));
        // add to the client context
        ResteasyContext.pushContext(Long.class, 42l);
    }
    collector.collect(requestContext.getMethod());
}
 
Example 23
Source Project: sofa-rpc   Source 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 24
Source Project: robozonky   Source File: AbstractCommonFilterTest.java    License: Apache License 2.0 5 votes vote down vote up
protected static ClientRequestContext mockClientRequestContext() throws URISyntaxException {
    final MultivaluedMap<String, Object> map = mock(MultivaluedMap.class);
    final ClientRequestContext ctx = mock(ClientRequestContext.class);
    when(ctx.getHeaders()).thenReturn(map);
    when(ctx.getUri()).thenReturn(new URI("http://localhost"));
    return ctx;
}
 
Example 25
Source Project: cxf   Source File: ReturnAllOutboundHeadersFilter.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void filter(ClientRequestContext requestContext) throws IOException {
    StringBuilder sb = new StringBuilder();
    requestContext.getStringHeaders().forEach((k, v) -> {
        sb.append(k).append('=').append(v.stream().collect(Collectors.joining(",")))
            .append(System.lineSeparator());
    });
    requestContext.abortWith(Response.ok(sb.toString()).build());
}
 
Example 26
Source Project: keycloak   Source File: BearerAuthFilter.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void filter(ClientRequestContext requestContext) throws IOException {
    String authHeader = (tokenManager != null ? tokenManager.getAccessTokenString() : tokenString);
    if (!authHeader.startsWith(AUTH_HEADER_PREFIX)) {
        authHeader = AUTH_HEADER_PREFIX + authHeader;
    }
    requestContext.getHeaders().add(HttpHeaders.AUTHORIZATION, authHeader);
}
 
Example 27
private void logResponse(ClientRequestContext request, ClientResponseContext response) {
    LOG.info("{} {}: {} {}",
            request.getMethod(),
            request.getUri(),
            response.getStatus(),
            response.getStatusInfo().getReasonPhrase());
}
 
Example 28
Source Project: ats-framework   Source File: RestClient.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void filter( ClientRequestContext context ) throws IOException {

    if (debugLevel == RESTDebugLevel.NONE || debugLevel == RESTDebugLevel.TARGET_URI
        || isApacheConnectorProviderInUse()) {
        return;
    }

    MultivaluedMap<String, Object> reqHeaders = context.getHeaders();
    StringBuilder requestMessage = new StringBuilder();
    requestMessage.append("Sending the following request: \n");
    if ( (debugLevel & RESTDebugLevel.HEADERS) == RESTDebugLevel.HEADERS) {
        requestMessage.append(context.getMethod() + " " + context.getUri() + " \n");

        for (Entry<String, List<Object>> reqHeaderEntry : reqHeaders.entrySet()) {
            requestMessage.append(reqHeaderEntry.getKey() + ": "
                                  + Arrays.toString(reqHeaderEntry.getValue().toArray()) + " \n");
        }
    }
    if ( (debugLevel & RESTDebugLevel.BODY) == RESTDebugLevel.BODY && context.hasEntity()) {
        // log request body
        Object entity = context.getEntity();
        if (entity instanceof Form) {
            requestMessage.append("Body: " + ((Form) entity).asMap());
        } else {
            requestMessage.append("Body: " + entity.toString());
        }
    }
    log.info(requestMessage);
}
 
Example 29
Source Project: docker-java   Source File: LoggingFilter.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void filter(final ClientRequestContext requestContext, final ClientResponseContext responseContext)
        throws IOException {
    final long id = aid.incrementAndGet();
    final StringBuilder b = new StringBuilder();

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

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

    log(b);
}
 
Example 30
Source Project: opencensus-java   Source File: JaxrsClientFilterTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testRequestFilter() throws Exception {
  URI uri = URI.create("https://mydomain/myresource");
  ClientRequestContext requestContext = mock(ClientRequestContext.class);
  when(requestContext.getUri()).thenReturn(uri);
  filter.filter(requestContext);
  verify(requestContext).getUri();
}
 
Example 31
Source Project: java-jaxrs   Source File: ClientSpanDecorator.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void decorateRequest(ClientRequestContext requestContext, Span span) {
    Tags.COMPONENT.set(span, "jaxrs");
    Tags.PEER_HOSTNAME.set(span, requestContext.getUri().getHost());
    Tags.PEER_PORT.set(span, requestContext.getUri().getPort());

    Tags.HTTP_METHOD.set(span, requestContext.getMethod());

    String url = URIUtils.url(requestContext.getUri());
    if (url != null) {
        Tags.HTTP_URL.set(span, url);
    }
}
 
Example 32
@Override
public void filter(ClientRequestContext ctx) throws IOException {
    String contentType = ctx.getHeaderString(HttpHeaders.CONTENT_TYPE);
    String accept = ctx.getHeaderString(HttpHeaders.ACCEPT);
    ctx.abortWith(Response.ok()
                          .header("Sent-Accept", accept)
                          .header("Sent-ContentType", contentType)
                          .build());

}
 
Example 33
Source Project: docker-java   Source File: SelectiveLoggingFilter.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void filter(ClientRequestContext context) throws IOException {
    // Unless the content type is in the list of those we want to ellide, then just have
    // our super-class handle things.
    Object contentType = context.getHeaders().getFirst(HttpHeaders.CONTENT_TYPE);
    if (contentType == null || !SKIPPED_CONTENT.contains(contentType.toString())) {
        super.filter(context);
    }
}
 
Example 34
Source Project: jersey-hmac-auth   Source File: HmacClientFilter.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void filter(ClientRequestContext clientRequestContext) throws IOException {
    ClientRequest request = (ClientRequest) clientRequestContext;
    // Modify the request to include security credentials if appropriate
    if (shouldEncode(request)) {
        requestEncoder.encode(request);
    }
}
 
Example 35
Source Project: cxf   Source 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 36
Source Project: microprofile-rest-client   Source File: BeanParamFilter.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void filter(ClientRequestContext clientRequestContext) throws IOException {
    String body = (String)clientRequestContext.getEntity();
    String query = clientRequestContext.getUri().getQuery();
    Cookie cookie = clientRequestContext.getCookies().get("cookie");
    String cookieValue = cookie==null?"null":cookie.getValue();
    String header = clientRequestContext.getHeaderString("MyHeader");
    clientRequestContext.abortWith(Response.ok(query + " " + cookieValue + " " + header + " " + body).build());
}
 
Example 37
Source Project: docker-java   Source File: FollowRedirectsFilter.java    License: 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 38
Source Project: cxf   Source File: ClientRequestFilterTest.java    License: Apache License 2.0 5 votes vote down vote up
/** {@inheritDoc}*/
@Override
public void filter(ClientRequestContext context) throws IOException {
    Object o = context.getHeaders().getFirst("MyHeader");
    Response r = (o instanceof String) ? Response.ok(o).build() : Response.serverError().build();
    context.abortWith(r);
}
 
Example 39
Source Project: robozonky   Source File: RoboZonkyFilter.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void filter(final ClientRequestContext clientRequestContext) {
    requestHeaders.forEach((k, v) -> clientRequestContext.getHeaders()
        .putSingle(k, v));
    clientRequestContext.setUri(rebuild(clientRequestContext.getUri()));
    logger.trace("Request {} {}.", clientRequestContext.getMethod(), clientRequestContext.getUri());
}
 
Example 40
Source Project: dubbo-2.6.5   Source File: LoggingFilter.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public void filter(ClientRequestContext context) throws IOException {
    logHttpHeaders(context.getStringHeaders());
}