Java Code Examples for org.glassfish.jersey.client.ClientConfig#connectorProvider()

The following examples show how to use org.glassfish.jersey.client.ClientConfig#connectorProvider() . 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: JerseyServerIT.java    From tessera with Apache License 2.0 6 votes vote down vote up
@Test
public void param() {
    // URL.setURLStreamHandlerFactory(new UnixSocketURLStreamHandlerFactory());
    ClientConfig config = new ClientConfig();
    config.connectorProvider(new JerseyUnixSocketConnectorProvider());

    Response result =
        newClient(unixfile)
            .target(unixfile)
            .path("param")
            .queryParam("queryParam", "QueryParamValue")
            .request()
            .header("headerParam", "HeaderParamValue")
            .get();

    assertThat(result.getStatus()).isEqualTo(200);
}
 
Example 2
Source File: JerseyServerIT.java    From tessera with Apache License 2.0 6 votes vote down vote up
@Test
public void raw() {

    ClientConfig config = new ClientConfig();
    config.connectorProvider(new JerseyUnixSocketConnectorProvider());
    Response result =
        newClient(unixfile)
            .target(unixfile)
            .path("sendraw")
            .request()
            .header("c11n-from", "/+UuD63zItL1EbjxkKUljMgG8Z1w0AJ8pNOR4iq2yQc=")
            .header("c11n-to", "yGcjkFyZklTTXrn8+WIkYwicA2EGBn9wZFkctAad4X0=")
            .post(Entity.entity("PAYLOAD".getBytes(), MediaType.APPLICATION_OCTET_STREAM_TYPE));

    assertThat(result.getStatus()).isEqualTo(201);
}
 
Example 3
Source File: ParaClient.java    From para with Apache License 2.0 6 votes vote down vote up
/**
 * Default constructor.
 * @param accessKey app access key
 * @param secretKey app secret key
 */
public ParaClient(String accessKey, String secretKey) {
	this.accessKey = accessKey;
	this.secretKey = secretKey;
	if (StringUtils.length(secretKey) < 6) {
		logger.warn("Secret key appears to be invalid. Make sure you call 'signIn()' first.");
	}
	this.throwExceptionOnHTTPError = false;
	ObjectMapper mapper = ParaObjectUtils.getJsonMapper();
	mapper.setSerializationInclusion(JsonInclude.Include.USE_DEFAULTS);
	ClientConfig clientConfig = new ClientConfig();
	clientConfig.register(GenericExceptionMapper.class);
	clientConfig.register(new JacksonJsonProvider(mapper));
	clientConfig.connectorProvider(new HttpUrlConnectorProvider().useSetMethodWorkaround());
	SSLContext sslContext = SslConfigurator.newInstance().createSSLContext();
	apiClient = ClientBuilder.newBuilder().
			sslContext(sslContext).
			withConfig(clientConfig).build();
}
 
Example 4
Source File: DockerRegistry.java    From carnotzet with Apache License 2.0 6 votes vote down vote up
private WebTarget getRegistryWebTarget(ImageRef imageRef) {
	if (!webTargets.containsKey(imageRef.getRegistryUrl())) {

		ObjectMapper mapper = new ObjectMapper();
		mapper.registerModule(new JavaTimeModule());

		ClientConfig clientCOnfig = new ClientConfig();
		clientCOnfig.connectorProvider(new HttpUrlConnectorProvider());

		// TODO : This client doesn't handle mandatory Oauth2 Bearer token imposed by some registries implementations (ie : docker hub)
		Client client = ClientBuilder.newClient(clientCOnfig)
				.register(new JacksonJaxbJsonProvider(mapper, new Annotations[] {Annotations.JACKSON}))
				.register(JacksonFeature.class);
		String auth = config.getAuthFor(imageRef.getRegistryName());
		if (auth != null) {
			String[] credentials = new String(Base64.getDecoder().decode(auth), StandardCharsets.UTF_8).split(":");
			client.register(HttpAuthenticationFeature.basicBuilder().credentials(credentials[0], credentials[1]));
		}
		WebTarget webTarget = client.target(imageRef.getRegistryUrl());
		webTargets.put(imageRef.getRegistryUrl(), webTarget);
	}
	return webTargets.get(imageRef.getRegistryUrl());
}
 
