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

The following examples show how to use javax.ws.rs.client.ClientBuilder#build() . 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: 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 3
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 4
Source File: MattermostClient.java    From mattermost4j with Apache License 2.0 6 votes vote down vote up
protected Client buildClient(Consumer<ClientBuilder> httpClientConfig) {
  ClientBuilder builder = ClientBuilder.newBuilder()
      .register(new MattermostModelMapperProvider(ignoreUnknownProperties))
      .register(JacksonFeature.class).register(MultiPartFeature.class)
      // needs for PUT request with null entity
      // (/commands/{command_id}/regen_token)
      .property(ClientProperties.SUPPRESS_HTTP_COMPLIANCE_VALIDATION, true);
  if (clientLogLevel != null) {
    builder.register(new LoggingFeature(Logger.getLogger(getClass().getName()), clientLogLevel,
        Verbosity.PAYLOAD_ANY, 100000));
  }

  httpClientConfig.accept(builder);

  return builder.build();
}
 
Example 5
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 6
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 7
Source File: TestHelper.java    From aries-jax-rs-whiteboard with Apache License 2.0 5 votes vote down vote up
protected Client createClient() {
    ClientBuilder clientBuilder;

    try {
        clientBuilder = _clientBuilderTracker.waitForService(5000);

        return clientBuilder.build();
    }
    catch (InterruptedException ie) {
        throw new RuntimeException(ie);
    }
}
 
Example 8
Source File: HttpClient.java    From pandaria with MIT License 5 votes vote down vote up
private HttpClient(HttpContext context) {
    ClientBuilder builder = ClientBuilder.newBuilder()
            .property(SET_METHOD_WORKAROUND, true)
            .property(SUPPRESS_HTTP_COMPLIANCE_VALIDATION, true)
            .register(MultiPartFeature.class)
            .register(logAny())
            .sslContext(context.isHttpSslVerify() ? getDefaultContext() : emptyContext());

    if (!context.isHttpSslVerify()) {
        builder.hostnameVerifier(trustAll());
    }

    this.client = builder.build();
    this.context = context;
}
 
Example 9
Source File: RestClient.java    From ats-framework with Apache License 2.0 5 votes vote down vote up
private void createClient( ClientBuilder newClientBuilder ) {

        client = newClientBuilder.build();
        if (requestFilterNeedsRegistration && !requestFilterAlreadyRegistered) {
            RequestFilter requestFilter = new RequestFilter();
            client.register(requestFilter);
            requestFilterNeedsRegistration = false;
            requestFilterAlreadyRegistered = true;
        }
    }
 
Example 10
Source File: TestHelper.java    From aries-jax-rs-whiteboard with Apache License 2.0 5 votes vote down vote up
protected Client createClient() {
    ClientBuilder clientBuilder;

    try {
        clientBuilder = _clientBuilderTracker.waitForService(5000);

        return clientBuilder.build();
    }
    catch (InterruptedException ie) {
        throw new RuntimeException(ie);
    }
}
 
Example 11
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 12
Source File: ClientSetup.java    From component-runtime with Apache License 2.0 5 votes vote down vote up
@Produces
@ApplicationScoped
@Http(Http.Type.TALEND_COMPONENT_KIT)
public Client serverClient(@Http(Http.Type.TALEND_COMPONENT_KIT) final ExecutorService executor) {
    ClientBuilder builder = createClient(executor, serverKeystoreLocation, serverKeystoreType,
            serverKeystorePassword, serverTruststoreType, serverHostnames);
    if (serverToken.isPresent()) {
        final String token = serverToken.get();
        builder = builder
                .register((ClientRequestFilter) requestContext -> requestContext
                        .getHeaders()
                        .putSingle(HttpHeaders.AUTHORIZATION, token));
    }
    return builder.build();
}
 
Example 13
Source File: FHIRClientImpl.java    From FHIR with Apache License 2.0 5 votes vote down vote up
@Override
public WebTarget getWebTarget(String baseURL) throws Exception {
    ClientBuilder cb =
            ClientBuilder.newBuilder().register(new FHIRProvider(RuntimeType.CLIENT)).register(new FHIRJsonProvider(RuntimeType.CLIENT)).keyStore(getKeyStore(), getKeyStoreKeyPassword());

    KeyStore ts = getTrustStore();

    if (ts != null) {
        cb = cb.trustStore(ts);
    }
    Client client = cb.build();
    return client.target(baseURL);
}
 
