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

The following examples show how to use javax.ws.rs.client.ClientBuilder#register() . 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: GitLabApiClient.java    From gitlab4j-api with MIT License 6 votes vote down vote up
protected Client createApiClient() {

        // Explicitly use an instance of the JerseyClientBuilder, this allows this
        // library to work when both Jersey and Resteasy are present
        ClientBuilder clientBuilder = new JerseyClientBuilder().withConfig(clientConfig);

        // Register JacksonJson as the ObjectMapper provider.
        clientBuilder.register(JacksonJson.class);

        if (ignoreCertificateErrors) {
            clientBuilder.sslContext(openSslContext).hostnameVerifier(openHostnameVerifier);
        }

        apiClient = clientBuilder.build();
        return (apiClient);
    }
 
Example 2
Source File: HttpClientCommon.java    From datacollector with Apache License 2.0 6 votes vote down vote up
private void configureCompression(ClientBuilder clientBuilder) {
  if (jerseyClientConfig.httpCompression != null) {
    switch (jerseyClientConfig.httpCompression) {
      case SNAPPY:
        clientBuilder.register(SnappyEncoder.class);
        break;
      case GZIP:
        clientBuilder.register(GZipEncoder.class);
        break;
      case NONE:
      default:
        break;
    }
    clientBuilder.register(EncodingFilter.class);
  }
}
 
Example 3
Source File: JerseyClientUtil.java    From datacollector with Apache License 2.0 6 votes vote down vote up
public static AccessToken configureOAuth1(
  String consumerKey,
  String consumerSecret,
  String token,
  String tokenSecret,
  ClientBuilder clientBuilder
) {
  ConsumerCredentials consumerCredentials = new ConsumerCredentials(consumerKey, consumerSecret);

  AccessToken accessToken = new AccessToken(token, tokenSecret);
  Feature feature = OAuth1ClientSupport.builder(consumerCredentials)
      .feature()
      .accessToken(accessToken)
      .build();
  clientBuilder.register(feature);

  return accessToken;
}
 
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: JerseyClientUtil.java    From datacollector with Apache License 2.0 6 votes vote down vote up
public static void configurePasswordAuth(
    AuthenticationType authType,
    String username,
    String password,
    ClientBuilder clientBuilder
) {
  if (authType == AuthenticationType.BASIC) {
    clientBuilder.register(HttpAuthenticationFeature.basic(username, password));
  }

  if (authType == AuthenticationType.DIGEST) {
    clientBuilder.register(HttpAuthenticationFeature.digest(username, password));
  }

  if (authType == AuthenticationType.UNIVERSAL) {
    clientBuilder.register(HttpAuthenticationFeature.universal(username, password));
  }
}
 
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: 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 8
Source File: Keycloak.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private static Client newRestEasyClient(ResteasyJackson2Provider customJacksonProvider, SSLContext sslContext, boolean disableTrustManager) {
    ClientBuilder clientBuilder = ClientBuilderWrapper.create(sslContext, disableTrustManager);

    if (customJacksonProvider != null) {
        clientBuilder.register(customJacksonProvider, 100);
    } else {
        clientBuilder.register(JacksonProvider.class, 100);
    }

    return clientBuilder.build();
}
 
Example 9
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 10
Source File: VespaClientBuilderFactory.java    From vespa with Apache License 2.0 5 votes vote down vote up
private void setSslConfiguration(ClientBuilder builder) {
    if (tlsContext != null) {
        builder.sslContext(tlsContext.context());
        builder.hostnameVerifier((hostname, sslSession) -> true); // disable hostname verification
        if (mixedMode != MixedMode.PLAINTEXT_CLIENT_MIXED_SERVER) {
            builder.register(new UriRewritingRequestFilter());
        }
    }
}
 
Example 11
Source File: IncomingWebhookClient.java    From mattermost4j with Apache License 2.0 5 votes vote down vote up
protected Client createClient(Level clientLogLevel) {
  ClientBuilder builder = ClientBuilder.newBuilder().register(MattermostModelMapperProvider.class)
      .register(JacksonFeature.class);
  if (clientLogLevel != null) {
    builder.register(new LoggingFeature(Logger.getLogger(getClass().getName()), clientLogLevel,
        Verbosity.PAYLOAD_ANY, 1000));
  }
  return builder.build();
}
 
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: BulkDataClient.java    From FHIR with Apache License 2.0 5 votes vote down vote up
public WebTarget getWebTarget(String baseURL) throws Exception {
    ClientBuilder cb = ClientBuilder.newBuilder();

    String trustStore = properties.get(BulkDataConfigUtil.BATCH_TRUSTSTORE);
    String trustStorePass = properties.get(BulkDataConfigUtil.BATCH_TRUSTSTORE_PASS);
    cb.keyStore(loadKeyStoreFile(trustStore, trustStorePass), trustStorePass);
    cb.trustStore(loadKeyStoreFile(trustStore, trustStorePass));

    String user = properties.get(BulkDataConfigUtil.BATCH_USER);
    String pass = properties.get(BulkDataConfigUtil.BATCH_USER_PASS);

    cb = cb.register(new FHIRBasicAuthenticator(user, pass));

    return cb.build().target(baseURL);
}
 
Example 14
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;
}
 
Example 15
Source File: HttpClientCommon.java    From datacollector with Apache License 2.0 4 votes vote down vote up
private void configureCompression(ClientBuilder clientBuilder) {
  clientBuilder.register(GZipEncoder.class);
  clientBuilder.register(EncodingFilter.class);
}
 
Example 16
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 17
Source File: JaxRsAgentIntercept.java    From java-specialagent with Apache License 2.0 4 votes vote down vote up
public static void enter(final Object thiz) {
  final ClientBuilder builder = (ClientBuilder)thiz;
  builder.register(ClientTracingFeature.class);
}