Example 5
Source File: RESTClient.java    From TeaStore with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new REST Client for an entity of Type T. The client interacts with a Server providing
 * CRUD functionalities
 * @param hostURL The url of the host. Common Pattern: "http://[hostname]:[port]/servicename/"
 * @param application The name of the rest application, usually {@link #DEFAULT_REST_APPLICATION} "rest" (no "/"!)
 * @param endpoint The name of the rest endpoint, typically the all lower case name of the entity in a plural form.
 * E.g., "products" for the entity "Product" (no "/"!)
 * @param entityClass Classtype of the Entitiy to send/receive. Note that the use of this Class type is
 * 			open for interpretation by the inheriting REST clients.
 */
public RESTClient(String hostURL, String application, String endpoint, final Class<T> entityClass) {
	if (!hostURL.endsWith("/")) {
		hostURL += "/";
	}
	if (!hostURL.contains("://")) {
		hostURL = "http://" + hostURL;
	}
	ClientConfig config = new ClientConfig();
	config.property(ClientProperties.CONNECT_TIMEOUT, connectTimeout);
	config.property(ClientProperties.READ_TIMEOUT, readTimeout);
	//PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();
    //connectionManager.setMaxTotal(MAX_POOL_SIZE);
    //connectionManager.setDefaultMaxPerRoute(DEFAULT_POOL_SIZE);
    //config.property(ApacheClientProperties.CONNECTION_MANAGER, connectionManager);
	config.connectorProvider(new GrizzlyConnectorProvider());
	client = ClientBuilder.newClient(config);
	service = client.target(UriBuilder.fromUri(hostURL).build());
	applicationURI = application;
	endpointURI = endpoint;
	this.entityClass = entityClass;
	
	parameterizedGenericType = new ParameterizedType() {
	        public Type[] getActualTypeArguments() {
	            return new Type[] { entityClass };
	        }

	        public Type getRawType() {
	            return List.class;
	        }

	        public Type getOwnerType() {
	            return List.class;
	        }
	    };
	    genericListType = new GenericType<List<T>>(parameterizedGenericType) { };
}
 
Example 6
Source File: RxJerseyClientFeature.java    From rx-jersey with MIT License 5 votes vote down vote up
private Client createClient() {
    int cores = Runtime.getRuntime().availableProcessors();
    ClientConfig config = new ClientConfig();
    config.connectorProvider(new GrizzlyConnectorProvider());
    config.property(ClientProperties.ASYNC_THREADPOOL_SIZE, cores);
    config.register(RxObservableInvokerProvider.class);

    return ClientBuilder.newClient(config);
}
 
Example 7
Source File: RxJerseyClientFeature.java    From rx-jersey with MIT License 5 votes vote down vote up
private Client defaultClient() {
    int cores = Runtime.getRuntime().availableProcessors();
    ClientConfig config = new ClientConfig();
    config.connectorProvider(new GrizzlyConnectorProvider());
    config.property(ClientProperties.ASYNC_THREADPOOL_SIZE, cores);
    config.register(RxFlowableInvokerProvider.class);

    return ClientBuilder.newClient(config);
}
 
Example 8
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 9
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 10
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 11
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;

    }
 
