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

The following are top voted examples for showing how to use javax.ws.rs.client.ClientRequestContext. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: ameba   File: LoggingFilter.java   Source Code and License 7 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 2
Project: keycloak-jaxrs-client-authfilter   File: BearerAuthFilter.java   Source Code and License 6 votes vote down vote up
@Override
public void filter( final ClientRequestContext requestContext, final ClientResponseContext responseContext )
  throws IOException
{
  if ( Response.Status.UNAUTHORIZED.getStatusCode() == responseContext.getStatus() )
  {
    final List<Object> headers = requestContext.getHeaders().get( HttpHeaders.AUTHORIZATION );
    if ( null == headers )
    {
      return;
    }
    for ( final Object header : headers )
    {
      if ( header instanceof String )
      {
        final String headerValue = (String) header;
        if ( headerValue.startsWith( AUTH_HEADER_PREFIX ) )
        {
          final String token = headerValue.substring( AUTH_HEADER_PREFIX.length() );
          _keycloak.invalidate( token );
        }
      }
    }
  }
}
 
Example 3
Project: Mastering-Java-EE-Development-with-WildFly   File: MyClientRequestFilter.java   Source Code and License 6 votes vote down vote up
@Override
public void filter(ClientRequestContext requestContext) throws IOException {
	logger.info("getAcceptableLanguages : " + requestContext.getAcceptableLanguages());
	logger.info("getClient : " + requestContext.getClient());
	logger.info("getConfiguration : " + requestContext.getConfiguration());
	logger.info("getCookies : " + requestContext.getCookies());
	logger.info("getDate : " + requestContext.getDate());
	logger.info("getEntity : " + requestContext.getEntity());
	logger.info("getEntityAnnotations : " + requestContext.getEntityAnnotations());
	logger.info("getEntityClass : " + requestContext.getEntityClass());
	logger.info("getEntityStream : " + requestContext.getEntityStream());
	logger.info("getEntityType : " + requestContext.getEntityType());
	logger.info("getHeaders : " + requestContext.getHeaders());
	logger.info("getLanguage : " + requestContext.getLanguage());
	logger.info("getMediaType : " + requestContext.getMediaType());
	logger.info("getMethod : " + requestContext.getMethod());
	logger.info("getPropertyNames : " + requestContext.getPropertyNames());
	logger.info("getStringHeaders : " + requestContext.getStringHeaders());
	logger.info("getUri : " + requestContext.getUri());
	requestContext.getHeaders().add(CONTENT_TYPE_STRING, TEXT_HTML);
}
 
Example 4
Project: Mastering-Java-EE-Development-with-WildFly   File: MyClientResponseFilter.java   Source Code and License 6 votes vote down vote up
@Override
public void filter(ClientRequestContext requestContext, ClientResponseContext responseContext) throws IOException {
	logger.info("getAllowedMethods : " + responseContext.getAllowedMethods());
	logger.info("getCookies : " + responseContext.getCookies());
	logger.info("getDate : " + responseContext.getDate());
	logger.info("getEntityStream : " + responseContext.getEntityStream());
	logger.info("getEntityTag : " + responseContext.getEntityTag());
	logger.info("getHeaders : " + responseContext.getHeaders());
	logger.info("getLanguage : " + responseContext.getLanguage());
	logger.info("getLastModified : " + responseContext.getLastModified());
	logger.info("getLength : " + responseContext.getLength());
	logger.info("getLinks : " + responseContext.getLinks());
	logger.info("getLocation : " + responseContext.getLocation());
	logger.info("getMediaType : " + responseContext.getMediaType());
	logger.info("getStatus : " + responseContext.getStatus());
	logger.info("getStatusInfo : " + responseContext.getStatusInfo());
	responseContext.getHeaders().putSingle(CONTENT_TYPE_STRING,
			requestContext.getHeaderString(CONTENT_TYPE_STRING));
}
 
