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

The following examples show how to use javax.ws.rs.client.ClientBuilder#newBuilder() . 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: SchemaRegistryRestAPIClient.java    From apicurio-registry with Apache License 2.0 6 votes vote down vote up
private static Client getJAXRSClient(boolean skipSSLValidation) throws KeyManagementException, NoSuchAlgorithmException {
    ClientBuilder cb = ClientBuilder.newBuilder();

    cb.connectTimeout(10, TimeUnit.SECONDS);

    Client newClient;
    if (skipSSLValidation) {
        SSLContext nullSSLContext = SSLContext.getInstance("TLSv1.2");
        nullSSLContext.init(null, nullTrustManager, null);
        cb.hostnameVerifier(NullHostnameVerifier.INSTANCE)
          .sslContext(nullSSLContext);

        newClient = cb.build();
    } else {
        newClient = cb.build();
    }

    newClient.register(JacksonJsonProvider.class);

    return newClient;
}
 
Example 2
Source File: ApiClient.java    From openapi-generator with Apache License 2.0 6 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 3
Source File: ClientFactory.java    From tessera with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a new client, which may or may not be SSL enabled or a unix socket enabled depending on the
 * configuration.
 *
 * @param config
 * @return
 * @see Client
 */
public Client buildFrom(final ServerConfig config) {

    final ClientBuilder clientBuilder = ClientBuilder.newBuilder();

    final long pollInterval = new IntervalPropertyHelper(config.getProperties()).partyInfoInterval();
    final long timeout = Math.round(Math.ceil(pollInterval * 0.75));
    clientBuilder.connectTimeout(timeout, TimeUnit.MILLISECONDS);
    clientBuilder.readTimeout(timeout, TimeUnit.MILLISECONDS);

    if (config.isUnixSocket()) {
        Configuration clientConfig = createUnixServerSocketConfig();
        URI unixfile = config.getServerUri();
        return ClientBuilder.newClient(clientConfig).property("unixfile", unixfile);

    } else if (config.isSsl()) {
        final SSLContext sslContext =
                sslContextFactory.from(config.getServerUri().toString(), config.getSslConfig());
        return clientBuilder.sslContext(sslContext).build();
    } else {
        return clientBuilder.build();
    }
}
 
Example 4
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 5
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 6
Source File: JAXRS20HttpsBookTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetBook() throws Exception {

    ClientBuilder builder = ClientBuilder.newBuilder();

    try (InputStream keystore = ClassLoaderUtils.getResourceAsStream("keys/Truststore.jks", this.getClass())) {
        KeyStore trustStore = loadStore(keystore, "password");
        builder.trustStore(trustStore);
    }
    builder.hostnameVerifier(new AllowAllHostnameVerifier());

    try (InputStream keystore = ClassLoaderUtils.getResourceAsStream("keys/Morpit.jks", this.getClass())) {
        KeyStore keyStore = loadStore(keystore, "password");
        builder.keyStore(keyStore, "password");
    }

    Client client = builder.build();
    client.register(new LoggingFeature());

    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 7
Source File: Connection.java    From ecs-cf-service-broker with Apache License 2.0 5 votes vote down vote up
private Client buildJerseyClient() throws EcsManagementClientException {
    ClientBuilder builder;
    if (certificate != null) {
        // Disable host name verification. Should be able to configure the
        // ECS certificate with the correct host name to avoid this.
        HostnameVerifier hostnameVerifier = getHostnameVerifier();
        HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier);
        builder = ClientBuilder.newBuilder()
                .register(hostnameVerifier);
        builder.sslContext(getSSLContext());
    } else {
        builder = ClientBuilder.newBuilder();
    }
    return builder.build();
}
 
Example 8
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 9
Source File: ClientBase.java    From pnc with Apache License 2.0 5 votes vote down vote up
protected ClientBase(Configuration configuration, Class<T> iface) {
    this.iface = iface;

    ApacheHttpClient43EngineWithRetry engine = new ApacheHttpClient43EngineWithRetry();
    // allow redirects for NCL-3766
    engine.setFollowRedirects(true);

    this.configuration = configuration;

    ResteasyClientBuilder clientBuilder = (ResteasyClientBuilder) ClientBuilder.newBuilder();
    client = clientBuilder.httpEngine(engine).build();
    client.register(ResteasyJackson2ProviderWithDateISO8601.class);
    client.register(new MdcToHeadersFilter(configuration.getMdcToHeadersMappings()));
    client.register(RequestLoggingFilter.class);
    target = client.target(
            configuration.getProtocol() + "://" + configuration.getHost() + ":" + configuration.getPort()
                    + BASE_PATH);
    Configuration.BasicAuth basicAuth = configuration.getBasicAuth();

    if (basicAuth != null) {
        target.register(new BasicAuthentication(basicAuth.getUsername(), basicAuth.getPassword()));
    } else {
        if (configuration.getBearerTokenSupplier() != null) {
            bearerAuthentication = new BearerAuthentication(configuration.getBearerTokenSupplier().get());
            target.register(bearerAuthentication);
        } else {
            String bearerToken = configuration.getBearerToken();
            if (bearerToken != null && !bearerToken.equals("")) {
                bearerAuthentication = new BearerAuthentication(bearerToken);
                target.register(bearerAuthentication);
            }
        }
    }

    proxy = ProxyBuilder.builder(iface, target).build();
}
 
