javax.ws.rs.client.ClientRequestContext Java Examples

The following examples show how to use javax.ws.rs.client.ClientRequestContext. 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: LoggingFilter.java    From docker-java with 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 #2
Source File: RpcContextFilter.java    From dubbox with 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 #3
Source File: JAXRS20ClientServerBookTest.java    From cxf with 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 File: EtcdV2ProxyImpl.java    From etcd-viewer with 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 #5
Source File: TraceClientRequestFilter.java    From sofa-rpc with 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 #6
Source File: LoggingFilter.java    From ameba with 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 #7
Source File: InvokedMethodRequestFilter.java    From microprofile-rest-client with Apache License 2.0 6 votes vote down vote up
@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 #8
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 #9
Source File: JAXRS20ClientServerBookTest.java    From cxf with 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 #10
Source File: BearerAuthFilter.java    From keycloak with 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 #11
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 #12
Source File: AuthorizationInjectionFilter.java    From SCIM-Client with 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 #13
Source File: RpcContextFilter.java    From dubbox-hystrix with 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 File: RoboZonkyFilter.java    From robozonky with 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 #15
Source File: NewRelicClientInterceptor.java    From newrelic-alerts-configurator with 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 #16
Source File: FHIRBasicAuthenticator.java    From FHIR with 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 #17
Source File: TraceeClientFilter.java    From tracee with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * 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 #18
Source File: FHIRBasicAuthenticator.java    From FHIR with 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
Source File: RestClient.java    From ats-framework with 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 #20
Source File: LoggingFilter.java    From docker-java with 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 #21
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 #22
Source File: HmacClientFilter.java    From jersey-hmac-auth with 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 #23
Source File: SelectiveLoggingFilter.java    From docker-java with 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 #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: AbstractCommonFilterTest.java    From robozonky with 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 #26
Source File: AuthenticationFilterTest.java    From robozonky with 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 #27
Source File: JaxrsClientFilterTest.java    From opencensus-java with 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 #28
Source File: ProducesConsumesFilter.java    From microprofile-rest-client with Apache License 2.0 5 votes vote down vote up
@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 #29
Source File: ClientSpanDecorator.java    From java-jaxrs with 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 #30
Source File: ClientRequestFilterTest.java    From cxf with 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);
}