org.glassfish.jersey.client.ClientProperties Java Examples

The following examples show how to use org.glassfish.jersey.client.ClientProperties. 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: AdminApiKeyStoreTlsAuthTest.java    From pulsar with Apache License 2.0 6 votes vote down vote up
WebTarget buildWebClient() throws Exception {
    ClientConfig httpConfig = new ClientConfig();
    httpConfig.property(ClientProperties.FOLLOW_REDIRECTS, true);
    httpConfig.property(ClientProperties.ASYNC_THREADPOOL_SIZE, 8);
    httpConfig.register(MultiPartFeature.class);

    ClientBuilder clientBuilder = ClientBuilder.newBuilder().withConfig(httpConfig)
        .register(JacksonConfigurator.class).register(JacksonFeature.class);

    SSLContext sslCtx = KeyStoreSSLContext.createClientSslContext(
            KEYSTORE_TYPE,
            CLIENT_KEYSTORE_FILE_PATH,
            CLIENT_KEYSTORE_PW,
            KEYSTORE_TYPE,
            BROKER_TRUSTSTORE_FILE_PATH,
            BROKER_TRUSTSTORE_PW);

    clientBuilder.sslContext(sslCtx).hostnameVerifier(NoopHostnameVerifier.INSTANCE);
    Client client = clientBuilder.build();

    return client.target(brokerUrlTls.toString());
}
 
Example #3
Source File: JerseyDockerHttpClient.java    From docker-java with Apache License 2.0 6 votes vote down vote up
private void configureProxy(ClientConfig clientConfig, URI originalUri, String protocol) {
    List<Proxy> proxies = ProxySelector.getDefault().select(originalUri);

    for (Proxy proxy : proxies) {
        InetSocketAddress address = (InetSocketAddress) proxy.address();
        if (address != null) {
            String hostname = address.getHostName();
            int port = address.getPort();

            clientConfig.property(ClientProperties.PROXY_URI, "http://" + hostname + ":" + port);

            String httpProxyUser = System.getProperty(protocol + ".proxyUser");
            if (httpProxyUser != null) {
                clientConfig.property(ClientProperties.PROXY_USERNAME, httpProxyUser);
                String httpProxyPassword = System.getProperty(protocol + ".proxyPassword");
                if (httpProxyPassword != null) {
                    clientConfig.property(ClientProperties.PROXY_PASSWORD, httpProxyPassword);
                }
            }
        }
    }
}
 
Example #4
Source File: ProxyClientConfig.java    From gitlab4j-api with MIT License 6 votes vote down vote up
/**
 * Create a Map instance set up to use a proxy server that can be passed to the GitLabAPi constructors 
 * and login methods to configure the GitLabApi instance to use a proxy server.
 *
 * @param proxyUri the URI of the proxy server
 * @param username the username for basic auth with the proxy server
 * @param password the password for basic auth with the proxy server
 * @return a Map set up to allow GitLabApi to use a proxy server
 */
public static Map<String, Object> createProxyClientConfig(String proxyUri, String username, String password) {

    Map<String, Object> clientConfig = new HashMap<>();
    clientConfig.put(ClientProperties.PROXY_URI, proxyUri);

    if (username != null && username.trim().length() > 0) {
        clientConfig.put(ClientProperties.PROXY_USERNAME, username);
    }

    if (password != null && password.trim().length() > 0) {
        clientConfig.put(ClientProperties.PROXY_PASSWORD, password);
    }

    return (clientConfig);
}
 
Example #5
Source File: ResolverClient.java    From proarc with GNU General Public License v3.0 6 votes vote down vote up
Client getHttpClient() {
    if (httpClient == null) {
        try {
            SSLContext sslCtx = SSLContext.getInstance("SSL");
            TrustManager tm = new TrustThemAll();
            sslCtx.init(null, new TrustManager[] {tm}, null);

            httpClient = ClientBuilder.newBuilder()
                    .sslContext(sslCtx)
                    .register(HttpAuthenticationFeature.basic(user, passwd))
                    .build();
            httpClient.property(ClientProperties.FOLLOW_REDIRECTS, true);
            httpClient.property(ClientProperties.CONNECT_TIMEOUT, 2 * 60 * 1000); // 2 min
        } catch (NoSuchAlgorithmException | KeyManagementException ex) {
            throw new IllegalStateException(ex);
        }
    }
    return httpClient;
}
 