Example 10
Source File: RestInterfaceFactory.java    From EDDI with Apache License 2.0 5 votes vote down vote up
private ResteasyClient getResteasyClient(String targetServerUri) {
    ResteasyClient client = clients.get(targetServerUri);
    if (client == null) {

        JettyClientEngine engine = new JettyClientEngine(httpClient);
        ResteasyClientBuilder clientBuilder = (ResteasyClientBuilder) ClientBuilder.newBuilder();
        clientBuilder.httpEngine(engine);

        client = clientBuilder.build();
        clients.put(targetServerUri, client);
    }

    return client;
}
 
Example 11
Source File: OaiCatalog.java    From proarc with GNU General Public License v3.0 5 votes vote down vote up
private Client createClient() {
    ClientBuilder builder = ClientBuilder.newBuilder();
    if (user != null) {
        builder.register(HttpAuthenticationFeature.basic(user, password));
    }
    if (LOG.isLoggable(Level.FINEST)) {
        builder.register(new LoggingFeature(LOG));
    }
    Client client = builder
            .property(ClientProperties.FOLLOW_REDIRECTS, true)
            .property(ClientProperties.CONNECT_TIMEOUT, 2 * 60 * 1000) // 2 min
            .property(ClientProperties.READ_TIMEOUT, 1 * 60 * 1000) // 1 min
            .build();
    return client;
}
 
Example 12
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 13
Source File: DatabricksJobExecutor.java    From datacollector with Apache License 2.0 4 votes vote down vote up
@VisibleForTesting
protected ClientBuilder getClientBuilder() {
  return ClientBuilder.newBuilder();
}
 
Example 14
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);
}
 
Example 15
Source File: WebUtils.java    From nifi with Apache License 2.0 4 votes vote down vote up
/**
 * A helper method for creating clients. The client will be created using
 * the given configuration and security context. Additionally, the client
 * will be automatically configured for JSON serialization/deserialization.
 *
 * @param config client configuration
 * @param ctx    security context, which may be null for non-secure client
 *               creation
 * @return a Client instance
 */
private static Client createClientHelper(final ClientConfig config, final SSLContext ctx) {

    ClientBuilder clientBuilder = ClientBuilder.newBuilder();

    if (config != null) {
        clientBuilder = clientBuilder.withConfig(config);
    }

    if (ctx != null) {

        // Apache http DefaultHostnameVerifier that checks subject alternative names against the hostname of the URI
        clientBuilder = clientBuilder.sslContext(ctx).hostnameVerifier(new DefaultHostnameVerifier());
    }

    clientBuilder = clientBuilder.register(ObjectMapperResolver.class).register(JacksonJaxbJsonProvider.class);

    return clientBuilder.build();

}
 
Example 16
Source File: ZMSClientExt.java    From athenz with Apache License 2.0 4 votes vote down vote up
@Override
ClientBuilder getClientBuilder() {
    return (clientBuilder == null) ? ClientBuilder.newBuilder() : clientBuilder;
}
 
Example 17
Source File: ZMSClient.java    From athenz with Apache License 2.0 4 votes vote down vote up
ClientBuilder getClientBuilder() {
    return ClientBuilder.newBuilder();
}
 
Example 18
Source File: TestClientRegistrarWebServices.java    From microprofile-opentracing with Apache License 2.0 4 votes vote down vote up
private Client instrumentedClientExecutor() {
    ClientBuilder clientBuilder = ClientBuilder.newBuilder();
    ClientTracingRegistrar.configure(clientBuilder, Executors.newFixedThreadPool(10));
    return clientBuilder.build();
}
 
Example 19
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 20
Source File: DefaultPowerBiConnection.java    From powerbi-rest-java with MIT License 2 votes vote down vote up
/**
 * Constructor.
 *
 * @param authenticator the {@see Authenticator} instance to use for authentication.
 * @param executor      the {@see ExecutorService} to use for background processing.
 */
public DefaultPowerBiConnection(Authenticator authenticator, ExecutorService executor) {
    this.authenticator = authenticator;
    this.executor = executor;
    this.clientBuilder = ClientBuilder.newBuilder();
}