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 Project: etcd-viewer   Author: nikfoundas   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   Author: sofastack   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   Author: apache   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   Author: apache   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   Author: keycloak   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   Author: GluuFederation   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   Author: yunhaibin   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   Author: docker-java   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   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 #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: microprofile-rest-client   Author: eclipse   File: InvokedMethodRequestFilter.java    License: 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 #12
Source Project: ameba   Author: icode   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   Author: hutai123   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   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 #15
Source Project: robozonky   Author: RoboZonky   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   Author: RoboZonky   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   Author: IBM   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   Author: IBM   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
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 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   Author: apache   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   Author: apache   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   Author: quarkusio   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   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 #24
Source Project: robozonky   Author: RoboZonky   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   Author: apache   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   Author: keycloak   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
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 #28
Source Project: ats-framework   Author: Axway   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   Author: docker-java   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   Author: census-instrumentation   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();
}