javax.ws.rs.client.ClientResponseFilter Java Examples

The following examples show how to use javax.ws.rs.client.ClientResponseFilter. 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: RestClientProcessor.java    From quarkus with Apache License 2.0 6 votes vote down vote up
@BuildStep
@Record(ExecutionTime.STATIC_INIT)
void setup(BuildProducer<FeatureBuildItem> feature,
        BuildProducer<AdditionalBeanBuildItem> additionalBeans,
        BuildProducer<ReflectiveClassBuildItem> reflectiveClass,
        RestClientRecorder restClientRecorder) {

    feature.produce(new FeatureBuildItem(Feature.REST_CLIENT));

    restClientRecorder.setRestClientBuilderResolver();

    additionalBeans.produce(new AdditionalBeanBuildItem(RestClient.class));

    reflectiveClass.produce(new ReflectiveClassBuildItem(false, false,
            DefaultResponseExceptionMapper.class.getName(),
            AsyncInterceptorRxInvokerProvider.class.getName(),
            ResteasyProviderFactoryImpl.class.getName(),
            ProxyBuilderImpl.class.getName(),
            ClientRequestFilter[].class.getName(),
            ClientResponseFilter[].class.getName(),
            javax.ws.rs.ext.ReaderInterceptor[].class.getName()));

    reflectiveClass.produce(new ReflectiveClassBuildItem(true, false,
            ResteasyClientBuilder.class.getName()));
}
 
Example #2
Source File: MetadataCommand.java    From syndesis with Apache License 2.0 6 votes vote down vote up
protected Client createClient() {

        return ClientBuilder.newClient().register((ClientResponseFilter) (requestContext, responseContext) -> {
            if (responseContext.getStatusInfo().getFamily() == Family.SERVER_ERROR
                && MediaType.APPLICATION_JSON.equals(responseContext.getHeaderString(HttpHeaders.CONTENT_TYPE))) {
                final RestError error = JsonUtils.reader().forType(RestError.class).readValue(responseContext.getEntityStream());

                throw new SyndesisRestException(
                    error.getDeveloperMsg(),
                    error.getUserMsg(),
                    error.getUserMsgDetail(),
                    error.getErrorCode()
                );
            }
        });
    }
 
Example #3
Source File: AdditionalRegistrationTest.java    From microprofile-rest-client with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldRegisterAMultiTypedProviderInstanceWithPriorities() {
    MultiTypedProvider provider = new MultiTypedProvider();
    Map<Class<?>, Integer> priorities = new HashMap<>();
    priorities.put(ClientRequestFilter.class, 500);
    priorities.put(ClientResponseFilter.class, 501);
    priorities.put(MessageBodyReader.class, 502);
    priorities.put(MessageBodyWriter.class, 503);
    priorities.put(ReaderInterceptor.class, 504);
    priorities.put(WriterInterceptor.class, 505);
    priorities.put(ResponseExceptionMapper.class, 506);
    priorities.put(ParamConverterProvider.class, 507);
    RestClientBuilder builder = RestClientBuilder.newBuilder().register(provider, priorities);
    Configuration configuration = builder.getConfiguration();
    assertTrue(configuration.isRegistered(MultiTypedProvider.class), MultiTypedProvider.class + " should be registered");
    assertTrue(configuration.isRegistered(provider), MultiTypedProvider.class + " should be registered");
    Map<Class<?>, Integer> contracts = configuration.getContracts(MultiTypedProvider.class);
    assertEquals(contracts.size(), priorities.size(),
        "There should be "+priorities.size()+" provider types registered");
    for(Map.Entry<Class<?>, Integer> priority : priorities.entrySet()) {
        Integer contractPriority = contracts.get(priority.getKey());
        assertEquals(contractPriority, priority.getValue(), "The priority for "+priority.getKey()+" should be "+priority.getValue());
    }
}
 
