Java Code Examples for javax.ws.rs.client.ClientBuilder#sslContext()

The following examples show how to use javax.ws.rs.client.ClientBuilder#sslContext() . 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: TlsToolkitGetStatus.java    From nifi with Apache License 2.0 7 votes vote down vote up
public void get(final GetStatusConfig config) {
    final SSLContext sslContext = config.getSslContext();

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

    final ClientConfig clientConfig = new ClientConfig();
    clientConfig.property(ClientProperties.CONNECT_TIMEOUT, 10000);
    clientConfig.property(ClientProperties.READ_TIMEOUT, 10000);
    clientBuilder.withConfig(clientConfig);

    final Client client = clientBuilder.build();
    final WebTarget target = client.target(config.getUrl());
    final Response response = target.request().get();
    System.out.println("Response Code - " + response.getStatus());
}
 
Example 2
Source File: ClientSetup.java    From component-runtime with Apache License 2.0 6 votes vote down vote up
private ClientBuilder createClient(final ExecutorService executor, final Optional<String> keystoreLocation,
        final Optional<String> keystoreType, final String keystorePassword, final Optional<String> truststoreType,
        final List<String> serverHostnames) {
    final ClientBuilder builder = ClientBuilder.newBuilder();
    builder.connectTimeout(connectTimeout, MILLISECONDS);
    builder.readTimeout(readTimeout, MILLISECONDS);
    builder.executorService(executor);
    if (acceptAnyCertificate) {
        builder.hostnameVerifier((host, session) -> true);
        builder.sslContext(createUnsafeSSLContext());
    } else if (keystoreLocation.isPresent()) {
        builder.hostnameVerifier((host, session) -> serverHostnames.contains(host));
        builder.sslContext(createSSLContext(keystoreLocation, keystoreType, keystorePassword, truststoreType));
    }
    providers.map(it -> Stream.of(it.split(",")).map(String::trim).filter(v -> !v.isEmpty()).map(fqn -> {
        try {
            return Thread.currentThread().getContextClassLoader().loadClass(fqn).getConstructor().newInstance();
        } catch (final Exception e) {
            log.warn("Can't add provider " + fqn + ": " + e.getMessage(), e);
            return null;
        }
    }).filter(Objects::nonNull)).ifPresent(it -> it.forEach(builder::register));
    return ClientTracingRegistrar.configure(builder);
}
 
Example 3
Source File: WebClient.java    From dremio-oss with Apache License 2.0 6 votes vote down vote up
private void setTrustStore(ClientBuilder clientBuilder, DACConfig dacConfig)
  throws IOException, GeneralSecurityException {
  Optional<KeyStore> trustStore = Optional.empty();

  if (checkCertificates) {
    trustStore = new SSLConfigurator(dacConfig.getConfig(), DremioConfig.WEB_SSL_PREFIX, "web").getTrustStore();
    if (trustStore.isPresent()) {
      clientBuilder.trustStore(trustStore.get());
    }
  } else {
    SSLContext sslContext = SSLHelper.newAllTrustingSSLContext("SSL");
    HostnameVerifier verifier = SSLHelper.newAllValidHostnameVerifier();
    clientBuilder.hostnameVerifier(verifier);
    clientBuilder.sslContext(sslContext);
  }
}
 