Example 14
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 15
Source File: JaxRSClientContainer.java    From JaxRSProviders with Apache License 2.0 5 votes vote down vote up
protected Client createJaxRSClient(Configuration configuration, ClassLoader cl) throws ECFException {
	ClientBuilder cb = ClientBuilder.newBuilder();
	if (configuration != null)
		cb.withConfig(configuration);
	cb.register(new ObjectMapperContextResolver(), ContextResolver.class);
	cb.register(new JaxRSClientJacksonFeature(getRegistration(), cl), jacksonPriority);
	return cb.build();
}
 
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: LibertyRestEndpoint.java    From microservices-traffic-management-using-istio with Apache License 2.0 4 votes vote down vote up
private JsonObject getRatings(Cookie user, String xreq, String xtraceid, String xspanid,
                              String xparentspanid, String xsampled, String xflags, String xotspan){
  ClientBuilder cb = ClientBuilder.newBuilder();
  String timeout = star_color.equals("black") ? "10000" : "2500";
  cb.property("com.ibm.ws.jaxrs.client.connection.timeout", timeout);
  cb.property("com.ibm.ws.jaxrs.client.receive.timeout", timeout);
  Client client = cb.build();
  WebTarget ratingsTarget = client.target(ratings_service);
  Invocation.Builder builder = ratingsTarget.request(MediaType.APPLICATION_JSON);
  if(xreq!=null) {
    builder.header("x-request-id",xreq);
  }
  if(xtraceid!=null) {
    builder.header("x-b3-traceid",xtraceid);
  }
  if(xspanid!=null) {
    builder.header("x-b3-spanid",xspanid);
  }
  if(xparentspanid!=null) {
    builder.header("x-b3-parentspanid",xparentspanid);
  }
  if(xsampled!=null) {
    builder.header("x-b3-sampled",xsampled);
  }
  if(xflags!=null) {
    builder.header("x-b3-flags",xflags);
  }
  if(xotspan!=null) {
    builder.header("x-ot-span-context",xotspan);
  }
  if(user!=null) {
    builder.cookie(user);
  }
  Response r = builder.get();
  int statusCode = r.getStatusInfo().getStatusCode();
  if (statusCode == Response.Status.OK.getStatusCode() ) {
    StringReader stringReader = new StringReader(r.readEntity(String.class));
    try (JsonReader jsonReader = Json.createReader(stringReader)) {
       JsonObject j = jsonReader.readObject();
       JsonObjectBuilder jb = Json.createObjectBuilder();
       for(String key : j.keySet()){
         int count = j.getInt(key);
         String stars = "<font color=\""+ star_color +"\">";
         for(int i=0; i<count; i++){
           stars += "<span class=\"glyphicon glyphicon-star\"></span>";
         }
         stars += "</font>";
         if(count<5){
           for(int i=0; i<(5-count); i++){
             stars += "<span class=\"glyphicon glyphicon-star-empty\"></span>";
           }
         }
         jb.add(key,stars);
       }
       JsonObject result = jb.build();
       return result;
    }
  }else{
    System.out.println("Error: unable to contact "+ratings_service+" got status of "+statusCode);
    return null;
  }
}
 