Example #4
Source File: AdditionalRegistrationTest.java    From microprofile-rest-client with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldRegisterAMultiTypedProviderClassWithPriorities() {
    Map<Class<?>, Integer> priorities = new HashMap<>();
    priorities.put(ClientRequestFilter.class, 500);
    priorities.put(ClientResponseFilter.class, 501);
    priorities.put(MessageBodyReader.class, 502);
    priorities.put(MessageBodyWriter.class, 503);
    priorities.put(ReaderInterceptor.class, 504);
    priorities.put(WriterInterceptor.class, 505);
    priorities.put(ResponseExceptionMapper.class, 506);
    priorities.put(ParamConverterProvider.class, 507);
    RestClientBuilder builder = RestClientBuilder.newBuilder().register(MultiTypedProvider.class, priorities);
    Configuration configuration = builder.getConfiguration();
    assertTrue(configuration.isRegistered(MultiTypedProvider.class), MultiTypedProvider.class + " should be registered");
    Map<Class<?>, Integer> contracts = configuration.getContracts(MultiTypedProvider.class);
    assertEquals(contracts.size(), priorities.size(),
        "There should be "+priorities.size()+" provider types registered");
    for(Map.Entry<Class<?>, Integer> priority : priorities.entrySet()) {
        Integer contractPriority = contracts.get(priority.getKey());
        assertEquals(contractPriority, priority.getValue(), "The priority for "+priority.getKey()+" should be "+priority.getValue());
    }
}
 
Example #5
Source File: JAXRS20ClientServerBookTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Test
public void testClientFiltersLocalResponseLambdas() {
    String address = "http://localhost:" + PORT + "/bookstores";
    WebClient wc = WebClient.create(address, Arrays.asList(
        (ClientRequestFilter) ctx -> {
            ctx.abortWith(Response.status(201).entity(ctx.getEntity()).type(MediaType.TEXT_XML_TYPE).build());
        },
        (ClientResponseFilter) (reqContext, respContext) -> {
            MultivaluedMap<String, String> headers = respContext.getHeaders();
            headers.putSingle(HttpHeaders.LOCATION, "http://localhost/redirect");
        }));
    Book theBook = new Book("Echo", 123L);
    Response r = wc.post(theBook);
    assertEquals(201, r.getStatus());
    assertEquals("http://localhost/redirect", r.getHeaderString(HttpHeaders.LOCATION));
    Book responseBook = r.readEntity(Book.class);
    assertSame(theBook, responseBook);
}
 
Example #6
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 #7
Source File: OAuthResource.java    From clouditor with Apache License 2.0 5 votes vote down vote up
private TokenResponse retrieveAccessToken(String code) {
  var tokenUrl = this.engine.getOAuthTokenUrl();

  LOGGER.info("Trying to retrieve access token from {}", tokenUrl);

  var uri =
      UriBuilder.fromUri(tokenUrl)
          .queryParam("grant_type", "authorization_code")
          .queryParam("code", code)
          .build();

  var client =
      ClientBuilder.newClient()
          .register(
              (ClientRequestFilter)
                  requestContext -> {
                    var headers = requestContext.getHeaders();
                    headers.add(
                        "Authorization",
                        "Basic "
                            + Base64.getEncoder()
                                .encodeToString(
                                    (this.engine.getOAuthClientId()
                                            + ":"
                                            + this.engine.getOAuthClientSecret())
                                        .getBytes()));
                  })
          .register(
              (ClientResponseFilter)
                  (requestContext, responseContext) -> {
                    // stupid workaround because some oauth servers incorrectly sends two
                    // Content-Type
                    // headers! fix it!
                    var contentType = responseContext.getHeaders().getFirst("Content-Type");
                    responseContext.getHeaders().putSingle("Content-Type", contentType);
                  });

  return client.target(uri).request().post(null, TokenResponse.class);
}
 
