org.glassfish.jersey.apache.connector.ApacheClientProperties Java Examples

The following examples show how to use org.glassfish.jersey.apache.connector.ApacheClientProperties. 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: DockerClient.java    From rapid with MIT License 6 votes vote down vote up
private void init() {
    final URI originalUri = URI.create(DEFAULT_UNIX_ENDPOINT);
    sanitizeUri = UnixFactory.sanitizeUri(originalUri);

    final RegistryBuilder<ConnectionSocketFactory> registryBuilder =
            RegistryBuilder.<ConnectionSocketFactory>create()
                    .register("https", SSLConnectionSocketFactory.getSocketFactory())
                    .register("http", PlainConnectionSocketFactory.getSocketFactory())
                    .register("unix", new UnixFactory(originalUri));

    final PoolingHttpClientConnectionManager cm =
            new PoolingHttpClientConnectionManager(registryBuilder.build());

    final RequestConfig requestConfig = RequestConfig.custom()
            .setConnectionRequestTimeout((int) SECONDS.toMillis(5))
            .setConnectTimeout((int) SECONDS.toMillis(5))
            .setSocketTimeout((int) SECONDS.toMillis(30))
            .build();

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

    client = ClientBuilder.newBuilder().withConfig(config).build();
}
 
Example #2
Source File: AbstractRestClient.java    From hugegraph-common with Apache License 2.0 5 votes vote down vote up
public AbstractRestClient(String url, ClientConfig config) {
    Client client = null;
    Object protocol = config.getProperty("protocol");
    if (protocol != null && protocol.equals("https")) {
        client = wrapTrustConfig(url, config);
    } else {
        client = ClientBuilder.newClient(config);
    }
    this.client = client;
    this.client.register(GZipEncoder.class);
    this.target = this.client.target(url);
    this.pool = (PoolingHttpClientConnectionManager) config.getProperty(
                ApacheClientProperties.CONNECTION_MANAGER);
    if (this.pool != null) {
        this.cleanExecutor = ExecutorUtil.newScheduledThreadPool(
                                          "conn-clean-worker-%d");
        Number idleTimeProp = (Number) config.getProperty("idleTime");
        final long idleTime = idleTimeProp == null ?
                              IDLE_TIME : idleTimeProp.longValue();
        final long checkPeriod = idleTime / 2L;
        this.cleanExecutor.scheduleWithFixedDelay(() -> {
            PoolStats stats = this.pool.getTotalStats();
            int using = stats.getLeased() + stats.getPending();
            if (using > 0) {
                // Do clean only when all connections are idle
                return;
            }
            // Release connections when all clients are inactive
            this.pool.closeIdleConnections(idleTime, TimeUnit.MILLISECONDS);
            this.pool.closeExpiredConnections();
        }, checkPeriod, checkPeriod, TimeUnit.MILLISECONDS);
    }
}
 
Example #3
Source File: ServerContextTest.java    From azure-devops-intellij with MIT License 5 votes vote down vote up
@Test
public void getClientConfig() {
    AuthenticationInfo info = new AuthenticationInfo("user1", "pass", "server1", "4display");
    final ClientConfig config = RestClientHelper.getClientConfig(ServerContext.Type.TFS, info, false);

    final Map<String, Object> properties = config.getProperties();
    Assert.assertEquals(3, properties.size());

    Assert.assertEquals(false, properties.get(ApacheClientProperties.PREEMPTIVE_BASIC_AUTHENTICATION));
    Assert.assertEquals(RequestEntityProcessing.BUFFERED, properties.get(ClientProperties.REQUEST_ENTITY_PROCESSING));

    final CredentialsProvider cp = (CredentialsProvider) properties.get(ApacheClientProperties.CREDENTIALS_PROVIDER);
    final Credentials credentials = cp.getCredentials(AuthScope.ANY);
    Assert.assertEquals(info.getPassword(), credentials.getPassword());
    Assert.assertEquals(info.getUserName(), credentials.getUserPrincipal().getName());

    // Make sure Fiddler properties get set if property is on
    final ClientConfig config2 = RestClientHelper.getClientConfig(ServerContext.Type.TFS, info, true);
    final Map<String, Object> properties2 = config2.getProperties();
    //proxy setting doesn't automatically mean we need to setup ssl trust store anymore
    Assert.assertEquals(4, properties2.size());
    Assert.assertNotNull(properties2.get(ClientProperties.PROXY_URI));

    info = new AuthenticationInfo("users1", "pass", "https://tfsonprem.test", "4display");
    final ClientConfig config3 = RestClientHelper.getClientConfig(ServerContext.Type.TFS, info, false);
    final Map<String, Object> properties3 = config3.getProperties();
    Assert.assertEquals(3, properties3.size());
    Assert.assertNull(properties3.get(ClientProperties.PROXY_URI));
}
 
