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

The following examples show how to use org.glassfish.jersey.apache.connector.ApacheConnectorProvider. 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: InstanceProviderClient.java    From athenz with Apache License 2.0 6 votes vote down vote up
public InstanceProviderClient(String url, SSLContext sslContext,
        HostnameVerifier hostnameVerifier, int connectTimeout, int readTimeout) {

    final ClientConfig config = new ClientConfig()
            .property(ClientProperties.CONNECT_TIMEOUT, connectTimeout)
            .property(ClientProperties.READ_TIMEOUT, readTimeout)
            .connectorProvider(new ApacheConnectorProvider());

    ClientBuilder builder = ClientBuilder.newBuilder();
    if (sslContext != null) {
        builder = builder.sslContext(sslContext);
    }

    client = builder.hostnameVerifier(hostnameVerifier)
            .withConfig(config)
            .build();
    base = client.target(url);
}
 
Example #3
Source File: Utils.java    From symphony-java-sample-bots with Apache License 2.0 5 votes vote down vote up
public static SymphonyClient getSymphonyClient(SymphonyClientConfig symphonyClientConfig) throws InitException, AuthenticationException {
    SymphonyClient symClient = SymphonyClientFactory.getClient(SymphonyClientFactory.TYPE.BASIC);
    String proxy = symphonyClientConfig.get("proxy.url");

    if (proxy == null) {
        symClient.init(symphonyClientConfig);
        return symClient;
    } else {
        ClientConfig clientConfig = new ClientConfig();
        clientConfig.connectorProvider(new ApacheConnectorProvider());
        clientConfig.property(ClientProperties.PROXY_URI, proxy);

        try {
            Client httpClient = CustomHttpClient.getClient(
                    symphonyClientConfig.get(SymphonyClientConfigID.USER_CERT_FILE),
                    symphonyClientConfig.get(SymphonyClientConfigID.USER_CERT_PASSWORD),
                    symphonyClientConfig.get(SymphonyClientConfigID.TRUSTSTORE_FILE),
                    symphonyClientConfig.get(SymphonyClientConfigID.TRUSTSTORE_PASSWORD),
                    clientConfig);
            symClient.init(httpClient, symphonyClientConfig);
            return symClient;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    return symClient;
}
 
Example #4
Source File: OmniturePollingConsumer.java    From datacollector with Apache License 2.0 5 votes vote down vote up
private void configureProxy(
  ClientConfig config,
  String proxyUri,
  String username,
  String password
) {
  config.property(ClientProperties.PROXY_URI, proxyUri);
  if (username != null && !username.isEmpty()) {
    config.property(ClientProperties.PROXY_USERNAME, username);
  }
  if (password != null && !password.isEmpty()) {
    config.property(ClientProperties.PROXY_PASSWORD, password);
  }
  config.connectorProvider(new ApacheConnectorProvider());
}
 
Example #5
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 #6
Source File: DefaultDockerClient.java    From docker-client with Apache License 2.0 5 votes vote down vote up
@Override
public EventStream events(EventsParam... params)
    throws DockerException, InterruptedException {
  WebTarget resource = noTimeoutResource().path("events");
  resource = addParameters(resource, params);

  try {
    final CloseableHttpClient client = (CloseableHttpClient) ApacheConnectorProvider
        .getHttpClient(noTimeoutClient);
    final CloseableHttpResponse response = client.execute(new HttpGet(resource.getUri()));
    return new EventStream(response, objectMapper());
  } catch (IOException exception) {
    throw new DockerException(exception);
  }
}
 
Example #7
Source File: GitLabApiClient.java    From gitlab4j-api with MIT License 5 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);
    this.baseUrl = this.hostUrl;
    this.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) {

        if (clientConfigProperties.containsKey(ClientProperties.PROXY_URI)) {
            clientConfig.connectorProvider(new ApacheConnectorProvider());
        }

        for (Map.Entry<String, Object> propertyEntry : clientConfigProperties.entrySet()) {
            clientConfig.property(propertyEntry.getKey(), propertyEntry.getValue());
        }
    }

    // Disable auto-discovery of feature and services lookup, this will force Jersey
    // to use the features and services explicitly configured by gitlab4j
    clientConfig.property(ClientProperties.FEATURE_AUTO_DISCOVERY_DISABLE, true);
    clientConfig.property(ClientProperties.METAINF_SERVICES_LOOKUP_DISABLE, true);

    clientConfig.register(JacksonJson.class);
    clientConfig.register(MultiPartFeature.class);
}
 
Example #8
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 #9
Source File: ZMSClient.java    From athenz with Apache License 2.0 4 votes vote down vote up
/**
 * Initialize the client for class constructors
 *
 * @param url        ZMS Server url
 * @param sslContext SSLContext for service authentication
 */
private void initClient(String url, SSLContext sslContext) {

    /* if we have no url specified then we're going to retrieve
     * the value from our configuration package */

    if (url == null) {
        zmsUrl = lookupZMSUrl();
    } else {
        zmsUrl = url;
    }

    /* verify if the url is ending with /zms/v1 and if it's
     * not we'll automatically append it */

    if (zmsUrl != null && !zmsUrl.isEmpty()) {
        if (!zmsUrl.endsWith("/zms/v1")) {
            if (zmsUrl.charAt(zmsUrl.length() - 1) != '/') {
                zmsUrl += '/';
            }
            zmsUrl += "zms/v1";
        }
    }

    /* determine our read and connect timeouts */

    int readTimeout = Integer.parseInt(System.getProperty(ZMS_CLIENT_PROP_READ_TIMEOUT, "30000"));
    int connectTimeout = Integer.parseInt(System.getProperty(ZMS_CLIENT_PROP_CONNECT_TIMEOUT, "30000"));

    /* if we are not given a url then use the default value */

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

    ClientBuilder builder = getClientBuilder();
    if (sslContext != null) {
        builder = builder.sslContext(sslContext);
    }

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

    // 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(clientConfig)
            .connectTimeout(connectTimeout, TimeUnit.MILLISECONDS)
            .readTimeout(readTimeout, TimeUnit.MILLISECONDS)
            .build();

    client = new ZMSRDLGeneratedClient(zmsUrl, rsClient);
}
 
Example #10
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 #11
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 #12
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 #13
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;

    }