Example 4
Source File: DefaultSchemaRegistryClient.java    From ranger with Apache License 2.0 6 votes vote down vote up
public DefaultSchemaRegistryClient(Map<String, ?> conf) {
    configuration = new Configuration(conf);
    login = SecurityUtils.initializeSecurityContext(conf);
    ClientConfig config = createClientConfig(conf);
    final boolean SSLEnabled = SecurityUtils.isHttpsConnection(conf);
    ClientBuilder clientBuilder = JerseyClientBuilder.newBuilder()
            .withConfig(config)
            .property(ClientProperties.FOLLOW_REDIRECTS, Boolean.TRUE);
    if (SSLEnabled) {
        SSLContext ctx;
        try {
            ctx = SecurityUtils.createSSLContext(conf, SSL_ALGORITHM);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        clientBuilder.sslContext(ctx);
    }
    client = clientBuilder.build();

    // get list of urls and create given or default UrlSelector.
    urlSelector = createUrlSelector();
    urlWithTargets = new ConcurrentHashMap<>();
}
 
Example 5
Source File: IntegrationTestBase.java    From nifi-registry with Apache License 2.0 6 votes vote down vote up
private static Client createClientFromConfig(NiFiRegistryClientConfig registryClientConfig) {

        final ClientConfig clientConfig = new ClientConfig();
        clientConfig.register(jacksonJaxbJsonProvider());

        final ClientBuilder clientBuilder = ClientBuilder.newBuilder().withConfig(clientConfig);

        final SSLContext sslContext = registryClientConfig.getSslContext();
        if (sslContext != null) {
            clientBuilder.sslContext(sslContext);
        }

        final HostnameVerifier hostnameVerifier = registryClientConfig.getHostnameVerifier();
        if (hostnameVerifier != null) {
            clientBuilder.hostnameVerifier(hostnameVerifier);
        }

        return clientBuilder.build();
    }
 
Example 6
Source File: JerseyJaxRsClientFactory.java    From vespa with 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 7
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 8
Source File: ConfigurationLoader.java    From openwebbeans-meecrowave with Apache License 2.0 6 votes vote down vote up
private Client createClient(final Routes.Route route) {
    final ClientBuilder clientBuilder = ClientBuilder.newBuilder();
    clientBuilder.executorService(route.executor);
    clientBuilder.readTimeout(route.clientConfiguration.timeouts.read, MILLISECONDS);
    clientBuilder.connectTimeout(route.clientConfiguration.timeouts.connect, MILLISECONDS);
    // clientBuilder.scheduledExecutorService(); // not used by cxf for instance so no need to overkill the conf

    if (route.clientConfiguration.sslConfiguration.acceptAnyCertificate) {
        clientBuilder.hostnameVerifier((host, session) -> true);
        clientBuilder.sslContext(createUnsafeSSLContext());
    } else if (route.clientConfiguration.sslConfiguration.keystoreLocation != null) {
        if (route.clientConfiguration.sslConfiguration.verifiedHostnames != null) {
            clientBuilder.hostnameVerifier((host, session) -> route.clientConfiguration.sslConfiguration.verifiedHostnames.contains(host));
        }
        clientBuilder.sslContext(createSSLContext(
                route.clientConfiguration.sslConfiguration.keystoreLocation,
                route.clientConfiguration.sslConfiguration.keystoreType,
                route.clientConfiguration.sslConfiguration.keystorePassword,
                route.clientConfiguration.sslConfiguration.truststoreType));
    }

    return clientBuilder.build();
}
 
Example 9
Source File: RestClientFactory.java    From pay-publicapi with MIT License 6 votes vote down vote up
public static Client buildClient(RestClientConfig clientConfig) {
    ClientBuilder clientBuilder = ClientBuilder.newBuilder();

    if (!clientConfig.isDisabledSecureConnection()) {
        try {
            SSLContext sslContext = SSLContext.getInstance(TLSV1_2);
            sslContext.init(null, null, null);
            clientBuilder = clientBuilder.sslContext(sslContext);
        } catch (NoSuchAlgorithmException | KeyManagementException e) {
            throw new RuntimeException(format("Unable to find an SSL context for %s", TLSV1_2), e);
        }
    }

    Client client = clientBuilder.build();
    client.register(RestClientLoggingFilter.class);

    return client;
}
 
Example 10
Source File: BatchEEJAXRS2Client.java    From incubator-batchee with Apache License 2.0 5 votes vote down vote up
public BatchEEJAXRS2Client(final ClientConfiguration configuration) {
    final String url;
    if (configuration.getBaseUrl().endsWith("/")) {
        url = configuration.getBaseUrl() + BATCHEE_PATH;
    } else {
        url = configuration.getBaseUrl() + "/" + BATCHEE_PATH;
    }

    ClientBuilder builder = ClientBuilder.newBuilder();
    final ClientSslConfiguration ssl = configuration.getSsl();
    if (ssl != null) {
        if (ssl.getHostnameVerifier() != null) {
            builder = builder.hostnameVerifier(ssl.getHostnameVerifier());
        }
        if (ssl.getSslContext() != null) {
            builder = builder.sslContext(ssl.getSslContext());
        }
        if (ssl.getKeystore() != null) {
            builder.keyStore(ssl.getKeystore(), ssl.getKeystorePassword());
        }
    }

    WebTarget target = builder.build().target(url);
    if (configuration.getJsonProvider() != null) {
        target = target.register(configuration.getJsonProvider());
    }

    final ClientSecurity security = configuration.getSecurity();
    if (security != null) {
        if ("Basic".equalsIgnoreCase(security.getType())) {
            target = target.register(new Base64Filter(security.getUsername(), security.getPassword()));
        } else {
            throw new IllegalArgumentException("Security not supported: " + security.getType());
        }
    }

    this.target = target;
}
 
Example 11
Source File: InfluxDbClient.java    From tessera with Apache License 2.0 5 votes vote down vote up
public Response postMetrics() {
    MetricsEnquirer metricsEnquirer = new MetricsEnquirer(mbs);
    List<MBeanMetric> metrics = metricsEnquirer.getMBeanMetrics(appType);

    InfluxDbProtocolFormatter formatter = new InfluxDbProtocolFormatter();
    String formattedMetrics = formatter.format(metrics, tesseraAppUri, appType);

    ClientBuilder clientBuilder = ClientBuilder.newBuilder();

    if (influxConfig.isSsl()) {
        final SSLContextFactory sslContextFactory = ClientSSLContextFactory.create();
        final SSLContext sslContext =
                sslContextFactory.from(influxConfig.getServerUri().toString(), influxConfig.getSslConfig());

        clientBuilder.sslContext(sslContext);
    }

    Client client = clientBuilder.build();

    WebTarget influxTarget =
            client.target(influxConfig.getServerUri()).path("write").queryParam("db", influxConfig.getDbName());

    return influxTarget
            .request(MediaType.TEXT_PLAIN)
            .accept(MediaType.TEXT_PLAIN)
            .post(Entity.text(formattedMetrics));
}
 
Example 12
Source File: OAuth2AuthenticationResource.java    From gravitee-management-rest-api with Apache License 2.0 5 votes vote down vote up
@PostConstruct
public void initClient() throws NoSuchAlgorithmException, KeyManagementException {
    final boolean trustAllEnabled = environment.getProperty("security.trustAll", Boolean.class, false);
    final ClientBuilder builder = ClientBuilder.newBuilder();
    if (trustAllEnabled) {
        SSLContext sc = SSLContext.getInstance("TLSv1.2");
        sc.init(null, new TrustManager[]{new BlindTrustManager()}, null);
        builder.sslContext(sc);
    }

    this.client = builder.build();
}
 
Example 13
Source File: OAuth2AuthenticationResource.java    From gravitee-management-rest-api with Apache License 2.0 5 votes vote down vote up
@PostConstruct
public void initClient() throws NoSuchAlgorithmException, KeyManagementException {
    final boolean trustAllEnabled = environment.getProperty("security.trustAll", Boolean.class, false);
    final ClientBuilder builder = ClientBuilder.newBuilder();
    if (trustAllEnabled) {
        SSLContext sc = SSLContext.getInstance("TLSv1.2");
        sc.init(null, new TrustManager[]{new BlindTrustManager()}, null);
        builder.sslContext(sc);
    }

    this.client = builder.build();
}
 
Example 14
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 15
Source File: JAXRS20HttpsBookTest.java    From cxf with Apache License 2.0 4 votes vote down vote up
@Test
public void testGetBookSslContext() throws Exception {

    ClientBuilder builder = ClientBuilder.newBuilder();

    SSLContext sslContext = createSSLContext();
    builder.sslContext(sslContext);

    builder.hostnameVerifier(new AllowAllHostnameVerifier());


    Client client = builder.build();

    WebTarget target = client.target("https://localhost:" + PORT + "/bookstore/securebooks/123");
    Book b = target.request().accept(MediaType.APPLICATION_XML_TYPE).get(Book.class);
    assertEquals(123, b.getId());
}
 
Example 16
Source File: JerseyNiFiClient.java    From nifi with Apache License 2.0 4 votes vote down vote up
private JerseyNiFiClient(final Builder builder) {
    final NiFiClientConfig clientConfig = builder.getConfig();
    if (clientConfig == null) {
        throw new IllegalArgumentException("NiFiClientConfig cannot be null");
    }

    String baseUrl = clientConfig.getBaseUrl();
    if (StringUtils.isBlank(baseUrl)) {
        throw new IllegalArgumentException("Base URL cannot be blank");
    }

    if (baseUrl.endsWith("/")) {
        baseUrl = baseUrl.substring(0, baseUrl.length() - 1);
    }

    if (!baseUrl.endsWith(NIFI_CONTEXT)) {
        baseUrl = baseUrl + "/" + NIFI_CONTEXT;
    }

    try {
        new URI(baseUrl);
    } catch (final Exception e) {
        throw new IllegalArgumentException("Invalid base URL: " + e.getMessage(), e);
    }

    final SSLContext sslContext = clientConfig.getSslContext();
    final HostnameVerifier hostnameVerifier = clientConfig.getHostnameVerifier();

    final ClientBuilder clientBuilder = ClientBuilder.newBuilder();
    if (sslContext != null) {
        clientBuilder.sslContext(sslContext);
    }
    if (hostnameVerifier != null) {
        clientBuilder.hostnameVerifier(hostnameVerifier);
    }

    final int connectTimeout = clientConfig.getConnectTimeout() == null ? DEFAULT_CONNECT_TIMEOUT : clientConfig.getConnectTimeout();
    final int readTimeout = clientConfig.getReadTimeout() == null ? DEFAULT_READ_TIMEOUT : clientConfig.getReadTimeout();

    final ClientConfig jerseyClientConfig = new ClientConfig();
    jerseyClientConfig.property(ClientProperties.CONNECT_TIMEOUT, connectTimeout);
    jerseyClientConfig.property(ClientProperties.READ_TIMEOUT, readTimeout);
    jerseyClientConfig.register(jacksonJaxbJsonProvider());
    clientBuilder.withConfig(jerseyClientConfig);
    this.client = clientBuilder.build();

    this.baseTarget = client.target(baseUrl);
}
 
Example 17
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 18
Source File: JerseyNiFiRegistryClient.java    From nifi-registry with Apache License 2.0 4 votes vote down vote up
private JerseyNiFiRegistryClient(final NiFiRegistryClient.Builder builder) {
    final NiFiRegistryClientConfig registryClientConfig = builder.getConfig();
    if (registryClientConfig == null) {
        throw new IllegalArgumentException("NiFiRegistryClientConfig cannot be null");
    }

    String baseUrl = registryClientConfig.getBaseUrl();
    if (StringUtils.isBlank(baseUrl)) {
        throw new IllegalArgumentException("Base URL cannot be blank");
    }

    if (baseUrl.endsWith("/")) {
        baseUrl = baseUrl.substring(0, baseUrl.length() - 1);
    }

    if (!baseUrl.endsWith(NIFI_REGISTRY_CONTEXT)) {
        baseUrl = baseUrl + "/" + NIFI_REGISTRY_CONTEXT;
    }

    try {
        new URI(baseUrl);
    } catch (final Exception e) {
        throw new IllegalArgumentException("Invalid base URL: " + e.getMessage(), e);
    }

    final SSLContext sslContext = registryClientConfig.getSslContext();
    final HostnameVerifier hostnameVerifier = registryClientConfig.getHostnameVerifier();

    final ClientBuilder clientBuilder = ClientBuilder.newBuilder();
    if (sslContext != null) {
        clientBuilder.sslContext(sslContext);
    }
    if (hostnameVerifier != null) {
        clientBuilder.hostnameVerifier(hostnameVerifier);
    }

    final int connectTimeout = registryClientConfig.getConnectTimeout() == null ? DEFAULT_CONNECT_TIMEOUT : registryClientConfig.getConnectTimeout();
    final int readTimeout = registryClientConfig.getReadTimeout() == null ? DEFAULT_READ_TIMEOUT : registryClientConfig.getReadTimeout();

    final ClientConfig clientConfig = new ClientConfig();
    clientConfig.property(ClientProperties.CONNECT_TIMEOUT, connectTimeout);
    clientConfig.property(ClientProperties.READ_TIMEOUT, readTimeout);
    clientConfig.property(ClientProperties.REQUEST_ENTITY_PROCESSING, RequestEntityProcessing.CHUNKED);
    clientConfig.register(jacksonJaxbJsonProvider());
    clientBuilder.withConfig(clientConfig);

    this.client = clientBuilder
            .register(MultiPartFeature.class)
            .build();

    this.baseTarget = client.target(baseUrl);
    this.bucketClient = new JerseyBucketClient(baseTarget);
    this.flowClient = new JerseyFlowClient(baseTarget);
    this.flowSnapshotClient = new JerseyFlowSnapshotClient(baseTarget);
    this.itemsClient = new JerseyItemsClient(baseTarget);
}
 
Example 19
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 20
Source File: JerseyExtendedNiFiRegistryClient.java    From nifi with Apache License 2.0 4 votes vote down vote up
public JerseyExtendedNiFiRegistryClient(final NiFiRegistryClient delegate, final NiFiRegistryClientConfig registryClientConfig) {
    this.delegate = delegate;

    // Copied from JerseyNiFiRegistryClient!
    if (registryClientConfig == null) {
        throw new IllegalArgumentException("NiFiRegistryClientConfig cannot be null");
    }

    String baseUrl = registryClientConfig.getBaseUrl();
    if (StringUtils.isBlank(baseUrl)) {
        throw new IllegalArgumentException("Base URL cannot be blank");
    }

    if (baseUrl.endsWith("/")) {
        baseUrl = baseUrl.substring(0, baseUrl.length() - 1);
    }

    if (!baseUrl.endsWith(NIFI_REGISTRY_CONTEXT)) {
        baseUrl = baseUrl + "/" + NIFI_REGISTRY_CONTEXT;
    }

    try {
        new URI(baseUrl);
    } catch (final Exception e) {
        throw new IllegalArgumentException("Invalid base URL: " + e.getMessage(), e);
    }

    final SSLContext sslContext = registryClientConfig.getSslContext();
    final HostnameVerifier hostnameVerifier = registryClientConfig.getHostnameVerifier();

    final ClientBuilder clientBuilder = ClientBuilder.newBuilder();
    if (sslContext != null) {
        clientBuilder.sslContext(sslContext);
    }
    if (hostnameVerifier != null) {
        clientBuilder.hostnameVerifier(hostnameVerifier);
    }

    final int connectTimeout = registryClientConfig.getConnectTimeout() == null ? DEFAULT_CONNECT_TIMEOUT : registryClientConfig.getConnectTimeout();
    final int readTimeout = registryClientConfig.getReadTimeout() == null ? DEFAULT_READ_TIMEOUT : registryClientConfig.getReadTimeout();

    final ClientConfig clientConfig = new ClientConfig();
    clientConfig.property(ClientProperties.CONNECT_TIMEOUT, connectTimeout);
    clientConfig.property(ClientProperties.READ_TIMEOUT, readTimeout);
    clientConfig.property(ClientProperties.REQUEST_ENTITY_PROCESSING, RequestEntityProcessing.CHUNKED);
    clientConfig.register(jacksonJaxbJsonProvider());
    clientBuilder.withConfig(clientConfig);

    this.client = clientBuilder
            .register(MultiPartFeature.class)
            .build();

    this.baseTarget = client.target(baseUrl);

    this.tenantsClient = new JerseyTenantsClient(baseTarget);
    this.policiesClient = new JerseyPoliciesClient(baseTarget);
}