Example #4
Source File: AnnotationAuthTest.java    From shiro-jersey with Apache License 2.0 5 votes vote down vote up
private void auth(String username, String password) {
    client.close();
    client = null;
    CredentialsProvider credentials = new BasicCredentialsProvider();
    credentials.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password));
    Map<String, Object> props = new HashMap<>();
    props.put(ApacheClientProperties.PREEMPTIVE_BASIC_AUTHENTICATION, true);
    props.put(ApacheClientProperties.CREDENTIALS_PROVIDER, credentials);
    client = newClient(props);
}
 
Example #5
Source File: AnnotationAuthTest.java    From shiro-jersey with Apache License 2.0 5 votes vote down vote up
private void auth(String username, String password) {
    client.close();
    client = null;
    CredentialsProvider credentials = new BasicCredentialsProvider();
    credentials.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password));
    Map<String, Object> props = new HashMap<>();
    props.put(ApacheClientProperties.PREEMPTIVE_BASIC_AUTHENTICATION, true);
    props.put(ApacheClientProperties.CREDENTIALS_PROVIDER, credentials);
    client = newClient(props);
}
 
Example #6
Source File: ZTSClient.java    From athenz with Apache License 2.0 4 votes vote down vote up
private void initClient(final String serverUrl, Principal identity,
        final String domainName, final String serviceName,
        final ServiceIdentityProvider siaProvider) {
    
    ztsUrl = (serverUrl == null) ? confZtsUrl : serverUrl;
    
    // verify if the url is ending with /zts/v1 and if it's
    // not we'll automatically append it
    
    if (ztsUrl != null && !ztsUrl.isEmpty()) {
        if (!ztsUrl.endsWith("/zts/v1")) {
            if (ztsUrl.charAt(ztsUrl.length() - 1) != '/') {
                ztsUrl += '/';
            }
            ztsUrl += "zts/v1";
        }
    }

    // determine to see if we need a host verifier for our ssl connections
    
    HostnameVerifier hostnameVerifier = null;
    if (x509CertDNSName != null && !x509CertDNSName.isEmpty()) {
        hostnameVerifier = new AWSHostNameVerifier(x509CertDNSName);
    }
    
    // if we don't have a ssl context specified, check the system
    // properties to see if we need to create one

    if (sslContext == null) {
        sslContext = createSSLContext();
    }

    // setup our client config object with timeouts

    final JacksonJsonProvider jacksonJsonProvider = new JacksonJaxbJsonProvider()
            .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    final ClientConfig config = new ClientConfig(jacksonJsonProvider);

    PoolingHttpClientConnectionManager connManager = createConnectionManager(sslContext, hostnameVerifier);
    if (connManager != null) {
        config.property(ApacheClientProperties.CONNECTION_MANAGER, connManager);
    }
    config.connectorProvider(new ApacheConnectorProvider());

    // if we're asked to use a proxy for our request
    // we're going to set the property that is supported
    // by the apache connector and use that
    
    if (proxyUrl != null) {
        config.property(ClientProperties.PROXY_URI, proxyUrl);
    }
    
    ClientBuilder builder = getClientBuilder();
    if (sslContext != null) {
        builder = builder.sslContext(sslContext);
        enablePrefetch = true;
    }

    // JerseyClientBuilder::withConfig() replaces the existing config with the new client
    // config. Hence the client config should be added to the builder before the timeouts.
    // Otherwise the timeout settings would be overridden.
    Client rsClient = builder.withConfig(config)
            .hostnameVerifier(hostnameVerifier)
            .readTimeout(reqReadTimeout, TimeUnit.MILLISECONDS)
            .connectTimeout(reqConnectTimeout, TimeUnit.MILLISECONDS)
            .build();

    ztsClient = new ZTSRDLGeneratedClient(ztsUrl, rsClient);
    principal = identity;
    domain = domainName;
    service = serviceName;
    this.siaProvider = siaProvider;
    
    // if we are given a principal object then we need
    // to update the domain/service settings
    
    if (principal != null) {
        domain  = principal.getDomain();
        service = principal.getName();
        ztsClient.addCredentials(identity.getAuthority().getHeader(), identity.getCredentials());
    }
}
 