Example #8
Source File: ClientProviderFactory.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Override
protected void setProviders(boolean custom, boolean busGlobal, Object... providers) {
    List<ProviderInfo<? extends Object>> theProviders =
        prepareProviders(custom, busGlobal, providers, null);
    super.setCommonProviders(theProviders);
    for (ProviderInfo<? extends Object> provider : theProviders) {
        Class<?> providerCls = ClassHelper.getRealClass(getBus(), provider.getProvider());
        if (providerCls == Object.class) {
            // If the provider is a lambda, ClassHelper.getRealClass returns Object.class
            providerCls = provider.getProvider().getClass();
        }
        if (filterContractSupported(provider, providerCls, ClientRequestFilter.class)) {
            addProviderToList(clientRequestFilters, provider);
        }

        if (filterContractSupported(provider, providerCls, ClientResponseFilter.class)) {
            addProviderToList(clientResponseFilters, provider);
        }

        if (ResponseExceptionMapper.class.isAssignableFrom(providerCls)) {
            addProviderToList(responseExceptionMappers, provider);
        }

        if (RxInvokerProvider.class.isAssignableFrom(providerCls)) {
            this.rxInvokerProvider = RxInvokerProvider.class.cast(provider.getProvider());
        }
    }
    Collections.sort(clientRequestFilters,
                     new BindingPriorityComparator(ClientRequestFilter.class, true));
    Collections.sort(clientResponseFilters,
                     new BindingPriorityComparator(ClientResponseFilter.class, false));

    injectContextProxies(responseExceptionMappers, clientRequestFilters, clientResponseFilters);
}
 
Example #9
Source File: MicroProfileClientFactoryBean.java    From cxf with Apache License 2.0 5 votes vote down vote up
private Set<Object> processProviders() {
    Set<Object> providers = new LinkedHashSet<>();
    for (Object provider : configuration.getInstances()) {
        Class<?> providerCls = ClassHelper.getRealClass(getBus(), provider);
        if (provider instanceof ClientRequestFilter || provider instanceof ClientResponseFilter) {
            FilterProviderInfo<Object> filter = new FilterProviderInfo<>(providerCls, providerCls,
                    provider, getBus(), configuration.getContracts(providerCls));
            providers.add(filter);
        } else {
            providers.add(provider);
        }
    }
    return providers;
}
 
Example #10
Source File: ConfigurationImplTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testClientFilterContractsOnServerFeatureIsRejected() {
    FeatureContextImpl featureContext = new FeatureContextImpl();
    Configurable<FeatureContext> configurable = new ConfigurableImpl<>(featureContext, RuntimeType.SERVER);
    featureContext.setConfigurable(configurable);
    featureContext.register(TestFilter.class);
    Configuration config = configurable.getConfiguration();
    Map<Class<?>, Integer> contracts = config.getContracts(TestFilter.class);
    assertFalse(contracts.containsKey(ClientRequestFilter.class));
    assertFalse(contracts.containsKey(ClientResponseFilter.class));
    assertTrue(contracts.containsKey(ContainerRequestFilter.class));
    assertTrue(contracts.containsKey(ContainerResponseFilter.class));
}
 
Example #11
Source File: ConfigurationImplTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testClientFilterWithNestedInterfacesIsAccepted() {
    try (ConfigurableImpl<Client> configurable 
            = new ConfigurableImpl<>(createClientProxy(), RuntimeType.CLIENT)) {
        Configuration config = configurable.getConfiguration();
        configurable.register(NestedInterfaceTestFilter.class);
        Map<Class<?>, Integer> contracts = config.getContracts(NestedInterfaceTestFilter.class);
        assertTrue(contracts.containsKey(ClientRequestFilter.class));
        assertTrue(contracts.containsKey(ClientResponseFilter.class));
    }
}
 
