Java Code Examples for org.glassfish.jersey.client.ClientConfig#property()

The following examples show how to use org.glassfish.jersey.client.ClientConfig#property() . 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: ApiClient.java    From openapi-generator with Apache License 2.0 8 votes vote down vote up
/**
 * Build the Client used to make HTTP requests.
 * @param debugging Debug setting
 * @return Client
 */
protected Client buildHttpClient(boolean debugging) {
  final ClientConfig clientConfig = new ClientConfig();
  clientConfig.register(MultiPartFeature.class);
  clientConfig.register(json);
  clientConfig.register(JacksonFeature.class);
  clientConfig.property(HttpUrlConnectorProvider.SET_METHOD_WORKAROUND, true);
  // turn off compliance validation to be able to send payloads with DELETE calls
  clientConfig.property(ClientProperties.SUPPRESS_HTTP_COMPLIANCE_VALIDATION, true);
  if (debugging) {
    clientConfig.register(new LoggingFeature(java.util.logging.Logger.getLogger(LoggingFeature.DEFAULT_LOGGER_NAME), java.util.logging.Level.INFO, LoggingFeature.Verbosity.PAYLOAD_ANY, 1024*50 /* Log payloads up to 50K */));
    clientConfig.property(LoggingFeature.LOGGING_FEATURE_VERBOSITY, LoggingFeature.Verbosity.PAYLOAD_ANY);
    // Set logger to ALL
    java.util.logging.Logger.getLogger(LoggingFeature.DEFAULT_LOGGER_NAME).setLevel(java.util.logging.Level.ALL);
  } else {
    // suppress warnings for payloads with DELETE calls:
    java.util.logging.Logger.getLogger("org.glassfish.jersey.client").setLevel(java.util.logging.Level.SEVERE);
  }
  performAdditionalClientConfiguration(clientConfig);
  ClientBuilder clientBuilder = ClientBuilder.newBuilder();
  customizeClientBuilder(clientBuilder);
  clientBuilder = clientBuilder.withConfig(clientConfig);
  return clientBuilder.build();
}
 
Example 2
Source File: GitLabApiClient.java    From choerodon-starters with Apache License 2.0 6 votes vote down vote up
/**
 * Construct an instance to communicate with a GitLab API server using the specified GitLab API version,
 * server URL and private token.
 *
 * @param apiVersion             the ApiVersion specifying which version of the API to use
 * @param hostUrl                the URL to the GitLab API server
 * @param tokenType              the type of auth the token is for, PRIVATE or ACCESS
 * @param authToken              the private token to authenticate with
 * @param secretToken            use this token to validate received payloads
 * @param clientConfigProperties the properties given to Jersey's clientconfig
 */
public GitLabApiClient(ApiVersion apiVersion, String hostUrl, TokenType tokenType, String authToken, String secretToken, Map<String, Object> clientConfigProperties) {

    // Remove the trailing "/" from the hostUrl if present
    this.hostUrl = (hostUrl.endsWith("/") ? hostUrl.replaceAll("/$", "") : hostUrl) + apiVersion.getApiNamespace();
    this.tokenType = tokenType;
    this.authToken = authToken;

    if (secretToken != null) {
        secretToken = secretToken.trim();
        secretToken = (secretToken.length() > 0 ? secretToken : null);
    }

    this.secretToken = secretToken;

    clientConfig = new ClientConfig();
    if (clientConfigProperties != null) {
        for (Map.Entry<String, Object> propertyEntry : clientConfigProperties.entrySet()) {
            clientConfig.property(propertyEntry.getKey(), propertyEntry.getValue());
        }
    }

    clientConfig.register(JacksonJson.class);
}
 
Example 3
Source File: BitmexRestClient.java    From zheshiyigeniubidexiangmu with MIT License 6 votes vote down vote up
public BitmexRestClient(boolean useProduction) {
    if (useProduction) {
        apiURL = productionApiUrl;
    } else {
        apiURL = testnetApiUrl;
    }
    ObjectMapper mapper = new ObjectMapper();
    mapper.registerModule(new JavaTimeModule());
    JacksonJaxbJsonProvider provider = new JacksonJaxbJsonProvider(mapper, new Annotations[0]);
    ClientConfig config = new ClientConfig();
    config.property(ClientProperties.SUPPRESS_HTTP_COMPLIANCE_VALIDATION, true);   
    config.register(provider);
    config.register(JacksonFeature.class);
            
    client = ClientBuilder.newBuilder().withConfig(config).build();
}
 