Example #7
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 #8
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 #9
Source File: UsergridExternalProvider.java    From usergrid with Apache License 2.0 4 votes vote down vote up
private Client getJerseyClient() {

        if (jerseyClient == null) {

            synchronized (this) {

                // create HTTPClient and with configured connection pool

                int poolSize = 100; // connections
                final String poolSizeStr = properties.getProperty(CENTRAL_CONNECTION_POOL_SIZE);
                if (poolSizeStr != null) {
                    poolSize = Integer.parseInt(poolSizeStr);
                }

                PoolingClientConnectionManager connectionManager = new PoolingClientConnectionManager();
                connectionManager.setMaxTotal(poolSize);

                int timeout = 20000; // ms
                final String timeoutStr = properties.getProperty(CENTRAL_CONNECTION_TIMEOUT);
                if (timeoutStr != null) {
                    timeout = Integer.parseInt(timeoutStr);
                }

                int readTimeout = 20000; // ms
                final String readTimeoutStr = properties.getProperty(CENTRAL_READ_TIMEOUT);
                if (readTimeoutStr != null) {
                    readTimeout = Integer.parseInt(readTimeoutStr);
                }

                ClientConfig clientConfig = new ClientConfig();
                clientConfig.register(new JacksonFeature());
                clientConfig.property(ApacheClientProperties.CONNECTION_MANAGER, connectionManager);
                clientConfig.connectorProvider(new ApacheConnectorProvider());

                jerseyClient = ClientBuilder.newClient(clientConfig);
                jerseyClient.property(ClientProperties.CONNECT_TIMEOUT, timeout);
                jerseyClient.property(ClientProperties.READ_TIMEOUT, readTimeout);
            }
        }

        return jerseyClient;

    }
 
Example #10
Source File: ProxyClientConfig.java    From gitlab4j-api with MIT License 3 votes vote down vote up
/**
 * Create a Map instance set up to use an NTLM proxy server that can be passed to the GitLabAPi constructors 
 * and login methods to configure the GitLabApi instance to use an NTLM proxy server.
 *
 * @param proxyUri the URI of the proxy server
 * @param username the user name. This should not include the domain to authenticate with.
 * For example: "user" is correct whereas "DOMAIN&#92;user" is not.
 * @param password the password
 * @param workstation the workstation the authentication request is originating from. Essentially, the computer name for this machine.
 * @param domain the domain to authenticate within
 * @return a Map set up to allow GitLabApi to use an NTLM proxy server
 */
public static Map<String, Object> createNtlmProxyClientConfig(String proxyUri, String username, String password, String workstation, String domain) {

    Map<String, Object> clientConfig = new HashMap<>();
    clientConfig.put(ClientProperties.PROXY_URI, proxyUri);

    CredentialsProvider credentials = new BasicCredentialsProvider();
    credentials.setCredentials(AuthScope.ANY, new NTCredentials(username, password, workstation, domain));
    clientConfig.put(ApacheClientProperties.CREDENTIALS_PROVIDER, credentials);

    return (clientConfig);
}