javax.ws.rs.client.ClientRequestFilter Java Examples

The following examples show how to use javax.ws.rs.client.ClientRequestFilter. 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: quarkus   Author: quarkusio   File: RestClientProcessor.java    License: 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 Project: microprofile-rest-client   Author: eclipse   File: AdditionalRegistrationTest.java    License: 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 #3
Source Project: microprofile-rest-client   Author: eclipse   File: AdditionalRegistrationTest.java    License: 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 #4
Source Project: vespa   Author: vespa-engine   File: JerseyJaxRsClientFactory.java    License: Apache License 2.0 6 votes vote down vote up
public JerseyJaxRsClientFactory(SSLContext sslContext, HostnameVerifier hostnameVerifier, String userAgent) {
    /*
     * Configure client with some workarounds for HTTP/JAX-RS/Jersey issues. See:
     *   https://jersey.java.net/apidocs/latest/jersey/org/glassfish/jersey/client/ClientProperties.html#SUPPRESS_HTTP_COMPLIANCE_VALIDATION
     *   https://jersey.java.net/apidocs/latest/jersey/org/glassfish/jersey/client/HttpUrlConnectorProvider.html#SET_METHOD_WORKAROUND
     */
    ClientBuilder builder = ClientBuilder.newBuilder()
                                         .property(ClientProperties.SUPPRESS_HTTP_COMPLIANCE_VALIDATION, true) // Allow empty PUT. TODO: Fix API.
                                         .property(HttpUrlConnectorProvider.SET_METHOD_WORKAROUND, true) // Allow e.g. PATCH method.
                                         .property(ClientProperties.FOLLOW_REDIRECTS, true);
    if (sslContext != null) {
        builder.sslContext(sslContext);
    }
    if (hostnameVerifier != null) {
        builder.hostnameVerifier(hostnameVerifier);
    }
    if (userAgent != null) {
        builder.register((ClientRequestFilter) context -> context.getHeaders().put(HttpHeaders.USER_AGENT, Collections.singletonList(userAgent)));
    }
    this.client = builder.build();
}
 