Example 12
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 13
Source File: HttpClientCommon.java    From datacollector with Apache License 2.0 4 votes vote down vote up
public List<Stage.ConfigIssue> init(List<Stage.ConfigIssue> issues, Stage.Context context) {
  this.context = context;
  if (jerseyClientConfig.tlsConfig.isEnabled()) {
    jerseyClientConfig.tlsConfig.init(
        context,
        Groups.TLS.name(),
        SSL_CONFIG_PREFIX,
        issues
    );
  }

  resourceVars = context.createELVars();
  resourceEval = context.createELEval(RESOURCE_CONFIG_NAME);

  methodVars = context.createELVars();
  methodEval = context.createELEval(HTTP_METHOD_CONFIG_NAME);

  headerVars = context.createELVars();
  headerEval = context.createELEval(HEADER_CONFIG_NAME);

  String proxyUsername = null;
  String proxyPassword = null;
  if(jerseyClientConfig.useProxy) {
    proxyUsername = jerseyClientConfig.proxy.resolveUsername(context, Groups.PROXY.name(), "conf.client.proxy.", issues);
    proxyPassword = jerseyClientConfig.proxy.resolvePassword(context, Groups.PROXY.name(), "conf.client.proxy.", issues);
  }

  jerseyClientConfig.init(context, Groups.PROXY.name(), "conf.client.", issues);
  // Validation succeeded so configure the client.
  if (issues.isEmpty()) {
    ClientConfig clientConfig = new ClientConfig()
        .property(ClientProperties.CONNECT_TIMEOUT, jerseyClientConfig.connectTimeoutMillis)
        .property(ClientProperties.READ_TIMEOUT, jerseyClientConfig.readTimeoutMillis)
        .property(ClientProperties.ASYNC_THREADPOOL_SIZE, jerseyClientConfig.numThreads)
        .property(ClientProperties.REQUEST_ENTITY_PROCESSING, jerseyClientConfig.transferEncoding)
        .property(ClientProperties.USE_ENCODING, jerseyClientConfig.httpCompression.getValue());

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

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

    if (jerseyClientConfig.requestLoggingConfig.enableRequestLogging) {
      Feature feature = new LoggingFeature(
          REQUEST_LOGGER,
          Level.parse(jerseyClientConfig.requestLoggingConfig.logLevel),
          jerseyClientConfig.requestLoggingConfig.verbosity, jerseyClientConfig.requestLoggingConfig.maxEntitySize
      );
      clientBuilder = clientBuilder.register(feature);
    }

    configureCompression(clientBuilder);

    if (jerseyClientConfig.useProxy) {
      JerseyClientUtil.configureProxy(
        jerseyClientConfig.proxy.uri,
        proxyUsername,
        proxyPassword, clientBuilder
      );
    }

    JerseyClientUtil.configureSslContext(jerseyClientConfig.tlsConfig, clientBuilder);

    configureAuthAndBuildClient(clientBuilder, issues);


    if(jerseyClientConfig.authType.equals(AuthenticationType.KERBEROS_SPNEGO)) {

      String principal = jerseyClientConfig.spnegoPrincipal;
      String keytab = jerseyClientConfig.spnegoKeytabFile;
      CredentialValue princPass = jerseyClientConfig.spnegoPrincipalPassword;
      String pathnameSpnegoConf = context.getResourcesDirectory() + "/spnego.conf";
      File f = new File(pathnameSpnegoConf);
      try {
        PrintWriter pw = new PrintWriter(f);
        pw.println(String.format(SPNEGO_CLIENT_LOGIN, principal, keytab));
        pw.close();
      } catch (IOException e) {
        throw new StageException(HTTP_36,e);
      }

      System.setProperty(JAVAX_SECURITY_AUTH_USE_SUBJECT_CREDS_ONLY, "false");
      System.setProperty(JAVA_SECURITY_AUTH_LOGIN_CONFIG, pathnameSpnegoConf);

      Authenticator.setDefault(new Authenticator() {
        @Override
        protected PasswordAuthentication getPasswordAuthentication() {
          String kuser = principal;
          String kpass = princPass.get();
          return (new PasswordAuthentication(kuser, kpass.toCharArray()));
        }
      });
    }
  }
  return issues;
}
 
Example 14
Source File: HttpClientCommon.java    From datacollector with Apache License 2.0 4 votes vote down vote up
public List<Stage.ConfigIssue> init(List<Stage.ConfigIssue> issues, Stage.Context context) {
  this.context = context;
  if (jerseyClientConfig.tlsConfig.isEnabled()) {
    jerseyClientConfig.tlsConfig.init(
        context,
        Groups.TLS.name(),
        SSL_CONFIG_PREFIX,
        issues
    );
  }

  resourceVars = context.createELVars();
  resourceEval = context.createELEval(RESOURCE_CONFIG_NAME);

  methodVars = context.createELVars();
  methodEval = context.createELEval(HTTP_METHOD_CONFIG_NAME);

  headerVars = context.createELVars();
  headerEval = context.createELEval(HEADER_CONFIG_NAME);

  String proxyUsername = null;
  String proxyPassword = null;
  if(jerseyClientConfig.useProxy) {
    proxyUsername = jerseyClientConfig.proxy.resolveUsername(context, Groups.PROXY.name(), "conf.client.proxy.", issues);
    proxyPassword = jerseyClientConfig.proxy.resolvePassword(context, Groups.PROXY.name(), "conf.client.proxy.", issues);
  }

  jerseyClientConfig.init(context, Groups.PROXY.name(), "conf.client.", issues);
  // Validation succeeded so configure the client.
  if (issues.isEmpty()) {
    ClientConfig clientConfig = new ClientConfig()
        .property(ClientProperties.CONNECT_TIMEOUT, jerseyClientConfig.connectTimeoutMillis)
        .property(ClientProperties.READ_TIMEOUT, jerseyClientConfig.readTimeoutMillis)
        .property(ClientProperties.ASYNC_THREADPOOL_SIZE, jerseyClientConfig.numThreads);

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

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

    if (jerseyClientConfig.requestLoggingConfig.enableRequestLogging) {
      Feature feature = new LoggingFeature(
          REQUEST_LOGGER,
          Level.parse(jerseyClientConfig.requestLoggingConfig.logLevel),
          jerseyClientConfig.requestLoggingConfig.verbosity, jerseyClientConfig.requestLoggingConfig.maxEntitySize
      );
      clientBuilder = clientBuilder.register(feature);
    }

    configureCompression(clientBuilder);

    if (jerseyClientConfig.useProxy) {
      JerseyClientUtil.configureProxy(
        jerseyClientConfig.proxy.uri,
        proxyUsername,
        proxyPassword, clientBuilder
      );
    }

    JerseyClientUtil.configureSslContext(jerseyClientConfig.tlsConfig, clientBuilder);

    configureAuthAndBuildClient(clientBuilder, issues);
  }

  return issues;
}
 