Example 4
Source File: JerseyDockerHttpClient.java    From docker-java with Apache License 2.0 6 votes vote down vote up
private void configureProxy(ClientConfig clientConfig, URI originalUri, String protocol) {
    List<Proxy> proxies = ProxySelector.getDefault().select(originalUri);

    for (Proxy proxy : proxies) {
        InetSocketAddress address = (InetSocketAddress) proxy.address();
        if (address != null) {
            String hostname = address.getHostName();
            int port = address.getPort();

            clientConfig.property(ClientProperties.PROXY_URI, "http://" + hostname + ":" + port);

            String httpProxyUser = System.getProperty(protocol + ".proxyUser");
            if (httpProxyUser != null) {
                clientConfig.property(ClientProperties.PROXY_USERNAME, httpProxyUser);
                String httpProxyPassword = System.getProperty(protocol + ".proxyPassword");
                if (httpProxyPassword != null) {
                    clientConfig.property(ClientProperties.PROXY_PASSWORD, httpProxyPassword);
                }
            }
        }
    }
}
 
Example 5
Source File: AdminApiKeyStoreTlsAuthTest.java    From pulsar with Apache License 2.0 6 votes vote down vote up
WebTarget buildWebClient() throws Exception {
    ClientConfig httpConfig = new ClientConfig();
    httpConfig.property(ClientProperties.FOLLOW_REDIRECTS, true);
    httpConfig.property(ClientProperties.ASYNC_THREADPOOL_SIZE, 8);
    httpConfig.register(MultiPartFeature.class);

    ClientBuilder clientBuilder = ClientBuilder.newBuilder().withConfig(httpConfig)
        .register(JacksonConfigurator.class).register(JacksonFeature.class);

    SSLContext sslCtx = KeyStoreSSLContext.createClientSslContext(
            KEYSTORE_TYPE,
            CLIENT_KEYSTORE_FILE_PATH,
            CLIENT_KEYSTORE_PW,
            KEYSTORE_TYPE,
            BROKER_TRUSTSTORE_FILE_PATH,
            BROKER_TRUSTSTORE_PW);

    clientBuilder.sslContext(sslCtx).hostnameVerifier(NoopHostnameVerifier.INSTANCE);
    Client client = clientBuilder.build();

    return client.target(brokerUrlTls.toString());
}
 
Example 6
Source File: RxJerseyClientFeature.java    From rx-jersey with MIT License 5 votes vote down vote up
private Client defaultClient() {
    int cores = Runtime.getRuntime().availableProcessors();
    ClientConfig config = new ClientConfig();
    config.connectorProvider(new GrizzlyConnectorProvider());
    config.property(ClientProperties.ASYNC_THREADPOOL_SIZE, cores);
    config.register(RxFlowableInvokerProvider.class);

    return ClientBuilder.newClient(config);
}
 
Example 7
Source File: Jersey2Test.java    From jerseyoauth2 with MIT License 5 votes vote down vote up
@Before
public void setUp()
{
	super.setUp();
	ClientConfig clientConfig = new ClientConfig();
	clientConfig.property(ClientProperties.FOLLOW_REDIRECTS, false);
	client = ClientBuilder.newClient(clientConfig);
	client.register(new HttpBasicAuthFilter("manager", "test"));
	client.register(LoggingFilter.class);
	authClient.authorizeClient(clientEntity, "test1 test2");
}
 
Example 8
Source File: JerseySpringTest.java    From gravitee-management-rest-api with Apache License 2.0 5 votes vote down vote up
@Autowired
public void setApplicationContext(final ApplicationContext context)
{
    _jerseyTest = new JerseyTest()
    {
        
        @Override
        protected Application configure()
        {
            // Find first available port.
            forceSet(TestProperties.CONTAINER_PORT, "0");

            ResourceConfig application = new GraviteeManagementApplication(authenticationProviderManager);

            application.property("contextConfig", context);
            decorate(application);

            return application;
        }

        @Override
        protected void configureClient(ClientConfig config) {
            super.configureClient(config);

            config.register(ObjectMapperResolver.class);
            config.register(MultiPartFeature.class);
            config.property(HttpUrlConnectorProvider.SET_METHOD_WORKAROUND, true);

        }
    };
}
 