Example #5
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 #6
Source Project: cxf   Author: apache   File: JAXRS20ClientServerBookTest.java    License: 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 #7
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 #8
Source Project: cxf   Author: apache   File: JAXRS20ClientServerBookTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testGetSetEntityStreamLambda() {
    String address = "http://localhost:" + PORT + "/bookstore/entityecho";
    String entity = "BOOKSTORE";

    Client client = ClientBuilder.newClient();
    client.register((ClientRequestFilter) context -> {
        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 #9
Source Project: keycloak   Author: keycloak   File: TwitterShowUserServlet.java    License: Apache License 2.0 6 votes vote down vote up
private TwitterOAuthResponse getTwitterOAuthResponse(final HttpServletRequest req) {
    ClientRequestFilter authFilter = new ClientRequestFilter() {
        @Override
        public void filter(ClientRequestContext requestContext) throws IOException {
            KeycloakSecurityContext securityContext = (KeycloakSecurityContext) req.getAttribute(KeycloakSecurityContext.class.getName());
            String accessToken = securityContext.getTokenString();

            requestContext.getHeaders().add(HttpHeaders.AUTHORIZATION, "Bearer " + accessToken);
        }
    };

    Client client = ClientBuilder.newBuilder().register(authFilter).build();
    WebTarget target = client.target(getIdentityProviderTokenUrl());

    return target.request().get().readEntity(TwitterOAuthResponse.class);
}
 
Example #10
Source Project: clouditor   Author: clouditor   File: OAuthResource.java    License: 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 #11
Source Project: component-runtime   Author: Talend   File: ClientSetup.java    License: Apache License 2.0 5 votes vote down vote up
@Produces
@ApplicationScoped
@Http(Http.Type.TALEND_COMPONENT_KIT)
public Client serverClient(@Http(Http.Type.TALEND_COMPONENT_KIT) final ExecutorService executor) {
    ClientBuilder builder = createClient(executor, serverKeystoreLocation, serverKeystoreType,
            serverKeystorePassword, serverTruststoreType, serverHostnames);
    if (serverToken.isPresent()) {
        final String token = serverToken.get();
        builder = builder
                .register((ClientRequestFilter) requestContext -> requestContext
                        .getHeaders()
                        .putSingle(HttpHeaders.AUTHORIZATION, token));
    }
    return builder.build();
}
 
Example #12
Source Project: microprofile-rest-client   Author: eclipse   File: AdditionalRegistrationTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void shouldRegisterInstanceWithPriority() {
    Integer priority = 1000;
    TestClientRequestFilter instance = new TestClientRequestFilter();
    RestClientBuilder builder = RestClientBuilder.newBuilder().register(instance, priority);
    Configuration configuration = builder.getConfiguration();
    assertTrue(configuration.isRegistered(TestClientRequestFilter.class), TestClientRequestFilter.class + " should be registered");
    assertTrue(configuration.isRegistered(instance), TestClientRequestFilter.class + " should be registered");
    Map<Class<?>, Integer> contracts = configuration.getContracts(TestClientRequestFilter.class);
    assertEquals(contracts.size(), 1, "There should be a registered contract for "+TestClientRequestFilter.class);
    assertEquals(contracts.get(ClientRequestFilter.class), priority, "The priority for "+TestClientRequestFilter.class+" should be 1000");
}
 
Example #13
Source Project: microprofile-rest-client   Author: eclipse   File: AdditionalRegistrationTest.java    License: 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 #14
Source Project: microprofile-rest-client   Author: eclipse   File: AdditionalRegistrationTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void shouldRegisterProvidersWithPriority() {
    Integer priority = 1000;
    RestClientBuilder builder = RestClientBuilder.newBuilder().register(TestClientRequestFilter.class, priority);
    Configuration configuration = builder.getConfiguration();
    assertTrue(configuration.isRegistered(TestClientRequestFilter.class), TestClientRequestFilter.class + " should be registered");
    Map<Class<?>, Integer> contracts = configuration.getContracts(TestClientRequestFilter.class);
    assertEquals(contracts.size(), 1, "There should be a registered contract for "+TestClientRequestFilter.class);
    assertEquals(contracts.get(ClientRequestFilter.class), priority, "The priority for "+TestClientRequestFilter.class+" should be 1000");
}
 
Example #15
Source Project: microprofile-rest-client   Author: eclipse   File: AdditionalRegistrationTest.java    License: 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 #16
Source Project: vespa   Author: vespa-engine   File: ConfigConvergenceChecker.java    License: Apache License 2.0 5 votes vote down vote up
private Client createClient(Duration timeout) {
    return clientBuilderFactory.newBuilder()
                        .register(
                                (ClientRequestFilter) ctx ->
                                        ctx.getHeaders().put(HttpHeaders.USER_AGENT, List.of("config-convergence-checker")))
                        .property(ClientProperties.CONNECT_TIMEOUT, (int) timeout.toMillis())
                        .property(ClientProperties.READ_TIMEOUT, (int) timeout.toMillis())
                        .build();
}
 
Example #17
Source Project: vespa   Author: vespa-engine   File: VespaJerseyJaxRsClientFactory.java    License: Apache License 2.0 5 votes vote down vote up
public VespaJerseyJaxRsClientFactory(String userAgent) {
    this.client = clientBuilder.newBuilder()
            .property(ClientProperties.SUPPRESS_HTTP_COMPLIANCE_VALIDATION, true) // Allow empty PUT
            .property(HttpUrlConnectorProvider.SET_METHOD_WORKAROUND, true) // Allow e.g. PATCH method.
            .property(ClientProperties.FOLLOW_REDIRECTS, true)
            .register((ClientRequestFilter) context -> context.getHeaders().put(HttpHeaders.USER_AGENT, List.of(userAgent)))
            .build();
}
 
Example #18
Source Project: cxf   Author: apache   File: ConfigurationImplTest.java    License: 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 #19
Source Project: cxf   Author: apache   File: ConfigurationImplTest.java    License: 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 #20
Source Project: cxf   Author: apache   File: ConfigurationImplTest.java    License: 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 #21
Source Project: cxf   Author: apache   File: MicroProfileClientFactoryBean.java    License: 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 #22
Source Project: cxf   Author: apache   File: ClientProviderFactory.java    License: 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 #23
Source Project: vespa   Author: vespa-engine   File: StateResource.java    License: Apache License 2.0 4 votes vote down vote up
private Client client() {
    return clientBuilderFactory.newBuilder()
                        .register((ClientRequestFilter) ctx -> ctx.getHeaders().put(HttpHeaders.USER_AGENT, List.of(USER_AGENT)))
                        .build();
}
 
Example #24
Source Project: azure-devops-intellij   Author: microsoft   File: RestClientHelper.java    License: MIT License 4 votes vote down vote up
public static ClientConfig getClientConfig(final ServerContext.Type type,
                                           final Credentials credentials,
                                           final String serverUri,
                                           final boolean includeProxySettings) {

    final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(AuthScope.ANY, credentials);

    final ConnectorProvider connectorProvider = new ApacheConnectorProvider();
    // custom json provider ignores new fields that aren't recognized
    final JacksonJsonProvider jacksonJsonProvider = new JacksonJaxbJsonProvider()
            .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

    final ClientConfig clientConfig = new ClientConfig(jacksonJsonProvider).connectorProvider(connectorProvider);
    clientConfig.property(ApacheClientProperties.CREDENTIALS_PROVIDER, credentialsProvider);
    clientConfig.property(ClientProperties.REQUEST_ENTITY_PROCESSING, RequestEntityProcessing.BUFFERED);

    // For TFS OnPrem we only support NTLM authentication right now. Since 2016 servers support Basic as well,
    // we need to let the server and client negotiate the protocol instead of preemptively assuming Basic.
    // TODO: This prevents PATs from being used OnPrem. We need to fix this soon to support PATs onPrem.
    clientConfig.property(ApacheClientProperties.PREEMPTIVE_BASIC_AUTHENTICATION, type != ServerContext.Type.TFS);

    //Define a local HTTP proxy
    if (includeProxySettings) {
        final HttpProxyService proxyService = PluginServiceProvider.getInstance().getHttpProxyService();
        final String proxyUrl = proxyService.getProxyURL();
        clientConfig.property(ClientProperties.PROXY_URI, proxyUrl);
        if (proxyService.isAuthenticationRequired()) {
            // To work with authenticated proxies and TFS, we provide the proxy credentials if they are registered
            final AuthScope ntlmAuthScope =
                    new AuthScope(proxyService.getProxyHost(), proxyService.getProxyPort(),
                            AuthScope.ANY_REALM, AuthScope.ANY_SCHEME);
            credentialsProvider.setCredentials(ntlmAuthScope,
                    new UsernamePasswordCredentials(proxyService.getUserName(), proxyService.getPassword()));
        }
    }

    // register a filter to set the User Agent header
    clientConfig.register(new ClientRequestFilter() {
        @Override
        public void filter(final ClientRequestContext requestContext) throws IOException {
            // The default user agent is something like "Jersey/2.6"
            final String userAgent = VersionInfo.getUserAgent("Apache-HttpClient", "org.apache.http.client", HttpClientBuilder.class);
            // Finally, we can add the header
            requestContext.getHeaders().add(HttpHeaders.USER_AGENT, userAgent);
        }
    });

    return clientConfig;
}
 
Example #25
Source Project: JaxRSProviders   Author: ECF   File: JaxRSClientDistributionProvider.java    License: Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("rawtypes")
protected void bindClientRequestFilter(ClientRequestFilter instance, Map serviceProps) {
	this.bindJaxComponent(instance, serviceProps);
}
 
Example #26
Source Project: JaxRSProviders   Author: ECF   File: JaxRSClientDistributionProvider.java    License: Apache License 2.0 4 votes vote down vote up
protected void unbindClientRequestFilter(ClientRequestFilter instance) {
	this.removeJaxComponent(instance);
}
 
Example #27
Source Project: datacollector   Author: streamsets   File: DatabricksJobExecutor.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public List<Stage.ConfigIssue> init() {
  List<Stage.ConfigIssue> issues = new ArrayList<>();

  Optional
      .ofNullable(databricksConfigBean.init(getContext(), PREFIX))
      .ifPresent(issues::addAll);

  baseUrl = databricksConfigBean.baseUrl.endsWith("/") ?
      databricksConfigBean.baseUrl.substring(0, databricksConfigBean.baseUrl.length() - 1) :
      databricksConfigBean.baseUrl;

  HttpProxyConfigBean proxyConf = databricksConfigBean.proxyConfigBean;
  String proxyUsername = null;
  String proxyPassword = null;
  if(databricksConfigBean.useProxy) {
    proxyUsername = proxyConf.resolveUsername(getContext(), "PROXY", "conf.proxyConfigBean.", issues);
    proxyPassword = proxyConf.resolvePassword(getContext(), "PROXY", "conf.proxyConfigBean.", issues);
  }

  if(issues.isEmpty()) {
    ClientConfig clientConfig = new ClientConfig()
        .property(ClientProperties.ASYNC_THREADPOOL_SIZE, 1)
        .property(ClientProperties.REQUEST_ENTITY_PROCESSING, RequestEntityProcessing.BUFFERED);

    if (databricksConfigBean.useProxy) {
      clientConfig = clientConfig.connectorProvider(new GrizzlyConnectorProvider(new GrizzlyClientCustomizer(
          true,
          proxyUsername,
          proxyPassword
      )));
    }

    ClientBuilder builder = getClientBuilder()
        .withConfig(clientConfig)
        .register(JacksonJsonProvider.class);
    HttpAuthenticationFeature auth = null;
    if (databricksConfigBean.credentialsConfigBean.credentialType == CredentialType.PASSWORD) {
      String username = databricksConfigBean.credentialsConfigBean.resolveUsername(
          getContext(),
          "CREDENTIALS",
          "conf.credentialsConfigBean.",
          issues
      );
      String password = databricksConfigBean.credentialsConfigBean.resolvePassword(
          getContext(),
          "CREDENTIALS",
          "conf.credentialsConfigBean.",
          issues
      );
      auth = HttpAuthenticationFeature.basic(username, password);
      builder.register(auth);
    } else {
      String token = databricksConfigBean.credentialsConfigBean.resolveToken(
          getContext(),
          "CREDENTIALS",
          "conf.credentialsConfigBean.",
          issues
      );

      builder.register((ClientRequestFilter) requestContext ->
          requestContext.getHeaders().add("Authorization", "Bearer " + token)
      );
    }

    JerseyClientUtil.configureSslContext(databricksConfigBean.tlsConfigBean, builder);

    if(databricksConfigBean.useProxy) {
      JerseyClientUtil.configureProxy(
          proxyConf.uri,
          proxyUsername,
          proxyPassword,
          builder
      );
    }

    client = builder.build();
    validateWithDatabricks(getContext(), issues);
  }
  return issues;
}
 
Example #28
Source Project: docker-java   Author: docker-java   File: JerseyDockerCmdExecFactory.java    License: Apache License 2.0 4 votes vote down vote up
public JerseyDockerCmdExecFactory withClientRequestFilters(ClientRequestFilter... clientRequestFilters) {
    clientBuilder = clientBuilder.clientRequestFilters(clientRequestFilters);
    return this;
}
 
Example #29
Source Project: docker-java   Author: docker-java   File: JerseyDockerHttpClient.java    License: Apache License 2.0 4 votes vote down vote up
public Builder clientRequestFilters(ClientRequestFilter[] value) {
    this.clientRequestFilters = value;
    return this;
}
 
Example #30
Source Project: cxf   Author: apache   File: ClientProviderFactory.java    License: Apache License 2.0 4 votes vote down vote up
public List<ProviderInfo<ClientRequestFilter>> getClientRequestFilters() {
    return Collections.unmodifiableList(clientRequestFilters);
}