Example 5
Project: Mastering-Java-EE-Development-with-WildFly   File: OtherClientResponseFilter.java   Source Code and License 6 votes vote down vote up
@Override
public void filter(ClientRequestContext requestContext, ClientResponseContext responseContext) throws IOException {
	logger.info("getAllowedMethods : " + responseContext.getAllowedMethods());
	logger.info("getCookies : " + responseContext.getCookies());
	logger.info("getDate : " + responseContext.getDate());
	logger.info("getEntityStream : " + responseContext.getEntityStream());
	logger.info("getEntityTag : " + responseContext.getEntityTag());
	logger.info("getHeaders : " + responseContext.getHeaders());
	logger.info("getLanguage : " + responseContext.getLanguage());
	logger.info("getLastModified : " + responseContext.getLastModified());
	logger.info("getLength : " + responseContext.getLength());
	logger.info("getLinks : " + responseContext.getLinks());
	logger.info("getLocation : " + responseContext.getLocation());
	logger.info("getMediaType : " + responseContext.getMediaType());
	logger.info("getStatus : " + responseContext.getStatus());
	logger.info("getStatusInfo : " + responseContext.getStatusInfo());
}
 
Example 6
Project: Mastering-Java-EE-Development-with-WildFly   File: OtherClientRequestFilter.java   Source Code and License 6 votes vote down vote up
@Override
public void filter(ClientRequestContext requestContext) throws IOException {
	logger.info("getAcceptableLanguages : " + requestContext.getAcceptableLanguages());
	logger.info("getClient : " + requestContext.getClient());
	logger.info("getConfiguration : " + requestContext.getConfiguration());
	logger.info("getCookies : " + requestContext.getCookies());
	logger.info("getDate : " + requestContext.getDate());
	logger.info("getEntity : " + requestContext.getEntity());
	logger.info("getEntityAnnotations : " + requestContext.getEntityAnnotations());
	logger.info("getEntityClass : " + requestContext.getEntityClass());
	logger.info("getEntityStream : " + requestContext.getEntityStream());
	logger.info("getEntityType : " + requestContext.getEntityType());
	logger.info("getHeaders : " + requestContext.getHeaders());
	logger.info("getLanguage : " + requestContext.getLanguage());
	logger.info("getMediaType : " + requestContext.getMediaType());
	logger.info("getMethod : " + requestContext.getMethod());
	logger.info("getPropertyNames : " + requestContext.getPropertyNames());
	logger.info("getStringHeaders : " + requestContext.getStringHeaders());
	logger.info("getUri : " + requestContext.getUri());
}
 
Example 7
Project: redhat-sso   File: LoggingFilter.java   Source Code and License 6 votes vote down vote up
@Override
public void filter(ClientRequestContext clientRequestContext) throws IOException {
    String method = clientRequestContext.getMethod();
    URI uri = clientRequestContext.getUri();
    MultivaluedMap<String, Object> headers = clientRequestContext.getHeaders();
    System.out.printf("Sending %s to: %s\n", method, uri);
    System.out.printf("Headers:\n");
    for(String key : headers.keySet()) {
        System.out.printf("  %s: %s\n", key, headers.getFirst(key));
    }
    if(clientRequestContext.hasEntity()) {
        final OutputStream stream = new LoggingStream(clientRequestContext.getEntityStream());
        clientRequestContext.setEntityStream(stream);
        clientRequestContext.setProperty("client.LoggingStream", stream);
    }
}
 
Example 8
Project: dubbo2   File: RpcContextFilter.java   Source Code and License 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 9
Project: SpanEE   File: SpanEEClientRequestFilter.java   Source Code and License 6 votes vote down vote up
@Override
public void filter(ClientRequestContext requestContext, ClientResponseContext responseContext) throws IOException {
    System.out.println("Response = " + requestContext + " " + responseContext);
    Long start = concurrentRequests.get(requestContext);
    concurrentRequests.remove(requestContext);
    long duration = (System.nanoTime() - start);
    System.out.println("Duration: " + duration);
    URI uri = requestContext.getUri();

    String ipv4 = extractIpAddress(uri);
    System.out.println("ipv4 = " + ipv4);
    String serviceName = extractServiceName(uri);
    System.out.println("serviceName = " + serviceName);
    String spanName = uri.getPath();
    System.out.println("spanName = " + spanName);
    String traceId = extractTraceId(requestContext).orElse("--no spanid--");
    Boolean spanExists = Optional.ofNullable(requestContext.getProperty(SPAN_EXISTED)).
            map((o) -> (boolean) o).
            orElse(false);
    if (spanExists) {
        this.tracEE.saveChildSpan(traceId, spanName, serviceName, ipv4, duration);
    } else {
        this.tracEE.saveParentSpan(spanName, serviceName, ipv4, duration);
    }
}
 