Example 15
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 16
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 17
Source File: PulsarAdmin.java    From pulsar with Apache License 2.0 4 votes vote down vote up
public PulsarAdmin(String serviceUrl,
                   ClientConfigurationData clientConfigData,
                   int connectTimeout,
                   TimeUnit connectTimeoutUnit,
                   int readTimeout,
                   TimeUnit readTimeoutUnit,
                   int requestTimeout,
                   TimeUnit requestTimeoutUnit) throws PulsarClientException {
    this.connectTimeout = connectTimeout;
    this.connectTimeoutUnit = connectTimeoutUnit;
    this.readTimeout = readTimeout;
    this.readTimeoutUnit = readTimeoutUnit;
    this.requestTimeout = requestTimeout;
    this.requestTimeoutUnit = requestTimeoutUnit;
    this.clientConfigData = clientConfigData;
    this.auth = clientConfigData != null ? clientConfigData.getAuthentication() : new AuthenticationDisabled();
    LOG.debug("created: serviceUrl={}, authMethodName={}", serviceUrl,
            auth != null ? auth.getAuthMethodName() : null);

    if (auth != null) {
        auth.start();
    }

    if (StringUtils.isBlank(clientConfigData.getServiceUrl())) {
        clientConfigData.setServiceUrl(serviceUrl);
    }

    AsyncHttpConnectorProvider asyncConnectorProvider = new AsyncHttpConnectorProvider(clientConfigData);

    ClientConfig httpConfig = new ClientConfig();
    httpConfig.property(ClientProperties.FOLLOW_REDIRECTS, true);
    httpConfig.property(ClientProperties.ASYNC_THREADPOOL_SIZE, 8);
    httpConfig.register(MultiPartFeature.class);
    httpConfig.connectorProvider(asyncConnectorProvider);

    ClientBuilder clientBuilder = ClientBuilder.newBuilder()
            .withConfig(httpConfig)
            .connectTimeout(this.connectTimeout, this.connectTimeoutUnit)
            .readTimeout(this.readTimeout, this.readTimeoutUnit)
            .register(JacksonConfigurator.class).register(JacksonFeature.class);

    boolean useTls = clientConfigData.getServiceUrl().startsWith("https://");

    this.client = clientBuilder.build();

    this.serviceUrl = serviceUrl;
    root = client.target(serviceUrl);

    this.httpAsyncClient = asyncConnectorProvider.getConnector(
            Math.toIntExact(connectTimeoutUnit.toMillis(this.connectTimeout)),
            Math.toIntExact(readTimeoutUnit.toMillis(this.readTimeout)),
            Math.toIntExact(requestTimeoutUnit.toMillis(this.requestTimeout))).getHttpClient();

    long readTimeoutMs = readTimeoutUnit.toMillis(this.readTimeout);
    this.clusters = new ClustersImpl(root, auth, readTimeoutMs);
    this.brokers = new BrokersImpl(root, auth, readTimeoutMs);
    this.brokerStats = new BrokerStatsImpl(root, auth, readTimeoutMs);
    this.proxyStats = new ProxyStatsImpl(root, auth, readTimeoutMs);
    this.tenants = new TenantsImpl(root, auth, readTimeoutMs);
    this.properties = new TenantsImpl(root, auth, readTimeoutMs);
    this.namespaces = new NamespacesImpl(root, auth, readTimeoutMs);
    this.topics = new TopicsImpl(root, auth, readTimeoutMs);
    this.nonPersistentTopics = new NonPersistentTopicsImpl(root, auth, readTimeoutMs);
    this.resourceQuotas = new ResourceQuotasImpl(root, auth, readTimeoutMs);
    this.lookups = new LookupImpl(root, auth, useTls, readTimeoutMs);
    this.functions = new FunctionsImpl(root, auth, httpAsyncClient, readTimeoutMs);
    this.sources = new SourcesImpl(root, auth, httpAsyncClient, readTimeoutMs);
    this.sinks = new SinksImpl(root, auth, httpAsyncClient, readTimeoutMs);
    this.worker = new WorkerImpl(root, auth, readTimeoutMs);
    this.schemas = new SchemasImpl(root, auth, readTimeoutMs);
    this.bookies = new BookiesImpl(root, auth, readTimeoutMs);
}
 