Example 18
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 19
Source File: DatabricksJobExecutor.java    From datacollector with Apache License 2.0 4 votes vote down vote up
@Override
public List<Stage.ConfigIssue> init() {
  List<Stage.ConfigIssue> issues = new ArrayList<>();

  Optional
      .ofNullable(databricksConfigBean.init(getContext(), PREFIX))
      .ifPresent(issues::addAll);

  baseUrl = databricksConfigBean.baseUrl.endsWith("/") ?
      databricksConfigBean.baseUrl.substring(0, databricksConfigBean.baseUrl.length() - 1) :
      databricksConfigBean.baseUrl;

  HttpProxyConfigBean proxyConf = databricksConfigBean.proxyConfigBean;
  String proxyUsername = null;
  String proxyPassword = null;
  if(databricksConfigBean.useProxy) {
    proxyUsername = proxyConf.resolveUsername(getContext(), "PROXY", "conf.proxyConfigBean.", issues);
    proxyPassword = proxyConf.resolvePassword(getContext(), "PROXY", "conf.proxyConfigBean.", issues);
  }

  if(issues.isEmpty()) {
    ClientConfig clientConfig = new ClientConfig()
        .property(ClientProperties.ASYNC_THREADPOOL_SIZE, 1)
        .property(ClientProperties.REQUEST_ENTITY_PROCESSING, RequestEntityProcessing.BUFFERED);

    if (databricksConfigBean.useProxy) {
      clientConfig = clientConfig.connectorProvider(new GrizzlyConnectorProvider(new GrizzlyClientCustomizer(
          true,
          proxyUsername,
          proxyPassword
      )));
    }

    ClientBuilder builder = getClientBuilder()
        .withConfig(clientConfig)
        .register(JacksonJsonProvider.class);
    HttpAuthenticationFeature auth = null;
    if (databricksConfigBean.credentialsConfigBean.credentialType == CredentialType.PASSWORD) {
      String username = databricksConfigBean.credentialsConfigBean.resolveUsername(
          getContext(),
          "CREDENTIALS",
          "conf.credentialsConfigBean.",
          issues
      );
      String password = databricksConfigBean.credentialsConfigBean.resolvePassword(
          getContext(),
          "CREDENTIALS",
          "conf.credentialsConfigBean.",
          issues
      );
      auth = HttpAuthenticationFeature.basic(username, password);
      builder.register(auth);
    } else {
      String token = databricksConfigBean.credentialsConfigBean.resolveToken(
          getContext(),
          "CREDENTIALS",
          "conf.credentialsConfigBean.",
          issues
      );

      builder.register((ClientRequestFilter) requestContext ->
          requestContext.getHeaders().add("Authorization", "Bearer " + token)
      );
    }

    JerseyClientUtil.configureSslContext(databricksConfigBean.tlsConfigBean, builder);

    if(databricksConfigBean.useProxy) {
      JerseyClientUtil.configureProxy(
          proxyConf.uri,
          proxyUsername,
          proxyPassword,
          builder
      );
    }

    client = builder.build();
    validateWithDatabricks(getContext(), issues);
  }
  return issues;
}
 
Example 20
Source File: FHIRClientImpl.java    From FHIR with Apache License 2.0 4 votes vote down vote up
/**
 * Retrieves a jax-rs Client from the ClientBuilder object. The Client instance is created if necessary.
 */
protected synchronized Client getClient() throws Exception {
    if (client == null) {
        ClientBuilder cb = ClientBuilder.newBuilder()
                .register(new FHIRProvider(RuntimeType.CLIENT))
                .register(new FHIRJsonProvider(RuntimeType.CLIENT))
                .register(new FHIRJsonPatchProvider(RuntimeType.CLIENT));

        // Add support for basic auth if enabled.
        if (isBasicAuthEnabled()) {
            cb = cb.register(new FHIRBasicAuthenticator(getBasicAuthUsername(), getBasicAuthPassword()));
        }

        // Add support for OAuth 2.0 if enabled.
        if (isOAuth2Enabled()) {
            cb = cb.register(new FHIROAuth2Authenticator(getOAuth2AccessToken()));
        }

        // If using oAuth 2.0 or clientauth, then we need to attach our Keystore.
        if (isOAuth2Enabled() || isClientAuthEnabled()) {
            cb = cb.keyStore(getKeyStore(), getKeyStoreKeyPassword());
        }

        // If using oAuth 2.0 or clientauth or an https endpoint, then we need to attach our Truststore.
        KeyStore ks = getTrustStore();
        if (ks != null) {
            cb = cb.trustStore(ks);
        }

        // Add a hostname verifier if we're using an ssl transport.
        if (usingSSLTransport() && !isHostnameVerificationEnabled()) {
            cb = cb.hostnameVerifier(new HostnameVerifier() {

                @Override
                public boolean verify(String s, SSLSession sslSession) {
                    return true;
                }
            });
        }

        // Set the http client's receive timeout setting
        cb.property("http.receive.timeout", getHttpTimeout()); // defaults to 60s

        // true: If need, tell Apache CXF to use the Async HTTP conduit for PATCH operation as the
        // default HTTP conduit does not support PATCH
        // false(default): To avoid the http async client time out issue (http://mail-archives.apache.org
        // /mod_mbox/hc-dev/201909.mbox/%[email protected]%3E),
        // please set this to false.
        cb.property("use.async.http.conduit", false);

        // Add request/response logging if enabled.
        if (isLoggingEnabled()) {
            cb.register(LoggingFeature.class);
        }

        // Save off our cached Client instance.
        client = cb.build();
    }
    return client;
}