Example 10
Project: dubbox-hystrix   File: RpcContextFilter.java   Source Code and License 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 11
Project: servicebuilder   File: ClientErrorResponseFilter.java   Source Code and License 6 votes vote down vote up
@Override
public void filter(ClientRequestContext requestContext, ClientResponseContext responseContext)
        throws IOException
{
    // for non-200 response, deal with the custom error messages
    if (! Response.Status.Family.SUCCESSFUL.equals(responseContext.getStatusInfo().getFamily())) {
        MetaData metaData = MetaData.builder()
                .httpRequestMetaData(getRequestMetaData(requestContext))
                .httpResponseMetaData(getResponseMetaData(responseContext))
                .gotAnswer(true)
                .targetName(serviceDefinition.getName())
                .build();
        if (Response.Status.NOT_FOUND.getStatusCode() == responseContext.getStatus()) {
            throw new ExternalResourceNotFoundException(metaData);
        }
        throw new ExternalResourceException(metaData);
    }
}
 
Example 12
Project: dubbocloud   File: RpcContextFilter.java   Source Code and License 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 13
Project: dubbos   File: RpcContextFilter.java   Source Code and License 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
Project: robozonky   File: RoboZonkyFilter.java   Source Code and License 6 votes vote down vote up
@Override
public void filter(final ClientRequestContext clientRequestContext,
                   final ClientResponseContext clientResponseContext) throws IOException {
    this.logger.debug("HTTP {} Response from {}: {} {}.", clientRequestContext.getMethod(),
                      clientRequestContext.getUri(), clientResponseContext.getStatus(),
                      clientResponseContext.getStatusInfo().getReasonPhrase());
    final String responseEntity = getResponseEntity(clientResponseContext);
    if (clientResponseContext.getStatus() == 400) {
        if (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().size() > 0)
            .collect(Collectors.toMap(Map.Entry::getKey, e -> e.getValue().get(0)));
}
 
Example 15
Project: robozonky   File: RoboZonkyFilterTest.java   Source Code and License 6 votes vote down vote up
@Test
public void response() throws IOException {
    final String key = UUID.randomUUID().toString();
    final String key2 = UUID.randomUUID().toString();
    final String value = UUID.randomUUID().toString();
    final MultivaluedMap<String, String> map = new MultivaluedMapImpl<>();
    map.add(key, value);
    map.addAll(key2, Collections.emptyList());
    final ClientRequestContext ctx = Mockito.mock(ClientRequestContext.class);
    final ClientResponseContext ctx2 = Mockito.mock(ClientResponseContext.class);
    Mockito.when(ctx2.getHeaders()).thenReturn(map);
    Mockito.when(ctx2.getStatusInfo()).thenReturn(Mockito.mock(Response.StatusType.class));
    final RoboZonkyFilter filter = new RoboZonkyFilter();
    filter.filter(ctx, ctx2);
    SoftAssertions.assertSoftly(softly -> {
        softly.assertThat(filter.getLastResponseHeader(key)).contains(value);
        softly.assertThat(filter.getLastResponseHeader(key2)).isEmpty();
    });
}
 
Example 16
Project: camel-alma   File: AlmaResponseFilter.java   Source Code and License 6 votes vote down vote up
@Override
public void filter(ClientRequestContext requestContext, ClientResponseContext responseContext) throws IOException {
    if (LOG.isTraceEnabled()) {
        LOG.trace("Response status: {} {}", responseContext.getStatus(), responseContext.getStatusInfo().toString());
        LOG.trace("Response headers: {}", responseContext.getHeaders());

        InputStream stream = responseContext.getEntityStream();
        ByteArrayOutputStream result = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int length;
        while ((length = stream.read(buffer)) != -1) {
            result.write(buffer, 0, length);
        }
        stream.close();
        LOG.trace("Response body: {}", result.toString("UTF-8"));

        responseContext.setEntityStream(new ByteArrayInputStream(result.toByteArray()));
    }
}
 
Example 17
Project: dubbox   File: RpcContextFilter.java   Source Code and License 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 18
Project: dubbo-rpc-rest   File: RpcContextFilter.java   Source Code and License 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 19
Project: java-jaxrs   File: ClientTracingFilter.java   Source Code and License 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 20
Project: xhub4j   File: XHubClientRequestFilter.java   Source Code and License 6 votes vote down vote up
@Override
public void filter(ClientRequestContext requestContext) throws IOException {
    if (token == null) {
        throw new IOException("cannot encode with a null token");
    }
    
    forceJerseyBuffering(requestContext);
    
    Consumer<byte[]> dataInterceptor = data -> {
        if (!requestContext.getHeaders().containsKey(header)) {
            String xhubHeaderValue = XHub.generateHeaderXHubToken(getEncoder(), getHash(), token, data);
            requestContext.getHeaders().putSingle(header, xhubHeaderValue);
        }
    };
    
    requestContext.setEntityStream(new ByteArrayInterceptingOutputStream(requestContext.getEntityStream(), dataInterceptor));
}
 
Example 21
Project: cloud-native-javaee   File: RibbonClientRequestFilter.java   Source Code and License 6 votes vote down vote up
@Override
public void filter(ClientRequestContext requestContext) throws IOException {
    // get the load balanced server info
    Server server = loadBalancer.chooseServer(null);
    String host = server.getHost();
    int port = server.getPort();

    URI uri = requestContext.getUri();
    URI lbUri;
    try {
        lbUri = new URI(uri.getScheme(), uri.getUserInfo(), host, port,
                uri.getPath(), uri.getQuery(), uri.getFragment());
    } catch (URISyntaxException e) {
        throw new IOException(e);
    }

    requestContext.setUri(lbUri);
}
 
Example 22
Project: fili   File: BardLoggingFilter.java   Source Code and License 6 votes vote down vote up
@Override
public void filter(ClientRequestContext request, ClientResponseContext response) throws IOException {
    StringBuilder debugMsgBuilder = new StringBuilder();

    debugMsgBuilder.append("ClientRequest: ").append(request.getMethod()).append("\t");
    debugMsgBuilder.append(request.getUri().toASCIIString()).append("\t");

    appendObjectHeaders(debugMsgBuilder, "> ", request.getHeaders().entrySet());
    appendStringHeaders(debugMsgBuilder, "< ", response.getHeaders().entrySet());

    debugMsgBuilder.append(response.getStatusInfo()).append(", length=").append(response.getLength()).append(" ");

    Long requestStartTime = (Long) request.getProperty(PROPERTY_NANOS);
    if (requestStartTime != null) {
        debugMsgBuilder
                .append((System.nanoTime() - requestStartTime) / MILLISECONDS_PER_NANOSECOND)
                .append(" ms\t");
    }

    LOG.debug(debugMsgBuilder.toString());
    RequestLog.stopTiming(CLIENT_TOTAL_TIMER);
}
 
Example 23
Project: jahhan   File: RpcContextFilter.java   Source Code and License 6 votes vote down vote up
@Override
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("=");
		String encode = URLEncoder.encode(entry.getValue(), "UTF-8");
		attachments.append(encode);
		requestContext.getHeaders().add(DUBBO_ATTACHMENT_HEADER, attachments.toString());
	}
}
 