Example #6
Source File: TenantWebResourceTest.java    From onos with Apache License 2.0 6 votes vote down vote up
/**
 * Tests removing a tenant id with DELETE request.
 */
@Test
public void testDelete() {
    expect(mockVnetAdminService.getTenantIds())
            .andReturn(ImmutableSet.of(tenantId2)).anyTimes();
    mockVnetAdminService.unregisterTenantId(anyObject());
    expectLastCall();
    replay(mockVnetAdminService);

    WebTarget wt = target()
            .property(ClientProperties.SUPPRESS_HTTP_COMPLIANCE_VALIDATION, true);
    Response response = wt.path("tenants/" + tenantId2)
            .request(MediaType.APPLICATION_JSON_TYPE)
            .delete();

    assertThat(response.getStatus(), is(HttpURLConnection.HTTP_NO_CONTENT));

    verify(mockVnetAdminService);
}
 
Example #7
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 #8
Source File: DefaultSchemaRegistryClient.java    From ranger with Apache License 2.0 6 votes vote down vote up
public DefaultSchemaRegistryClient(Map<String, ?> conf) {
    configuration = new Configuration(conf);
    login = SecurityUtils.initializeSecurityContext(conf);
    ClientConfig config = createClientConfig(conf);
    final boolean SSLEnabled = SecurityUtils.isHttpsConnection(conf);
    ClientBuilder clientBuilder = JerseyClientBuilder.newBuilder()
            .withConfig(config)
            .property(ClientProperties.FOLLOW_REDIRECTS, Boolean.TRUE);
    if (SSLEnabled) {
        SSLContext ctx;
        try {
            ctx = SecurityUtils.createSSLContext(conf, SSL_ALGORITHM);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        clientBuilder.sslContext(ctx);
    }
    client = clientBuilder.build();

    // get list of urls and create given or default UrlSelector.
    urlSelector = createUrlSelector();
    urlWithTargets = new ConcurrentHashMap<>();
}
 
Example #9
Source File: InstanceProviderClient.java    From athenz with Apache License 2.0 6 votes vote down vote up
public InstanceProviderClient(String url, SSLContext sslContext,
        HostnameVerifier hostnameVerifier, int connectTimeout, int readTimeout) {

    final ClientConfig config = new ClientConfig()
            .property(ClientProperties.CONNECT_TIMEOUT, connectTimeout)
            .property(ClientProperties.READ_TIMEOUT, readTimeout)
            .connectorProvider(new ApacheConnectorProvider());

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

    client = builder.hostnameVerifier(hostnameVerifier)
            .withConfig(config)
            .build();
    base = client.target(url);
}
 
Example #10
Source File: VirtualNetworkWebResourceTest.java    From onos with Apache License 2.0 6 votes vote down vote up
/**
 * Tests removing a virtual host with DELETE request.
 */
@Test
public void testDeleteVirtualHost() {
    NetworkId networkId = networkId3;
    mockVnetAdminService.removeVirtualHost(networkId, hId1);
    expectLastCall();
    replay(mockVnetAdminService);

    WebTarget wt = target()
            .property(ClientProperties.SUPPRESS_HTTP_COMPLIANCE_VALIDATION, true);
    InputStream jsonStream = VirtualNetworkWebResourceTest.class
            .getResourceAsStream("post-virtual-host.json");
    String reqLocation = "vnets/" + networkId.toString() + "/hosts";
    Response response = wt.path(reqLocation).request().method("DELETE", Entity.json(jsonStream));

    assertThat(response.getStatus(), is(HttpURLConnection.HTTP_NO_CONTENT));
    verify(mockVnetAdminService);
}
 
Example #11
Source File: ApiClient.java    From datacollector with Apache License 2.0 6 votes vote down vote up
/**
 * Get an existing client or create a new client to handle HTTP request.
 */
private Client getClient() {
  if (!hostMap.containsKey(basePath)) {
    ClientConfig config = new ClientConfig();
    config.property(ClientProperties.SUPPRESS_HTTP_COMPLIANCE_VALIDATION, true);
    Client client;
    if (sslContext != null) {
      client = ClientBuilder.newBuilder().sslContext(sslContext).withConfig(config).build();
    } else {
      client = ClientBuilder.newClient(config);
    }
    client.register(new CsrfProtectionFilter("CSRF"));
    hostMap.put(basePath, client);
  }
  return hostMap.get(basePath);
}
 
Example #12
Source File: Sencha_DELETE_IT.java    From agrest with Apache License 2.0 6 votes vote down vote up
@Test
public void test_BatchDelete_CompoundId() {

    e17().insertColumns("id1", "id2", "name")
            .values(1, 1, "aaa")
            .values(2, 2, "bbb")
            .values(3, 3, "ccc").exec();

    Response response = target("/e17").request()
            .property(ClientProperties.SUPPRESS_HTTP_COMPLIANCE_VALIDATION, true)
            .method("DELETE", Entity.json("[{\"id1\":1,\"id2\":1},{\"id1\":2,\"id2\":2}]"), Response.class);

    assertEquals(Response.Status.OK.getStatusCode(), response.getStatus());

    e17().matcher().assertOneMatch();
    e17().matcher().eq("id1", 3).eq("id2", 3).assertOneMatch();
}
 
Example #13
Source File: JerseyClientUtil.java    From datacollector with Apache License 2.0 6 votes vote down vote up
public static ClientBuilder configureProxy(
  String uri,
  String username,
  String password,
  ClientBuilder clientBuilder
) {
  if (!StringUtils.isEmpty(uri)) {
    clientBuilder.property(ClientProperties.PROXY_URI, uri);
    LOG.debug("Using Proxy: '{}'", uri);
  } else { // No proxy URI, then return
    return clientBuilder;
  }
  if (!StringUtils.isEmpty(username)) {
    clientBuilder.property(ClientProperties.PROXY_USERNAME, username);
    LOG.debug("Using Proxy Username: '{}'", username);
  }
  if (!StringUtils.isEmpty(password)) {
    clientBuilder.property(ClientProperties.PROXY_PASSWORD, password);
    LOG.debug("Using Proxy Password: '{}'", password);
  }

  return clientBuilder;
}
 
Example #14
Source File: BitmexRestClient.java    From zheshiyigeniubidexiangmu with MIT License 6 votes vote down vote up
public BitmexRestClient(boolean useProduction) {
    if (useProduction) {
        apiURL = productionApiUrl;
    } else {
        apiURL = testnetApiUrl;
    }
    ObjectMapper mapper = new ObjectMapper();
    mapper.registerModule(new JavaTimeModule());
    JacksonJaxbJsonProvider provider = new JacksonJaxbJsonProvider(mapper, new Annotations[0]);
    ClientConfig config = new ClientConfig();
    config.property(ClientProperties.SUPPRESS_HTTP_COMPLIANCE_VALIDATION, true);   
    config.register(provider);
    config.register(JacksonFeature.class);
            
    client = ClientBuilder.newBuilder().withConfig(config).build();
}
 
Example #15
Source File: VirtualNetworkWebResourceTest.java    From onos with Apache License 2.0 6 votes vote down vote up
/**
 * Tests removing a virtual device with DELETE request.
 */
@Test
public void testDeleteVirtualDevice() {
    NetworkId networkId = networkId3;
    DeviceId deviceId = devId2;
    mockVnetAdminService.removeVirtualDevice(networkId, deviceId);
    expectLastCall();
    replay(mockVnetAdminService);

    WebTarget wt = target()
            .property(ClientProperties.SUPPRESS_HTTP_COMPLIANCE_VALIDATION, true);
    String reqLocation = "vnets/" + networkId.toString() + "/devices/" + deviceId.toString();
    Response response = wt.path(reqLocation)
            .request(MediaType.APPLICATION_JSON_TYPE)
            .delete();

    assertThat(response.getStatus(), is(HttpURLConnection.HTTP_NO_CONTENT));

    verify(mockVnetAdminService);
}
 
Example #16
Source File: BitmexRestClient.java    From zheshiyigeniubidexiangmu with MIT License 6 votes vote down vote up
public BitmexRestClient(boolean useProduction) {
    if (useProduction) {
        apiURL = productionApiUrl;
    } else {
        apiURL = testnetApiUrl;
    }
    ObjectMapper mapper = new ObjectMapper();
    mapper.registerModule(new JavaTimeModule());
    JacksonJaxbJsonProvider provider = new JacksonJaxbJsonProvider(mapper, new Annotations[0]);
    ClientConfig config = new ClientConfig();
    config.property(ClientProperties.SUPPRESS_HTTP_COMPLIANCE_VALIDATION, true);   
    config.register(provider);
    config.register(JacksonFeature.class);
            
    client = ClientBuilder.newBuilder().withConfig(config).build();
}
 
Example #17
Source File: ShopifySdk.java    From shopify-sdk with Apache License 2.0 6 votes vote down vote up
protected ShopifySdk(final Steps steps) {
	if (steps != null) {
		this.shopSubdomain = steps.subdomain;
		this.accessToken = steps.accessToken;
		this.clientId = steps.clientId;
		this.clientSecret = steps.clientSecret;
		this.authorizationToken = steps.authorizationToken;
		this.apiUrl = steps.apiUrl;
		this.minimumRequestRetryRandomDelayMilliseconds = steps.minimumRequestRetryRandomDelayMilliseconds;
		this.maximumRequestRetryRandomDelayMilliseconds = steps.maximumRequestRetryRandomDelayMilliseconds;
		this.maximumRequestRetryTimeoutMilliseconds = steps.maximumRequestRetryTimeoutMilliseconds;

		CLIENT.property(ClientProperties.CONNECT_TIMEOUT, Math.toIntExact(steps.connectionTimeoutMilliseconds));
		CLIENT.property(ClientProperties.READ_TIMEOUT, Math.toIntExact(steps.readTimeoutMilliseconds));
		validateConstructionOfShopifySdk();
	}

}
 
Example #18
Source File: ClientFactoryTest.java    From tessera with Apache License 2.0 6 votes vote down vote up
@Test
public void testBuildSecureClientCAMode() throws URISyntaxException {

    ServerConfig serverConfig = mock(ServerConfig.class);
    SslConfig sslConfig = mock(SslConfig.class);
    when(serverConfig.isSsl()).thenReturn(true);
    when(serverConfig.getServerUri()).thenReturn(new URI("https://localhost:8080"));
    when(serverConfig.getSslConfig()).thenReturn(sslConfig);
    Map<String, String> props = new HashMap<>();
    props.put("partyInfoInterval", "20000");
    when(serverConfig.getProperties()).thenReturn(props);

    SSLContext sslContext = mock(SSLContext.class);
    when(sslContextFactory.from(serverConfig.getServerUri().toString(), sslConfig)).thenReturn(sslContext);

    Client client = factory.buildFrom(serverConfig);
    assertThat(client).isNotNull();
    Map clientProperties = client.target(serverConfig.getServerUri()).getConfiguration().getProperties();

    assertThat(clientProperties.get(ClientProperties.READ_TIMEOUT)).isEqualTo(15000);
    assertThat(clientProperties.get(ClientProperties.CONNECT_TIMEOUT)).isEqualTo(15000);
    verify(sslContextFactory).from(serverConfig.getServerUri().toString(), sslConfig);
}
 
Example #19
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 #20
Source File: RegionsResourceTest.java    From onos with Apache License 2.0 6 votes vote down vote up
/**
 * Tests deleting a set of devices contained in the given region with DELETE.
 */
@Test
public void testRemoveDevicesDelete() {
    mockRegionAdminService.removeDevices(anyObject(), anyObject());
    expectLastCall();
    replay(mockRegionAdminService);

    expect(mockRegionService.getRegion(anyObject())).andReturn(region1).anyTimes();
    replay(mockRegionService);

    WebTarget wt = target()
            .property(ClientProperties.SUPPRESS_HTTP_COMPLIANCE_VALIDATION, true);
    InputStream jsonStream = RegionsResourceTest.class
            .getResourceAsStream("region-deviceIds.json");

    // FIXME: need to consider whether to use jsonStream for entry deletion
    Response response = wt.path("regions/" + region1.id().toString() + "/devices")
            .request().method("DELETE", Entity.json(jsonStream));
    assertThat(response.getStatus(), is(HttpURLConnection.HTTP_NO_CONTENT));
    verify(mockRegionAdminService);
}
 
Example #21
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 #22
Source File: VirtualNetworkWebResourceTest.java    From onos with Apache License 2.0 6 votes vote down vote up
/**
 * Tests removing a virtual port with DELETE request.
 */
@Test
public void testDeleteVirtualPort() {
    NetworkId networkId = networkId3;
    DeviceId deviceId = devId2;
    PortNumber portNum = portNumber(2);
    mockVnetAdminService.removeVirtualPort(networkId, deviceId, portNum);
    expectLastCall();
    replay(mockVnetAdminService);

    WebTarget wt = target()
            .property(ClientProperties.SUPPRESS_HTTP_COMPLIANCE_VALIDATION, true);
    String reqLocation = "vnets/" + networkId.toString()
            + "/devices/" + deviceId.toString() + "/ports/" + portNum.toLong();
    Response response = wt.path(reqLocation)
            .request(MediaType.APPLICATION_JSON_TYPE)
            .delete();

    assertThat(response.getStatus(), is(HttpURLConnection.HTTP_NO_CONTENT));

    verify(mockVnetAdminService);
}
 
Example #23
Source File: AdminApiTlsAuthTest.java    From pulsar with Apache License 2.0 6 votes vote down vote up
WebTarget buildWebClient(String user) throws Exception {
    ClientConfig httpConfig = new ClientConfig();
    httpConfig.property(ClientProperties.FOLLOW_REDIRECTS, true);
    httpConfig.property(ClientProperties.ASYNC_THREADPOOL_SIZE, 8);
    httpConfig.register(MultiPartFeature.class);

    ClientBuilder clientBuilder = ClientBuilder.newBuilder().withConfig(httpConfig)
        .register(JacksonConfigurator.class).register(JacksonFeature.class);

    X509Certificate trustCertificates[] = SecurityUtility.loadCertificatesFromPemFile(
            getTLSFile("ca.cert"));
    SSLContext sslCtx = SecurityUtility.createSslContext(
            false, trustCertificates,
            SecurityUtility.loadCertificatesFromPemFile(getTLSFile(user + ".cert")),
            SecurityUtility.loadPrivateKeyFromPemFile(getTLSFile(user + ".key-pk8")));
    clientBuilder.sslContext(sslCtx).hostnameVerifier(NoopHostnameVerifier.INSTANCE);
    Client client = clientBuilder.build();

    return client.target(brokerUrlTls.toString());
}
 
Example #24
Source File: GitLabApiClient.java    From gitlab4j-api with MIT License 5 votes vote down vote up
protected Invocation.Builder invocation(URL url, MultivaluedMap<String, String> queryParams, String accept) {

        if (apiClient == null) {
            createApiClient();
        }

        WebTarget target = apiClient.target(url.toExternalForm()).property(ClientProperties.FOLLOW_REDIRECTS, true);
        if (queryParams != null) {
            for (Map.Entry<String, List<String>> param : queryParams.entrySet()) {
                target = target.queryParam(param.getKey(), param.getValue().toArray());
            }
        }

        String authHeader = (tokenType == TokenType.OAUTH2_ACCESS ? AUTHORIZATION_HEADER : PRIVATE_TOKEN_HEADER);
        String authValue = (tokenType == TokenType.OAUTH2_ACCESS ? "Bearer " + authToken : authToken);
        Invocation.Builder builder = target.request();
        if (accept == null || accept.trim().length() == 0) {
            builder = builder.header(authHeader, authValue);
        } else {
            builder = builder.header(authHeader, authValue).accept(accept);
        }

        // If sudo as ID is set add the Sudo header
        if (sudoAsId != null && sudoAsId.intValue() > 0)
            builder = builder.header(SUDO_HEADER,  sudoAsId);

        // Set the per request connect timeout
        if (connectTimeout != null) {
            builder.property(ClientProperties.CONNECT_TIMEOUT, connectTimeout);
        }

        // Set the per request read timeout
        if (readTimeout != null) {
            builder.property(ClientProperties.READ_TIMEOUT, readTimeout);
        }

        return (builder);
    }
 
Example #25
Source File: OAuth2TestUtil.java    From datacollector with Apache License 2.0 5 votes vote down vote up
public OAuth2ConfigBean setup(Client client, WebTarget target, Invocation.Builder builder, Response response, OAuth2GrantTypes grantType) {
  OAuth2ConfigBean configBean = new OAuth2ConfigBean();
  MultivaluedMap<String, String> params = new MultivaluedHashMap<>();
  RequestEntityProcessing transferEncoding = RequestEntityProcessing.BUFFERED;
  if (grantType == OAuth2GrantTypes.CLIENT_CREDENTIALS) {
    params.put(OAuth2ConfigBean.CLIENT_ID_KEY, Collections.singletonList(clientId));
    params.put(OAuth2ConfigBean.CLIENT_SECRET_KEY, Collections.singletonList(clientSecret));
    params.put(OAuth2ConfigBean.GRANT_TYPE_KEY, Collections.singletonList(OAuth2ConfigBean.CLIENT_CREDENTIALS_GRANT));
    configBean.clientId = () -> clientId;
    configBean.clientSecret = () -> clientSecret;
  } else {
    params.put(OAuth2ConfigBean.RESOURCE_OWNER_KEY, Collections.singletonList(clientId));
    params.put(OAuth2ConfigBean.PASSWORD_KEY, Collections.singletonList(clientSecret));
    params.put(OAuth2ConfigBean.GRANT_TYPE_KEY, Collections.singletonList(OAuth2ConfigBean.RESOURCE_OWNER_GRANT));
    configBean.username = () -> clientId;
    configBean.password = () -> clientSecret;
  }

  configBean.credentialsGrantType = grantType;
  configBean.transferEncoding = RequestEntityProcessing.BUFFERED;
  configBean.tokenUrl = "https://example.com";

  Mockito.when(response.readEntity(String.class)).thenReturn(TOKEN_RESPONSE);
  Mockito.when(response.getStatus()).thenReturn(200);
  Mockito.when(builder.post(Mockito.argThat(new FormMatcher(Entity.form(params))))).thenReturn(response);
  Mockito.when(builder.property(ClientProperties.REQUEST_ENTITY_PROCESSING, transferEncoding)).thenReturn(builder);
  Mockito.when(builder.header(any(String.class), any(Object.class))).thenReturn(builder);
  Mockito.when(target.request()).thenReturn(builder);

  Mockito.when(client.target(configBean.tokenUrl)).thenReturn(target);
  return configBean;
}
 
Example #26
Source File: ClassLoaderStageLibraryTask.java    From datacollector with Apache License 2.0 5 votes vote down vote up
private RepositoryManifestJson getRepositoryManifestFile(String repoUrl) {
  ClientConfig clientConfig = new ClientConfig();
  clientConfig.property(ClientProperties.READ_TIMEOUT, 2000);
  clientConfig.property(ClientProperties.CONNECT_TIMEOUT, 2000);
  RepositoryManifestJson repositoryManifestJson = null;
  try (Response response = ClientBuilder.newClient(clientConfig).target(repoUrl).request().get()) {
    InputStream inputStream = response.readEntity(InputStream.class);
    repositoryManifestJson = ObjectMapperFactory.get().readValue(inputStream, RepositoryManifestJson.class);
  } catch (Exception ex) {
    LOG.error("Failed to read repository manifest json", ex);
  }
  return repositoryManifestJson;
}
 
Example #27
Source File: RemoteNiFiUtils.java    From nifi with Apache License 2.0 5 votes vote down vote up
private Client getClient(final SSLContext sslContext) {
    final ClientConfig clientConfig = new ClientConfig();
    clientConfig.property(ClientProperties.READ_TIMEOUT, READ_TIMEOUT);
    clientConfig.property(ClientProperties.CONNECT_TIMEOUT, CONNECT_TIMEOUT);

    final Client client;
    if (sslContext == null) {
        client = WebUtils.createClient(clientConfig);
    } else {
        client = WebUtils.createClient(clientConfig, sslContext);
    }

    return client;
}
 
Example #28
Source File: ServerContextTest.java    From azure-devops-intellij with MIT License 5 votes vote down vote up
@Test
public void getClientConfig() {
    AuthenticationInfo info = new AuthenticationInfo("user1", "pass", "server1", "4display");
    final ClientConfig config = RestClientHelper.getClientConfig(ServerContext.Type.TFS, info, false);

    final Map<String, Object> properties = config.getProperties();
    Assert.assertEquals(3, properties.size());

    Assert.assertEquals(false, properties.get(ApacheClientProperties.PREEMPTIVE_BASIC_AUTHENTICATION));
    Assert.assertEquals(RequestEntityProcessing.BUFFERED, properties.get(ClientProperties.REQUEST_ENTITY_PROCESSING));

    final CredentialsProvider cp = (CredentialsProvider) properties.get(ApacheClientProperties.CREDENTIALS_PROVIDER);
    final Credentials credentials = cp.getCredentials(AuthScope.ANY);
    Assert.assertEquals(info.getPassword(), credentials.getPassword());
    Assert.assertEquals(info.getUserName(), credentials.getUserPrincipal().getName());

    // Make sure Fiddler properties get set if property is on
    final ClientConfig config2 = RestClientHelper.getClientConfig(ServerContext.Type.TFS, info, true);
    final Map<String, Object> properties2 = config2.getProperties();
    //proxy setting doesn't automatically mean we need to setup ssl trust store anymore
    Assert.assertEquals(4, properties2.size());
    Assert.assertNotNull(properties2.get(ClientProperties.PROXY_URI));

    info = new AuthenticationInfo("users1", "pass", "https://tfsonprem.test", "4display");
    final ClientConfig config3 = RestClientHelper.getClientConfig(ServerContext.Type.TFS, info, false);
    final Map<String, Object> properties3 = config3.getProperties();
    Assert.assertEquals(3, properties3.size());
    Assert.assertNull(properties3.get(ClientProperties.PROXY_URI));
}
 
Example #29
Source File: ClientSupport.java    From dropwizard-guicey with MIT License 5 votes vote down vote up
private JerseyClientBuilder clientBuilder() {
    return new JerseyClientBuilder()
            .register(new JacksonFeature(support.getEnvironment().getObjectMapper()))
            .property(ClientProperties.CONNECT_TIMEOUT, 1000)
            .property(ClientProperties.READ_TIMEOUT, 5000)
            .property(HttpUrlConnectorProvider.SET_METHOD_WORKAROUND, true);
}
 
Example #30
Source File: TestRestServicePushSource.java    From datacollector with Apache License 2.0 5 votes vote down vote up
private void testPayloadRequest(
    String method,
    String httpServerUrl,
    List<Record> requestRecords
) {
  Response response = ClientBuilder.newClient()
      .property(ClientProperties.SUPPRESS_HTTP_COMPLIANCE_VALIDATION, true)
      .property(HttpUrlConnectorProvider.SET_METHOD_WORKAROUND, true)
      .target(httpServerUrl)
      .request()
      .header(Constants.X_SDC_APPLICATION_ID_HEADER, "id")
      .method(method, Entity.json("{\"f1\": \"abc\", \"f2\": \"xyz\"}"));

  // Test Request Records
  Assert.assertEquals(1, requestRecords.size());
  Record.Header payloadRecord = requestRecords.get(0).getHeader();
  Assert.assertEquals(method, payloadRecord.getAttribute(RestServiceReceiver.METHOD_HEADER));
  Assert.assertNull(payloadRecord.getAttribute(RestServiceReceiver.EMPTY_PAYLOAD_RECORD_HEADER_ATTR_NAME));
  Assert.assertEquals("abc", requestRecords.get(0).get("/f1").getValue());
  Assert.assertEquals("xyz", requestRecords.get(0).get("/f2").getValue());

  // Test Response from REST Service
  Assert.assertEquals(HttpURLConnection.HTTP_OK, response.getStatus());
  ResponseEnvelope responseBody = response.readEntity(ResponseEnvelope.class);
  Assert.assertNotNull(responseBody);
  Assert.assertEquals(200, responseBody.getHttpStatusCode());
  Assert.assertNotNull(responseBody.getData());
  Assert.assertEquals(1, responseBody.getData().size());
  Assert.assertNotNull(responseBody.getError());
  Assert.assertEquals(0, responseBody.getError().size());
  Assert.assertNull(responseBody.getErrorMessage());
}