private Greeting getGreeting(String endpoint, String name) { String endpointURL = endpoints.get(endpoint); Client client = ClientBuilder.newClient(); try { WebTarget target = client.target(endpointURL); // Provide the authorization information target.register((ClientRequestFilter) requestContext -> { requestContext.getHeaders().add("Authorization", "Bearer "+token); }); if(cmdArgs.debugLevel > 0) target.register(new LoggingFilter()); IGreeting greetingClient = ((ResteasyWebTarget)target).proxy(IGreeting.class); Greeting greeting = greetingClient.greeting(name); return greeting; } finally { client.close(); } }
@Test public void shouldRegisterAMultiTypedProviderInstanceWithPriorities() { MultiTypedProvider provider = new MultiTypedProvider(); Map<Class<?>, Integer> priorities = new HashMap<>(); priorities.put(ClientRequestFilter.class, 500); priorities.put(ClientResponseFilter.class, 501); priorities.put(MessageBodyReader.class, 502); priorities.put(MessageBodyWriter.class, 503); priorities.put(ReaderInterceptor.class, 504); priorities.put(WriterInterceptor.class, 505); priorities.put(ResponseExceptionMapper.class, 506); priorities.put(ParamConverterProvider.class, 507); RestClientBuilder builder = RestClientBuilder.newBuilder().register(provider, priorities); Configuration configuration = builder.getConfiguration(); assertTrue(configuration.isRegistered(MultiTypedProvider.class), MultiTypedProvider.class + " should be registered"); assertTrue(configuration.isRegistered(provider), MultiTypedProvider.class + " should be registered"); Map<Class<?>, Integer> contracts = configuration.getContracts(MultiTypedProvider.class); assertEquals(contracts.size(), priorities.size(), "There should be "+priorities.size()+" provider types registered"); for(Map.Entry<Class<?>, Integer> priority : priorities.entrySet()) { Integer contractPriority = contracts.get(priority.getKey()); assertEquals(contractPriority, priority.getValue(), "The priority for "+priority.getKey()+" should be "+priority.getValue()); } }
@Test public void shouldRegisterAMultiTypedProviderClassWithPriorities() { Map<Class<?>, Integer> priorities = new HashMap<>(); priorities.put(ClientRequestFilter.class, 500); priorities.put(ClientResponseFilter.class, 501); priorities.put(MessageBodyReader.class, 502); priorities.put(MessageBodyWriter.class, 503); priorities.put(ReaderInterceptor.class, 504); priorities.put(WriterInterceptor.class, 505); priorities.put(ResponseExceptionMapper.class, 506); priorities.put(ParamConverterProvider.class, 507); RestClientBuilder builder = RestClientBuilder.newBuilder().register(MultiTypedProvider.class, priorities); Configuration configuration = builder.getConfiguration(); assertTrue(configuration.isRegistered(MultiTypedProvider.class), MultiTypedProvider.class + " should be registered"); Map<Class<?>, Integer> contracts = configuration.getContracts(MultiTypedProvider.class); assertEquals(contracts.size(), priorities.size(), "There should be "+priorities.size()+" provider types registered"); for(Map.Entry<Class<?>, Integer> priority : priorities.entrySet()) { Integer contractPriority = contracts.get(priority.getKey()); assertEquals(contractPriority, priority.getValue(), "The priority for "+priority.getKey()+" should be "+priority.getValue()); } }
@Test public void testNewClient_Auth() { config.property("a", "b"); Map<String, ClientRequestFilter> authFilters = new HashMap<>(); authFilters.put("one", mockAuth1); authFilters.put("two", mockAuth2); DefaultHttpClientFactory factory = new DefaultHttpClientFactory(config, null, authFilters); Client c = factory.newAuthenticatedClient("one"); assertNotNull(c); assertEquals("b", c.getConfiguration().getProperty("a")); assertTrue(c.getConfiguration().isRegistered(mockAuth1)); assertFalse(c.getConfiguration().isRegistered(mockAuth2)); }
/** * Contains 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 */ @Override public <T> T createClient(final Class<T> apiClass, final HostName hostName, final int port, final String pathPrefix, String scheme) { final UriBuilder uriBuilder = UriBuilder.fromPath(pathPrefix).host(hostName.s()).port(port).scheme(scheme); ClientBuilder builder = ClientBuilder.newBuilder() .property(ClientProperties.CONNECT_TIMEOUT, connectTimeoutMs) .property(ClientProperties.READ_TIMEOUT, readTimeoutMs) .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))); } final WebTarget target = builder.build().target(uriBuilder); // TODO: Check if this fills up non-heap memory with loaded classes. return WebResourceFactory.newResource(apiClass, target); }
private WebTarget getWebTarget() { if (client == null) { client = ClientBuilder.newClient(); client.register(JacksonJsonProvider.class); // register the basic authentication filter if authentication information is provided if (authenticationToken != null) { client.register(new ClientRequestFilter() { @Override public void filter(ClientRequestContext requestContext) throws IOException { requestContext.getHeaders().add("Authorization", "Basic " + authenticationToken); } }); } } WebTarget target = client.target(targetUrl); return target; }
public WordPressClientFactory withCredentials(String username, String password) { this.clientRequestFilter = new ClientRequestFilter() { private final String charset = StandardCharsets.UTF_8.name(); @Override public void filter(ClientRequestContext requestContext) throws IOException { String token = String.format("%s:%s", username, password); String basicAuthHeader = null; try { basicAuthHeader = "BASIC " + DatatypeConverter.printBase64Binary(token.getBytes(charset)); } catch (UnsupportedEncodingException ex) { throw new IllegalStateException("Cannot encode with " + charset, ex); } MultivaluedMap<String, Object> headers = requestContext.getHeaders(); headers.add("Authorization", basicAuthHeader); logger.trace("Added BasicAuth filter with username {}", username); } }; return this; }
/** * <p>Package private constructor to encourage the caller to use this Client's associated Factory</p> * @param targetURI The base URI of the Wordpress REST API. The {@code targetUri} should include the FQDN up to, but * not including the REST endpoints (e.g. "https://wp.foo.com/wp-json/" not * "https://wp.foo.com/wp-json/posts") * @param requestFilter A possibly null filter to pass every request this CLient makes to WordPress through. Useful for * adding BasicAuth header information to every request, if appropriate. * @param transformer A concrete class to provide transformation services from the JSON returned by the WP-API and a POJO * that implements the Post marker interface */ JAXRSWordPressClient(URI targetURI, ClientRequestFilter requestFilter, Transformer<? extends Post> transformer) { this.targetURI = targetURI; this.transformer = transformer; this.jaxrsClient = ClientBuilder.newClient(); // If our authenticator is provided, register it as a default ClientRequestFilter so that every request this Client // makes has BasicAuth information added to it if (requestFilter != null) { jaxrsClient = jaxrsClient.register(requestFilter); } logger.debug("Constructing new JAXRSWordPressClient with targetURI '{}' and transformer '{}' " + "and requestFilter '{}'", targetURI, transformer, requestFilter); }
private static Greeting getGreeting(String url, String token, String from) { Client client = ClientBuilder.newClient(); try { WebTarget target = client.target(url); System.out.println("URL : " + url); target.register((ClientRequestFilter) requestContext -> { requestContext.getHeaders().add("Authorization", "Bearer " + token); }); IGreeting greetingClient = ((ResteasyWebTarget) target).proxy(IGreeting.class); return greetingClient.greeting(from); } finally { client.close(); } }
@Test public void shouldRegisterInstanceWithPriority() { Integer priority = 1000; TestClientRequestFilter instance = new TestClientRequestFilter(); RestClientBuilder builder = RestClientBuilder.newBuilder().register(instance, priority); Configuration configuration = builder.getConfiguration(); assertTrue(configuration.isRegistered(TestClientRequestFilter.class), TestClientRequestFilter.class + " should be registered"); assertTrue(configuration.isRegistered(instance), TestClientRequestFilter.class + " should be registered"); Map<Class<?>, Integer> contracts = configuration.getContracts(TestClientRequestFilter.class); assertEquals(contracts.size(), 1, "There should be a registered contract for "+TestClientRequestFilter.class); assertEquals(contracts.get(ClientRequestFilter.class), priority, "The priority for "+TestClientRequestFilter.class+" should be 1000"); }
@Test public void shouldRegisterAMultiTypedProviderInstance() { MultiTypedProvider provider = new MultiTypedProvider(); Class[] providerTypes = {ClientRequestFilter.class, ClientResponseFilter.class, MessageBodyReader.class, MessageBodyWriter.class, ReaderInterceptor.class, WriterInterceptor.class, ResponseExceptionMapper.class, ParamConverterProvider.class}; RestClientBuilder builder = RestClientBuilder.newBuilder().register(provider, providerTypes); Configuration configuration = builder.getConfiguration(); assertTrue(configuration.isRegistered(MultiTypedProvider.class), MultiTypedProvider.class + " should be registered"); assertTrue(configuration.isRegistered(provider), MultiTypedProvider.class + " should be registered"); assertEquals(configuration.getContracts(MultiTypedProvider.class).size(), providerTypes.length, "There should be "+providerTypes.length+" provider types registered"); }
@Test public void shouldRegisterProvidersWithPriority() { Integer priority = 1000; RestClientBuilder builder = RestClientBuilder.newBuilder().register(TestClientRequestFilter.class, priority); Configuration configuration = builder.getConfiguration(); assertTrue(configuration.isRegistered(TestClientRequestFilter.class), TestClientRequestFilter.class + " should be registered"); Map<Class<?>, Integer> contracts = configuration.getContracts(TestClientRequestFilter.class); assertEquals(contracts.size(), 1, "There should be a registered contract for "+TestClientRequestFilter.class); assertEquals(contracts.get(ClientRequestFilter.class), priority, "The priority for "+TestClientRequestFilter.class+" should be 1000"); }
@Test public void shouldRegisterAMultiTypedProviderClass() { Class[] providerTypes = {ClientRequestFilter.class, ClientResponseFilter.class, MessageBodyReader.class, MessageBodyWriter.class, ReaderInterceptor.class, WriterInterceptor.class, ResponseExceptionMapper.class, ParamConverterProvider.class}; RestClientBuilder builder = RestClientBuilder.newBuilder().register(MultiTypedProvider.class, providerTypes); Configuration configuration = builder.getConfiguration(); assertTrue(configuration.isRegistered(MultiTypedProvider.class), MultiTypedProvider.class + " should be registered"); assertEquals(configuration.getContracts(MultiTypedProvider.class).size(), providerTypes.length, "There should be "+providerTypes.length+" provider types registered"); }
protected Map<String, ClientRequestFilter> createAuthFilters(Injector injector) { Map<String, ClientRequestFilter> filters = new HashMap<>(); if (auth != null) { auth.forEach((k, v) -> filters.put(k, v.createAuthFilter(injector))); } return filters; }
@Override public ClientRequestFilter createAuthFilter(Injector injector) { Objects.requireNonNull(username); Objects.requireNonNull(password); return new BasicAuthenticator(username, password); }
@Override public Client newAuthenticatedClient(String authName) { ClientRequestFilter filter = authFilters.get(authName); if (filter == null) { throw new IllegalArgumentException("No authenticator configured for name: " + authName); } return newClient().register(filter); }
@Test(expected = IllegalArgumentException.class) public void testNewClient_Auth_BadAuth() { config.property("a", "b"); Map<String, ClientRequestFilter> authFilters = new HashMap<>(); authFilters.put("one", mockAuth1); authFilters.put("two", mockAuth2); DefaultHttpClientFactory factory = new DefaultHttpClientFactory(config, null, authFilters); factory.newAuthenticatedClient("three"); }
@Test public void testGetWithToken() { Oauth2AuthenticatorFactory factory = new Oauth2AuthenticatorFactory(); factory.setPassword("p"); factory.setUsername("u"); factory.setTokenUrl("http://127.0.0.1:8080/token"); ClientRequestFilter filter = factory.createAuthFilter(mock(Injector.class)); Response r1 = ClientBuilder .newClient() .register(filter) .target("http://127.0.0.1:8080/require_token") .request() .get(); assertEquals(200, r1.getStatus()); Response r2 = ClientBuilder .newClient() .register(filter) .target("http://127.0.0.1:8080/require_token") .request() .get(); assertEquals(200, r2.getStatus()); }
private SpringBootDockerCmdExecFactory() { withClientRequestFilters(new ClientRequestFilter() { @Override public void filter(ClientRequestContext requestContext) throws IOException { // Workaround for https://go-review.googlesource.com/#/c/3821/ requestContext.getHeaders().add("Connection", "close"); } }); }
@Override protected <T> T createRESTClientProxy(String apiUrl, Class<T> proxy) { URI i = null; try { i = new URI(apiUrl); } catch (URISyntaxException ex) { throw new RuntimeException(ex); } ResteasyClientBuilder builder = new ResteasyClientBuilder(); builder.connectionCheckoutTimeout(CONNECTION_SETUP_TO, TimeUnit.SECONDS); builder.socketTimeout(CONNECTION_SETUP_TO, TimeUnit.SECONDS); builder.httpEngine(new URLConnectionEngine()); ResteasyProviderFactory.getInstance().register(builder); ResteasyClient client = builder.build(); client.register(new ClientRequestFilter() { @Override public void filter(ClientRequestContext requestContext) throws IOException { requestContext.getHeaders().add("User-Agent", getImplementationName() + "=" + getVersion()); } }); ObjectMapper mapper = new ObjectMapper(); JacksonJaxbJsonProvider jaxbProvider = new JacksonJaxbJsonProvider(mapper, JacksonJaxbJsonProvider.DEFAULT_ANNOTATIONS); mapper.setAnnotationIntrospector(new JaxbAnnotationIntrospector()); mapper.configure(Feature.FAIL_ON_UNKNOWN_PROPERTIES, false); builder.register(jaxbProvider); builder.register(proxy); ResteasyWebTarget resteasyWebTarget = client.target(i); return resteasyWebTarget.proxy(proxy); }
@Override public <T> T get(Class<T> clazz, String targetServerUri, String securityToken) throws RestInterfaceFactoryException { ResteasyClient client = getResteasyClient(targetServerUri); ResteasyWebTarget target = client.target(targetServerUri); if (securityToken != null) { target.register((ClientRequestFilter) requestContext -> requestContext.getHeaders().add("Authorization", "Bearer " + securityToken)); } return target.proxy(clazz); }
private WebTarget initTarget() { WebTarget clientTarget = client.target(serverUrl); // Register the non-response object providers clientTarget.register(BucketObjectUpdateRepresentationMessageBodyReader.class); clientTarget.register(BucketObjectUpdateRepresentationClientMessageBodyWriter.class); clientTarget.register(MultipartUploadRepresentationMessageBodyReader.class); clientTarget.register(MultipartUploadRepresentationMessageBodyWriter.class); for (ClientRequestFilter filter : requestFilters) { clientTarget = clientTarget.register(filter); } return new ResponseObjectWebTarget(clientTarget, responseObjectMessageReader); }
@Override public ClientRequestFilter createAuthFilter(Injector injector) { return new OAuth2TokenAuthenticator(() -> getToken()); }
public DefaultHttpClientFactory(ClientConfig config, KeyStore trustStore, Map<String, ClientRequestFilter> authFilters) { this.authFilters = authFilters; this.config = config; this.trustStore = trustStore; }
@Before public void before() { config = new ClientConfig(); mockAuth1 = mock(ClientRequestFilter.class); mockAuth2 = mock(ClientRequestFilter.class); }
public ClientRequestFilter[] getClientRequestFilters() { return clientRequestFilters.toArray(new ClientRequestFilter[0]); }
public Config withClientRequestFilter(ClientRequestFilter clientRequestFilter) { this.clientRequestFilters.add(clientRequestFilter); return this; }
public static ClientConfig getClientConfig(final ServerContext.Type type, final Credentials credentials, final String serverUri, final boolean includeProxySettings) { final CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(AuthScope.ANY, credentials); final ConnectorProvider connectorProvider = new ApacheConnectorProvider(); // custom json provider ignores new fields that aren't recognized final JacksonJsonProvider jacksonJsonProvider = new JacksonJaxbJsonProvider() .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); final ClientConfig clientConfig = new ClientConfig(jacksonJsonProvider).connectorProvider(connectorProvider); clientConfig.property(ApacheClientProperties.CREDENTIALS_PROVIDER, credentialsProvider); clientConfig.property(ClientProperties.REQUEST_ENTITY_PROCESSING, RequestEntityProcessing.BUFFERED); // For TFS OnPrem we only support NTLM authentication right now. Since 2016 servers support Basic as well, // we need to let the server and client negotiate the protocol instead of preemptively assuming Basic. // TODO: This prevents PATs from being used OnPrem. We need to fix this soon to support PATs onPrem. clientConfig.property(ApacheClientProperties.PREEMPTIVE_BASIC_AUTHENTICATION, type != ServerContext.Type.TFS); //Define a local HTTP proxy if (includeProxySettings) { final HttpProxyService proxyService = PluginServiceProvider.getInstance().getHttpProxyService(); final String proxyUrl = proxyService.getProxyURL(); clientConfig.property(ClientProperties.PROXY_URI, proxyUrl); if (proxyService.isAuthenticationRequired()) { // To work with authenticated proxies and TFS, we provide the proxy credentials if they are registered final AuthScope ntlmAuthScope = new AuthScope(proxyService.getProxyHost(), proxyService.getProxyPort(), AuthScope.ANY_REALM, AuthScope.ANY_SCHEME); credentialsProvider.setCredentials(ntlmAuthScope, new UsernamePasswordCredentials(proxyService.getUserName(), proxyService.getPassword())); } } // if this is a onPrem server and the uri starts with https, we need to setup ssl if (isSSLEnabledOnPrem(type, serverUri)) { clientConfig.property(ApacheClientProperties.SSL_CONFIG, getSslConfigurator()); } // register a filter to set the User Agent header clientConfig.register(new ClientRequestFilter() { @Override public void filter(final ClientRequestContext requestContext) throws IOException { // The default user agent is something like "Jersey/2.6" final String defaultUserAgent = VersionInfo.getUserAgent("Apache-HttpClient", "org.apache.http.client", HttpClientBuilder.class); // We get the user agent string from the Telemetry context final String userAgent = PluginServiceProvider.getInstance().getTelemetryContextInitializer().getUserAgent(defaultUserAgent); // Finally, we can add the header requestContext.getHeaders().add(HttpHeaders.USER_AGENT, userAgent); } }); return clientConfig; }
private BlazeStorageClient(String serverUrl, ClientRequestFilter[] requestFilters) { this.serverUrl = serverUrl; this.requestFilters = requestFilters; this.client = ClientBuilder.newClient(); }
public static BlazeStorage getInstance(String serverUrl) { return new BlazeStorageClient(serverUrl, new ClientRequestFilter[0]); }
public static BlazeStorage getInstance(String serverUrl, ClientRequestFilter... requestFilters) { return new BlazeStorageClient(serverUrl, requestFilters); }
public JerseyDockerCmdExecFactory withClientRequestFilters(ClientRequestFilter... clientRequestFilters) { this.clientRequestFilters = clientRequestFilters; return this; }
private static void initialize() { /* //class MyX509TrustManager implements X509TrustManager TrustManager mytm[] = null; KeyManager mykm[] = null; try { mytm = new TrustManager[]{new MyX509TrustManager("./truststore_client", "asdfgh".toCharArray())}; mykm = new KeyManager[]{new MyX509KeyManager("./keystore_client", "asdfgh".toCharArray())}; } catch (Exception ex) { } SSLContext context = null; context = SSLContext.getInstance("SSL"); context.init(mykm, mytm, null); */ try { SSLContext context = null; context = SSLContext.getInstance("SSL"); context.init(null, null, null); SslConfigurator sslConfig = SslConfigurator.newInstance(); /* .trustStoreFile("./truststore_client") .trustStorePassword("asdfgh") .keyStoreFile("./keystore_client") .keyPassword("asdfgh"); */ //old: CLIENT.property(ClientProperties.SSL_CONFIG, new SslConfig(context)); CLIENT = ClientBuilder.newBuilder().sslContext(sslConfig.createSSLContext()).build(); DEFAULT_MAPPER = new ObjectMapper(); DEFAULT_MAPPER.setSerializationInclusion(Inclusion.NON_NULL); DEFAULT_MAPPER.enable(SerializationConfig.Feature.INDENT_OUTPUT); DEFAULT_MAPPER.enable(DeserializationConfig.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY); DEFAULT_MAPPER.disable(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES); DEFAULT_MAPPER.enable(DeserializationConfig.Feature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT); WRAPPED_MAPPER = new ObjectMapper(); WRAPPED_MAPPER.setSerializationInclusion(Inclusion.NON_NULL); WRAPPED_MAPPER.enable(SerializationConfig.Feature.INDENT_OUTPUT); WRAPPED_MAPPER.enable(SerializationConfig.Feature.WRAP_ROOT_VALUE); WRAPPED_MAPPER.enable(DeserializationConfig.Feature.UNWRAP_ROOT_VALUE); WRAPPED_MAPPER.enable(DeserializationConfig.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY); WRAPPED_MAPPER.disable(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES); WRAPPED_MAPPER.enable(DeserializationConfig.Feature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT); CLIENT.register(new JacksonFeature()).register(new ContextResolver<ObjectMapper>() { public ObjectMapper getContext(Class<?> type) { return type.getAnnotation(JsonRootName.class) == null ? DEFAULT_MAPPER : WRAPPED_MAPPER; } }); CLIENT.register(new ClientRequestFilter() { public void filter(ClientRequestContext requestContext) throws IOException { requestContext.getHeaders().remove("Content-Language"); requestContext.getHeaders().remove("Content-Encoding"); } }); } catch(Exception e) { throw new RuntimeException(e.getMessage(), e); } }
/** * @param injector DI injector that can be used to lookup extra services required by the factory. * @return * @since 0.24 */ ClientRequestFilter createAuthFilter(Injector injector);