Example 24
Project: Camel   File: LinkedInExceptionResponseFilter.java   Source Code and License 6 votes vote down vote up
@Override
public void filter(ClientRequestContext requestContext, ClientResponseContext responseContext) throws IOException {
    if (responseContext.getStatus() != Response.Status.OK.getStatusCode() && responseContext.hasEntity()) {
        try {
            final Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
            final Error error = (Error) unmarshaller.unmarshal(responseContext.getEntityStream());

            final Response.ResponseBuilder builder = Response.status(responseContext.getStatusInfo());
            builder.entity(error);
            // copy response headers
            for (Map.Entry<String, List<String>> header : responseContext.getHeaders().entrySet()) {
                builder.header(header.getKey(), header.getValue());
            }

            throw new LinkedInException(error, builder.build());
        } catch (JAXBException e) {
            // log and ignore
            LOG.warn("Unable to parse LinkedIn error: " + e.getMessage(), e);
        }
    }
}
 
Example 25
Project: hawkular-apm   File: HttpClientProducer.java   Source Code and License 6 votes vote down vote up
@Override
public void filter(ClientRequestContext clientRequestContext) throws IOException {
    final HttpClientRequest httpClientRequest = new HttpClientRequest() {
        @Override
        public void addHeader(String s, String s1) {
            clientRequestContext.getHeaders().add(s, s1);
        }

        @Override
        public URI getUri() {
            return clientRequestContext.getUri();
        }

        @Override
        public String getHttpMethod() {
            return clientRequestContext.getMethod();
        }
    };
    requestInterceptor.handle(new HttpClientRequestAdapter(httpClientRequest, spanNameProvider));
}
 