Example 9
Source File: AsyncRestClient.java    From micro-server with Apache License 2.0 5 votes vote down vote up
protected Client initClient(int rt, int ct) {

		ClientConfig clientConfig = new ClientConfig();
		clientConfig.property(ClientProperties.CONNECT_TIMEOUT, ct);
		clientConfig.property(ClientProperties.READ_TIMEOUT, rt);

		ClientBuilder.newBuilder().register(JacksonFeature.class);
		Client client = ClientBuilder.newClient(clientConfig);
		client.register(JacksonFeature.class);
		JacksonJaxbJsonProvider provider = new JacksonJaxbJsonProvider();
		provider.setMapper(JacksonUtil.getMapper());
		client.register(provider);
		return client;

	}
 
Example 10
Source File: DefaultSchemaRegistryClient.java    From ranger with Apache License 2.0 5 votes vote down vote up
private ClientConfig createClientConfig(Map<String, ?> conf) {
    ClientConfig config = new ClientConfig();
    config.property(ClientProperties.CONNECT_TIMEOUT, DEFAULT_CONNECTION_TIMEOUT);
    config.property(ClientProperties.READ_TIMEOUT, DEFAULT_READ_TIMEOUT);
    config.property(ClientProperties.FOLLOW_REDIRECTS, true);
    for (Map.Entry<String, ?> entry : conf.entrySet()) {
        config.property(entry.getKey(), entry.getValue());
    }
    return config;
}
 
Example 11
Source File: WnsClient.java    From java-wns with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private static void setProxyCredentials(ClientConfig clientConfig, WnsProxyProperties proxyProps) {
    if (proxyProps != null) {
        String proxyUri = proxyProps.getUri();
        String proxyUser = proxyProps.getUser();
        String proxyPass = proxyProps.getPass();

        if (proxyUri != null) {
            clientConfig.property(ClientProperties.PROXY_URI, proxyUri);
            if ( (proxyUser != null) && !proxyUser.trim().isEmpty()) {
                clientConfig.property(ClientProperties.PROXY_USERNAME, proxyUser);
                clientConfig.property(ClientProperties.PROXY_PASSWORD, proxyPass);
            }
        }
    }
}
 
Example 12
Source File: RestSchemaRegistryClient.java    From nifi with Apache License 2.0 5 votes vote down vote up
public RestSchemaRegistryClient(final List<String> baseUrls, final int timeoutMillis, final SSLContext sslContext, final ComponentLog logger) {
    this.baseUrls = new ArrayList<>(baseUrls);

    final ClientConfig clientConfig = new ClientConfig();
    clientConfig.property(ClientProperties.CONNECT_TIMEOUT, timeoutMillis);
    clientConfig.property(ClientProperties.READ_TIMEOUT, timeoutMillis);
    client = WebUtils.createClient(clientConfig, sslContext);

    this.logger = logger;
}
 
Example 13
Source File: AnnotationAuthTest.java    From shiro-jersey with Apache License 2.0 5 votes vote down vote up
private Client newClient(Map<String, Object> props) {
    ClientConfig config = new ClientConfig().connectorProvider(new ApacheConnectorProvider());
    if (props != null)
        for (Entry<String, Object> entry : props.entrySet())
            config.property(entry.getKey(), entry.getValue());
    return ClientBuilder.newClient(config);
}
 