Example 18
Source File: RestClient.java    From ats-framework with Apache License 2.0 4 votes vote down vote up
private ClientConfig createClientConfig(
                                         boolean suppressHttpComplianceValidation ) {

    ClientConfig clientConfig = new ClientConfig();

    // register third-party connector provider
    if (this.clientConfigurator.getConnectorProvider() != null) {

        Map<String, Object> connectorProviderProperties = this.clientConfigurator.getConnectorProviderProperties();
        if (connectorProviderProperties != null
            && !connectorProviderProperties.isEmpty()) {
            for (Entry<String, Object> propEntry : connectorProviderProperties.entrySet()) {
                clientConfig.property(propEntry.getKey(), propEntry.getValue());
            }
        }
        try {
            clientConfig.connectorProvider(clientConfigurator.getConnectorProvider());
        } catch (Exception e) {
            throw new RuntimeException("Unable to register connector provider '"
                                       + clientConfigurator.getConnectorProvider().getClass().getName() + "'");
        }
    }

    // attach any configuration providers instances or classes
    // (e.g. features or individual entity providers, filters or interceptors)
    for (Object provider : clientConfigurator.getProviders()) {
        clientConfig.register(provider);
    }
    for (Class<?> providerClass : clientConfigurator.getProviderClasses()) {
        clientConfig.register(providerClass);
    }

    // attach any configuration properties
    Map<String, Object> properties = clientConfigurator.getProperties();
    for (Entry<String, Object> propertyEntry : properties.entrySet()) {
        clientConfig.property(propertyEntry.getKey(), propertyEntry.getValue());
    }

    if (suppressHttpComplianceValidation == true) { // not default value
        if (properties.containsKey(ClientProperties.SUPPRESS_HTTP_COMPLIANCE_VALIDATION)) { // user provided value found
            boolean userProvidedValue = (boolean) properties.get(ClientProperties.SUPPRESS_HTTP_COMPLIANCE_VALIDATION);
            if (userProvidedValue != suppressHttpComplianceValidation) {
                // ignore our value
                log.info("You are executing PUT with null body and SUPPRESS_HTTP_COMPLIANCE_VALIDATION is set to false. Expect operation to fail.");
            } else {
                // set our value
                log.warn("You are executing PUT operation with null body. Expect the client implementation to complain.");
                clientConfig.property(ClientProperties.SUPPRESS_HTTP_COMPLIANCE_VALIDATION,
                                      suppressHttpComplianceValidation);
            }
        } else { // user provided value not found
            // set our value
            log.warn("You are executing PUT operation with null body. Expect the client implementation to complain.");
            clientConfig.property(ClientProperties.SUPPRESS_HTTP_COMPLIANCE_VALIDATION,
                                  suppressHttpComplianceValidation);
        }
    }

    // basic authorization
    if (username != null) {
        clientConfig.register(HttpAuthenticationFeature.basic(username, password));
    }

    return clientConfig;
}
 
Example 19
Source File: JerseyServerIT.java    From tessera with Apache License 2.0 4 votes vote down vote up
private static Client newClient(URI unixfile) {
    ClientConfig config = new ClientConfig();
    config.connectorProvider(new JerseyUnixSocketConnectorProvider());

    return ClientBuilder.newClient(config).property("unixfile", unixfile);
}