Example 26
Project: robots   File: FollowRedirectsFilter.java   Source Code and License 6 votes vote down vote up
private boolean isRedirectWithinLimits(ClientRequestContext requestContext, URI nextLocation) {

        final Set<URI> visitedLocations = getVisitedLocations(requestContext);

        if (visitedLocations.contains(nextLocation)) {
            log.warn("Detected redirect cycle: {} -> {}", visitedLocations, nextLocation);
            return false;
        }

        if (visitedLocations.size() > maxRedirectHops) {
            log.warn("Reached max hops ({}) following redirects: {}", maxRedirectHops, visitedLocations);
            return false;
        }

        return true;
    }
 
Example 27
Project: etcd-viewer   File: EtcdProxyImpl.java   Source Code and License 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 28
Project: wordpress-rest-api-java-client   File: WordPressClientFactory.java   Source Code and License 6 votes vote down vote up
public WordPressClientFactory withCredentials(String username, String password) {
    this.clientRequestFilter = new ClientRequestFilter() {
        private final String charset = StandardCharsets.UTF_8.name();

        @Override
        public void filter(ClientRequestContext requestContext) throws IOException {

            String token = String.format("%s:%s", username, password);

            String basicAuthHeader = null;

            try {
                basicAuthHeader = "BASIC " + DatatypeConverter.printBase64Binary(token.getBytes(charset));
            }
            catch (UnsupportedEncodingException ex) {
                throw new IllegalStateException("Cannot encode with " + charset, ex);
            }

            MultivaluedMap<String, Object> headers = requestContext.getHeaders();
            headers.add("Authorization", basicAuthHeader);

            logger.trace("Added BasicAuth filter with username {}", username);
        }
    };
    return this;
}
 
Example 29
Project: msf4j   File: MSF4JClientTracingFilter.java   Source Code and License 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 30
Project: LetUsGo-Server   File: RpcContextFilter.java   Source Code and License 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 31
Project: appverse-server   File: JWSJerseyFilter.java   Source Code and License 6 votes vote down vote up
/**
 * Check parameters on request Context
 * @param requestContext
 */
private void checkParams(ClientRequestContext requestContext){
    if (key==null) {
        Object keyObject = requestContext.getProperty(JWS_FILTER_KEY);
        if (keyObject == null) {
            requestContext.abortWith(
                    Response.status(Response.Status.BAD_REQUEST).entity("Error " + JWS_FILTER_KEY + " param is required")
                            .build()
            );
        }else if (keyObject instanceof RSAPrivateKey) {
            key = (RSAPrivateKey)keyObject;

       }

    }
}
 
Example 32
Project: appverse-server   File: JWSJerseyFilter.java   Source Code and License 6 votes vote down vote up
/**
 * Check parameters on request Context
 * @param requestContext
 */
private void checkParams(ClientRequestContext requestContext){
    if (key==null) {
        Object keyObject = requestContext.getProperty(JWS_FILTER_KEY);
        if (keyObject == null) {
            requestContext.abortWith(
                    Response.status(Response.Status.BAD_REQUEST).entity("Error " + JWS_FILTER_KEY + " param is required")
                            .build()
            );
        }else if (keyObject instanceof RSAPrivateKey) {
            key = (RSAPrivateKey)keyObject;

       }

    }
}
 