Example #12
Source File: ConfigurationImplTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testServerFilterContractsOnClientIsRejected() {
    try (ConfigurableImpl<Client> configurable 
            = new ConfigurableImpl<>(createClientProxy(), RuntimeType.CLIENT)) {
        Configuration config = configurable.getConfiguration();
        configurable.register(TestFilter.class);
        Map<Class<?>, Integer> contracts = config.getContracts(TestFilter.class);
        assertTrue(contracts.containsKey(ClientRequestFilter.class));
        assertTrue(contracts.containsKey(ClientResponseFilter.class));
        assertFalse(contracts.containsKey(ContainerRequestFilter.class));
        assertFalse(contracts.containsKey(ContainerResponseFilter.class));
    }
}
 
Example #13
Source File: AdditionalRegistrationTest.java    From microprofile-rest-client with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldRegisterAMultiTypedProviderClass() {
    Class<?>[] providerTypes = {ClientRequestFilter.class, ClientResponseFilter.class,
        MessageBodyReader.class, MessageBodyWriter.class, ReaderInterceptor.class, WriterInterceptor.class,
        ResponseExceptionMapper.class, ParamConverterProvider.class};
    RestClientBuilder builder = RestClientBuilder.newBuilder().register(MultiTypedProvider.class, providerTypes);
    Configuration configuration = builder.getConfiguration();
    assertTrue(configuration.isRegistered(MultiTypedProvider.class), MultiTypedProvider.class + " should be registered");
    assertEquals(configuration.getContracts(MultiTypedProvider.class).size(), providerTypes.length,
        "There should be "+providerTypes.length+" provider types registered");
}
 
Example #14
Source File: AdditionalRegistrationTest.java    From microprofile-rest-client with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldRegisterAMultiTypedProviderInstance() {
    MultiTypedProvider provider = new MultiTypedProvider();
    Class<?>[] providerTypes = {ClientRequestFilter.class, ClientResponseFilter.class,
        MessageBodyReader.class, MessageBodyWriter.class, ReaderInterceptor.class, WriterInterceptor.class,
        ResponseExceptionMapper.class, ParamConverterProvider.class};
    RestClientBuilder builder = RestClientBuilder.newBuilder().register(provider, providerTypes);
    Configuration configuration = builder.getConfiguration();
    assertTrue(configuration.isRegistered(MultiTypedProvider.class), MultiTypedProvider.class + " should be registered");
    assertTrue(configuration.isRegistered(provider), MultiTypedProvider.class + " should be registered");
    assertEquals(configuration.getContracts(MultiTypedProvider.class).size(), providerTypes.length,
        "There should be "+providerTypes.length+" provider types registered");
}
 
Example #15
Source File: JerseyDockerHttpClient.java    From docker-java with Apache License 2.0 4 votes vote down vote up
public Builder clientResponseFilters(ClientResponseFilter[] value) {
    this.clientResponseFilters = value;
    return this;
}
 
Example #16
Source File: JerseyDockerCmdExecFactory.java    From docker-java with Apache License 2.0 4 votes vote down vote up
public JerseyDockerCmdExecFactory withClientResponseFilters(ClientResponseFilter... clientResponseFilter) {
    clientBuilder = clientBuilder.clientResponseFilters(clientResponseFilter);
    return this;
}
 
Example #17
Source File: JaxRSClientDistributionProvider.java    From JaxRSProviders with Apache License 2.0 4 votes vote down vote up
protected void unbindClientResponseFilter(ClientResponseFilter instance) {
	this.removeJaxComponent(instance);
}
 
Example #18
Source File: JaxRSClientDistributionProvider.java    From JaxRSProviders with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("rawtypes")
protected void bindClientResponseFilter(ClientResponseFilter instance, Map serviceProps) {
	this.bindJaxComponent(instance, serviceProps);
}
 
Example #19
Source File: ClientProviderFactory.java    From cxf with Apache License 2.0 4 votes vote down vote up
public List<ProviderInfo<ClientResponseFilter>> getClientResponseFilters() {
    return Collections.unmodifiableList(clientResponseFilters);
}