Example 14
Source File: JerseyHttpClient.java    From karate with MIT License 5 votes vote down vote up
@Override
public void configure(Config config, ScenarioContext context) {
    ClientConfig cc = new ClientConfig();
    // support request body for DELETE (non-standard)
    cc.property(ClientProperties.SUPPRESS_HTTP_COMPLIANCE_VALIDATION, true);
    charset = config.getCharset();
    if (!config.isFollowRedirects()) {
        cc.property(ClientProperties.FOLLOW_REDIRECTS, false);
    }
    ClientBuilder clientBuilder = ClientBuilder.newBuilder()
            .withConfig(cc)
            .register(new LoggingInterceptor(context)) // must be first
            .register(MultiPartFeature.class);
    if (config.isSslEnabled()) {
        String algorithm = config.getSslAlgorithm(); // could be null
        KeyStore trustStore = HttpUtils.getKeyStore(context,
                config.getSslTrustStore(), config.getSslTrustStorePassword(), config.getSslTrustStoreType());
        KeyStore keyStore = HttpUtils.getKeyStore(context,
                config.getSslKeyStore(), config.getSslKeyStorePassword(), config.getSslKeyStoreType());
        SSLContext sslContext = SslConfigurator.newInstance()
                .securityProtocol(algorithm) // will default to TLS if null
                .trustStore(trustStore)
                .keyStore(keyStore)
                .createSSLContext();
        HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());
        clientBuilder.sslContext(sslContext);
        clientBuilder.hostnameVerifier((host, session) -> true);
    }
    client = clientBuilder.build();
    client.property(ClientProperties.CONNECT_TIMEOUT, config.getConnectTimeout());
    client.property(ClientProperties.READ_TIMEOUT, config.getReadTimeout());
    if (config.getProxyUri() != null) {
        client.property(ClientProperties.PROXY_URI, config.getProxyUri());
        if (config.getProxyUsername() != null && config.getProxyPassword() != null) {
            client.property(ClientProperties.PROXY_USERNAME, config.getProxyUsername());
            client.property(ClientProperties.PROXY_PASSWORD, config.getProxyPassword());
        }
    }
}
 
Example 15
Source File: AnnotationAuthTest.java    From shiro-jersey with Apache License 2.0 5 votes vote down vote up
private Client newClient(Map<String, Object> props) {
    ClientConfig config = new ClientConfig().connectorProvider(new ApacheConnectorProvider());
    if (props != null)
        for (Entry<String, Object> entry : props.entrySet())
            config.property(entry.getKey(), entry.getValue());
    return ClientBuilder.newClient(config);
}
 
Example 16
Source File: ElasticConnectionPool.java    From dremio-oss with Apache License 2.0 4 votes vote down vote up
public void connect() throws IOException {
  final ClientConfig configuration = new ClientConfig();
  configuration.property(ClientProperties.READ_TIMEOUT, readTimeoutMillis);
  final AWSCredentialsProvider awsCredentialsProvider = elasticsearchAuthentication.getAwsCredentialsProvider();
  if (awsCredentialsProvider != null) {
    configuration.property(REGION_NAME, elasticsearchAuthentication.getRegionName());
    configuration.register(ElasticsearchRequestClientFilter.class);
    configuration.register(new InjectableAWSCredentialsProvider(awsCredentialsProvider), InjectableAWSCredentialsProvider.class);
  }

  final ClientBuilder builder = ClientBuilder.newBuilder()
      .withConfig(configuration);

  switch(sslMode) {
  case UNSECURE:
    builder.sslContext(SSLHelper.newAllTrustingSSLContext("SSL"));
    // fall-through
  case VERIFY_CA:
    builder.hostnameVerifier(SSLHelper.newAllValidHostnameVerifier());
    // fall-through
  case STRICT:
    break;

  case OFF:
    // no TLS/SSL configuration
  }

  client = builder.build();
  client.register(GZipEncoder.class);
  client.register(DeflateEncoder.class);
  client.register(EncodingFilter.class);

  if (REQUEST_LOGGER.isDebugEnabled()) {
    java.util.logging.Logger julLogger = java.util.logging.Logger.getLogger(REQUEST_LOGGER_NAME);
    client.register(new LoggingFeature(
        julLogger,
        Level.FINE,
        REQUEST_LOGGER.isTraceEnabled() ? LoggingFeature.Verbosity.PAYLOAD_TEXT : LoggingFeature.Verbosity.HEADERS_ONLY,
        65536));
  }

  final JacksonJaxbJsonProvider provider = new JacksonJaxbJsonProvider();
  provider.setMapper(ElasticMappingSet.MAPPER);

  // Disable other JSON providers.
  client.property(
    PropertiesHelper.getPropertyNameForRuntime(InternalProperties.JSON_FEATURE, client.getConfiguration().getRuntimeType()),
    JacksonJaxbJsonProvider.class.getSimpleName());

  client.register(provider);

  HttpAuthenticationFeature httpAuthenticationFeature = elasticsearchAuthentication.getHttpAuthenticationFeature();
  if (httpAuthenticationFeature != null) {
    client.register(httpAuthenticationFeature);
  }

  updateClients();
}
 