Example 33
Project: qds-sdk-java   File: ErrorResponseFilter.java   Source Code and License 6 votes vote down vote up
@Override
public void filter(final ClientRequestContext requestContext,
                   final ClientResponseContext responseContext) {
    try {
        // For non-200 response, log the custom error message.
        if (responseContext.getStatus() != Response.Status.OK.getStatusCode()) {
            if (responseContext.hasEntity()) {
                String error = CharStreams.toString(
                    new InputStreamReader(responseContext.getEntityStream(), Charsets.UTF_8));
                LOG.severe(error);
                System.err.println(error);
            }
        }
    } catch (Exception e) {
        // Silently pass. We don't want anything to fail because of this filter.
        LOG.warning("Error while checking response code: " + e.getMessage());
    }
}
 
Example 34
Project: ameba   File: LoggingFilter.java   Source Code and 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 35
Project: jive-sdk-java-jersey   File: DebugClientResponseFilter.java   Source Code and License 6 votes vote down vote up
private void logRequest(ClientRequestContext requestContext) throws IOException {

        Object requestBody = requestContext.getEntity();

        if (log.isTraceEnabled()) {
            StringBuffer sbuf = new StringBuffer("\nHeaders:");
            sbuf.append("\n--- BEGIN ---");
            MultivaluedMap<String,String> headers = requestContext.getStringHeaders();
            for (String key : headers.keySet()) {
                sbuf.append("\n").append(key).append("=").append(headers.get(key));
            } // end for key
            sbuf.append("\n--- END ---");
            log.trace(sbuf.toString());
            sbuf = null;
        } // end if

        if (MediaType.APPLICATION_JSON.equals(requestContext.getHeaderString(HttpHeaders.CONTENT_TYPE))) {
            log.debug("\n["+requestContext.getMethod()+"] : "+requestContext.getUri().toString()+"\n"+JiveSDKUtils.getJson(requestBody));
        } else {
            log.debug("\n["+requestContext.getMethod()+"] : "+requestContext.getUri().toString()+"\n"+requestBody);
        } // end if

    }
 
Example 36
Project: docker-java   File: LoggingFilter.java   Source Code and License 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 37
Project: docker-java   File: ResponseStatusExceptionFilter.java   Source Code and License 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 38
Project: spearal-jaxrs   File: SpearalClientRequestFilter.java   Source Code and License 6 votes vote down vote up
public void filter(ClientRequestContext requestContext) throws IOException {
	// Wrap entity to store property filters
	SpearalPropertyFilterBuilder clientPropertyFilterBuilder = (SpearalPropertyFilterBuilder)requestContext.getProperty(SpearalJaxrs.PROPERTY_FILTER_CLIENT);
	if (clientPropertyFilterBuilder != null)
		requestContext.setEntity(new SpearalEntity(requestContext.getEntity(), clientPropertyFilterBuilder));
	
	// Transmit server property filters as http header
	SpearalPropertyFilterBuilder serverPropertyFilterBuilder = (SpearalPropertyFilterBuilder)requestContext.getProperty(SpearalJaxrs.PROPERTY_FILTER_SERVER);
	if (serverPropertyFilterBuilder == null)
		return;
	
	SpearalFactory factory = SpearalJaxrs.locateFactory(configuration, providers);
	
	List<Object> serverPropertyFilterHeaders = new ArrayList<Object>(serverPropertyFilterBuilder.toHeaders(factory.getContext()));
	requestContext.getHeaders().put(Spearal.PROPERTY_FILTER_HEADER, serverPropertyFilterHeaders);
}
 
Example 39
Project: keycloak-jaxrs-client-authfilter   File: BearerAuthFilter.java   Source Code and License 5 votes vote down vote up
@Override
public void filter( final ClientRequestContext requestContext )
  throws IOException
{
  final String accessToken = _keycloak.getAccessTokenString();
  if ( null != accessToken )
  {
    requestContext.getHeaders().add( HttpHeaders.AUTHORIZATION, AUTH_HEADER_PREFIX + accessToken );
  }
}
 
Example 40
Project: keycloak-jaxrs-client-authfilter   File: BasicAuthFilter.java   Source Code and License 5 votes vote down vote up
@Override
public void filter( final ClientRequestContext requestContext )
  throws IOException
{
  final String pair = _username + ":" + _password;
  final String header = "Basic " + Base64.getEncoder().encodeToString( pair.getBytes() );
  requestContext.getHeaders().add( HttpHeaders.AUTHORIZATION, header );
}