Example 17
Source File: JsonApiResponseFilterTestBase.java    From crnk-framework with Apache License 2.0 4 votes vote down vote up
@BeforeClass
public static void setup() {
    ClientConfig config = new ClientConfig();
    config.property(HttpUrlConnectorProvider.SET_METHOD_WORKAROUND, true);
    httpClient = ClientBuilder.newClient(config);
}
 
Example 18
Source File: RestClientHelper.java    From azure-devops-intellij with 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 19
Source File: DefaultDockerClient.java    From docker-client with Apache License 2.0 4 votes vote down vote up
/**
 * Create a new client using the configuration of the builder.
 *
 * @param builder DefaultDockerClient builder
 */
protected DefaultDockerClient(final Builder builder) {
  final URI originalUri = checkNotNull(builder.uri, "uri");
  checkNotNull(originalUri.getScheme(), "url has null scheme");
  this.apiVersion = builder.apiVersion();

  if ((builder.dockerCertificatesStore != null) && !originalUri.getScheme().equals("https")) {
    throw new IllegalArgumentException(
        "An HTTPS URI for DOCKER_HOST must be provided to use Docker client certificates");
  }

  if (originalUri.getScheme().equals(UNIX_SCHEME)) {
    this.uri = UnixConnectionSocketFactory.sanitizeUri(originalUri);
  } else if (originalUri.getScheme().equals(NPIPE_SCHEME)) {
    this.uri = NpipeConnectionSocketFactory.sanitizeUri(originalUri);
  } else {
    this.uri = originalUri;
  }

  final HttpClientConnectionManager cm = getConnectionManager(builder);
  final HttpClientConnectionManager noTimeoutCm = getConnectionManager(builder);

  final RequestConfig requestConfig = RequestConfig.custom()
      .setConnectionRequestTimeout((int) builder.connectTimeoutMillis)
      .setConnectTimeout((int) builder.connectTimeoutMillis)
      .setSocketTimeout((int) builder.readTimeoutMillis)
      .build();

  final ClientConfig config = updateProxy(defaultConfig, builder)
      .connectorProvider(new ApacheConnectorProvider())
      .property(ApacheClientProperties.CONNECTION_MANAGER, cm)
      .property(ApacheClientProperties.REQUEST_CONFIG, requestConfig);

  if (builder.registryAuthSupplier == null) {
    this.registryAuthSupplier = new FixedRegistryAuthSupplier();
  } else {
    this.registryAuthSupplier = builder.registryAuthSupplier;
  }
  
  if (builder.getRequestEntityProcessing() != null) {
    config.property(ClientProperties.REQUEST_ENTITY_PROCESSING, builder.requestEntityProcessing);
  }

  this.client = ClientBuilder.newBuilder()
      .withConfig(config)
      .build();

  // ApacheConnector doesn't respect per-request timeout settings.
  // Workaround: instead create a client with infinite read timeout,
  // and use it for waitContainer, stopContainer, attachContainer, logs, and build
  final RequestConfig noReadTimeoutRequestConfig = RequestConfig.copy(requestConfig)
      .setSocketTimeout((int) NO_TIMEOUT)
      .build();
  this.noTimeoutClient = ClientBuilder.newBuilder()
      .withConfig(config)
      .property(ApacheClientProperties.CONNECTION_MANAGER, noTimeoutCm)
      .property(ApacheClientProperties.REQUEST_CONFIG, noReadTimeoutRequestConfig)
      .build();

  this.headers = new HashMap<>(builder.headers());
}
 
Example 20
Source File: ReactiveRequest.java    From micro-server with Apache License 2.0 3 votes vote down vote up
protected Client initClient(int rt, int ct) {

        ClientConfig clientConfig = new ClientConfig();
        clientConfig.property(ClientProperties.CONNECT_TIMEOUT, ct);
        clientConfig.property(ClientProperties.READ_TIMEOUT, rt);

        ClientBuilder.newBuilder()
                     .register(JacksonFeature.class);
        Client client = ClientBuilder.newClient(clientConfig);

        return client;

    }