org.eclipse.microprofile.rest.client.RestClientBuilder Java Examples
The following examples show how to use
org.eclipse.microprofile.rest.client.RestClientBuilder.
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: ProducesConsumesTest.java From microprofile-rest-client with Apache License 2.0 | 6 votes |
@Test public void testProducesConsumesAnnotationOnMethod() { final String m = "testProducesConsumesAnnotationOnClientInterface"; ProducesConsumesClient client = RestClientBuilder.newBuilder() .baseUri(URI.create("http://localhost:8080/null")) .register(ProducesConsumesFilter.class) .build(ProducesConsumesClient.class); LOG.info(m + " @Produce(application/json) @Consume(application/xml)"); Response r = client.produceJSONConsumeXML(XML_PAYLOAD); String acceptHeader = r.getHeaderString("Sent-Accept"); LOG.info(m + "Sent-Accept: " + acceptHeader); String contentTypeHeader = r.getHeaderString("Sent-ContentType"); LOG.info(m + "Sent-ContentType: " + contentTypeHeader); assertEquals(acceptHeader, MediaType.APPLICATION_JSON); assertEquals(contentTypeHeader, MediaType.APPLICATION_XML); LOG.info(m + " @Produce(application/xml) @Consume(application/json)"); r = client.produceXMLConsumeJSON(JSON_PAYLOAD); acceptHeader = r.getHeaderString("Sent-Accept"); LOG.info(m + "Sent-Accept: " + acceptHeader); contentTypeHeader = r.getHeaderString("Sent-ContentType"); LOG.info(m + "Sent-ContentType: " + contentTypeHeader); assertEquals(acceptHeader, MediaType.APPLICATION_XML); assertEquals(contentTypeHeader, MediaType.APPLICATION_JSON); }
Example #2
Source File: ClientServerAsyncTest.java From microprofile1.4-samples with MIT License | 6 votes |
@Test @RunAsClient public void testClientServerAsync() throws IOException, IllegalStateException, RestClientDefinitionException, URISyntaxException, InterruptedException, ExecutionException { HelloService remoteApi = RestClientBuilder.newBuilder() .baseUrl(base) .build(HelloService.class); String response = remoteApi.helloAsync("Programmer (Async)") .thenApply(String::toUpperCase) .toCompletableFuture() .get(); System.out.println("-------------------------------------------------------------------------"); System.out.println("Response: " + response); System.out.println("-------------------------------------------------------------------------"); assertTrue( response.contains("HELLO PROGRAMMER (ASYNC)!") ); }
Example #3
Source File: AsyncTest.java From cxf with Apache License 2.0 | 6 votes |
@Test public void testAsyncClient() throws Exception { MockWebServer mockWebServer = new MockWebServer(); URI uri = mockWebServer.url("/").uri(); AsyncClient client = RestClientBuilder.newBuilder() .baseUri(uri) .connectTimeout(5, TimeUnit.SECONDS) .readTimeout(5, TimeUnit.SECONDS) .build(AsyncClient.class); assertNotNull(client); mockWebServer.enqueue(new MockResponse().setBody("Hello")); mockWebServer.enqueue(new MockResponse().setBody("World")); String combined = client.get().thenCombine(client.get(), (a, b) -> { return a + " " + b; }).toCompletableFuture().get(10, TimeUnit.SECONDS); assertTrue("Hello World".equals(combined) || "World Hello".equals(combined)); }
Example #4
Source File: MicroProfileClientFactoryBean.java From cxf with Apache License 2.0 | 6 votes |
public MicroProfileClientFactoryBean(MicroProfileClientConfigurableImpl<RestClientBuilder> configuration, String baseUri, Class<?> aClass, ExecutorService executorService, TLSConfiguration secConfig) { super(new MicroProfileServiceFactoryBean()); this.configuration = configuration.getConfiguration(); this.comparator = MicroProfileClientProviderFactory.createComparator(this); this.executorService = executorService; this.secConfig = secConfig; super.setAddress(baseUri); super.setServiceClass(aClass); super.setProviderComparator(comparator); super.setProperties(this.configuration.getProperties()); registeredProviders = new ArrayList<>(); registeredProviders.addAll(processProviders()); if (!configuration.isDefaultExceptionMapperDisabled()) { registeredProviders.add(new ProviderInfo<>(new DefaultResponseExceptionMapper(), getBus(), false)); } registeredProviders.add(new ProviderInfo<>(new JsrJsonpProvider(), getBus(), false)); super.setProviders(registeredProviders); }
Example #5
Source File: AdditionalRegistrationTest.java From microprofile-rest-client with Apache License 2.0 | 6 votes |
@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()); } }
Example #6
Source File: DefaultExceptionMapperConfigTest.java From microprofile-rest-client with Apache License 2.0 | 6 votes |
@Test public void testNoExceptionThrownWhenDisabledDuringBuild() throws Exception { stubFor(get(urlEqualTo("/")).willReturn(aResponse().withStatus(STATUS).withBody(BODY))); SimpleGetApi simpleGetApi = RestClientBuilder.newBuilder() .baseUri(getServerURI()) .build(SimpleGetApi.class); try { Response response = simpleGetApi.executeGet(); assertEquals(response.getStatus(), STATUS); } catch (Exception w) { fail("No exception should be thrown", w); } }
Example #7
Source File: ClientHeadersTest.java From cxf with Apache License 2.0 | 6 votes |
@Test public void testClientHeadersFactory() { HeadersFactoryClient client = RestClientBuilder.newBuilder() .baseUri(URI.create("http://localhost/notUsed")) .register(HeaderCaptureClientRequestFilter.class) .build(HeadersFactoryClient.class); assertEquals("SUCCESS", client.get("headerParamValue1")); assertNotNull(getInitialHeaders()); assertEquals("headerParamValue1", getInitialHeaders().getFirst("HeaderParam1")); assertEquals("abc", getInitialHeaders().getFirst("IntfHeader1")); assertEquals("def", getInitialHeaders().getFirst("MethodHeader1")); assertNotNull(getOutboundHeaders()); assertEquals("1eulaVmaraPredaeh", getOutboundHeaders().getFirst("HeaderParam1")); assertEquals("cba", getOutboundHeaders().getFirst("IntfHeader1")); assertEquals("fed", getOutboundHeaders().getFirst("MethodHeader1")); }
Example #8
Source File: DefaultExceptionMapperTest.java From microprofile-rest-client with Apache License 2.0 | 6 votes |
@Test public void testNoExceptionThrownWhenDisabledDuringBuild() throws Exception { stubFor(get(urlEqualTo("/")).willReturn(aResponse().withStatus(STATUS).withBody(BODY))); SimpleGetApi simpleGetApi = RestClientBuilder.newBuilder() .baseUri(getServerURI()) .property("microprofile.rest.client.disable.default.mapper", true) .build(SimpleGetApi.class); try { Response response = simpleGetApi.executeGet(); assertEquals(response.getStatus(), STATUS); } catch (Exception w) { fail("No exception should be thrown", w); } }
Example #9
Source File: RestClientServices.java From microprofile-opentracing with Apache License 2.0 | 6 votes |
private void executeNestedMpRestClient(int depth, int breath, String id, boolean async) throws MalformedURLException, InterruptedException, ExecutionException { URL webServicesUrl = new URL(getBaseURL().toString() + "rest/" + REST_SERVICE_PATH); ClientServices clientServices = RestClientBuilder.newBuilder() .baseUrl(webServicesUrl) .executorService(Executors.newFixedThreadPool(50)) .build(ClientServices.class); if (async) { CompletionStage<Response> completionStage = clientServices.executeNestedAsync(depth, breath, async, id, false); completionStage.toCompletableFuture() .get(); } else { clientServices.executeNested(depth, breath, async, id, false) .close(); } }
Example #10
Source File: RestClientProxyTest.java From thorntail with Apache License 2.0 | 6 votes |
@Test public void testClose() throws InterruptedException, IllegalStateException, RestClientDefinitionException, MalformedURLException { counter.reset(1); HelloClient helloClient = RestClientBuilder.newBuilder().baseUrl(url).build(HelloClient.class); RestClientProxy clientProxy = (RestClientProxy) helloClient; assertEquals("C:OK1:C", helloClient.hello()); clientProxy.close(); assertTrue(CharlieService.DESTROYED.get()); // Further calls are no-op clientProxy.close(); // Invoking any method on the client proxy should result in ISE try { helloClient.hello(); fail(); } catch (IllegalStateException expected) { } }
Example #11
Source File: ExceptionMapperTest.java From microprofile-rest-client with Apache License 2.0 | 6 votes |
@Test public void testWithOneRegisteredProvider() throws Exception { stubFor(get(urlEqualTo("/")).willReturn(aResponse().withHeader("CustomHeader", "true") .withBody("body is ignored in this test"))); SimpleGetApi simpleGetApi = RestClientBuilder.newBuilder() .baseUri(getServerURI()) .register(TestResponseExceptionMapper.class) .build(SimpleGetApi.class); try { simpleGetApi.executeGet(); fail("A "+WebApplicationException.class+" should have been thrown via the registered "+TestResponseExceptionMapper.class); } catch (WebApplicationException w) { assertEquals(w.getMessage(), TestResponseExceptionMapper.MESSAGE, "The message should be sourced from "+TestResponseExceptionMapper.class); assertTrue(TestResponseExceptionMapper.isHandlesCalled(), "The handles method should have been called on "+TestResponseExceptionMapper.class); assertTrue(TestResponseExceptionMapper.isThrowableCalled(), "The toThrowable method should have been called on "+TestResponseExceptionMapper.class); } }
Example #12
Source File: BasicReactiveStreamsTest.java From microprofile-rest-client with Apache License 2.0 | 6 votes |
@Test public void testDataOnlySse_JsonObject() throws Exception { LOG.debug("testDataOnlySse_JsonObject"); CountDownLatch resultsLatch = new CountDownLatch(3); AtomicReference<Throwable> serverException = launchServer(resultsLatch, es -> { es.emitData("{\"date\":\"2020-01-21\", \"description\":\"Significant snowfall\"}"); es.emitData("{\"date\":\"2020-02-16\", \"description\":\"Hail storm\"}"); es.emitData("{\"date\":\"2020-04-12\", \"description\":\"Blizzard\"}"); }); RsWeatherEventClient client = RestClientBuilder.newBuilder() .baseUri(URI.create("http://localhost:" + PORT+ "/string/sse")) .build(RsWeatherEventClient.class); Publisher<WeatherEvent> publisher = client.getEvents(); WeatherEventSubscriber subscriber = new WeatherEventSubscriber(3, resultsLatch); publisher.subscribe(subscriber); assertTrue(resultsLatch.await(30, TimeUnit.SECONDS)); DateFormat df = new SimpleDateFormat("yyyy-MM-dd"); assertEquals(subscriber.weatherEvents, new HashSet<>(Arrays.asList( new WeatherEvent(df.parse("2020-01-21"), "Significant snowfall"), new WeatherEvent(df.parse("2020-02-16"), "Hail storm"), new WeatherEvent(df.parse("2020-04-12"), "Blizzard")))); assertNull(serverException.get()); assertNull(subscriber.throwable); }
Example #13
Source File: InvokeSimpleGetOperationTest.java From microprofile-rest-client with Apache License 2.0 | 6 votes |
@Test public void testGetExecutionWithBuiltClient() throws Exception{ String expectedBody = "Hello, MicroProfile!"; stubFor(get(urlEqualTo("/")) .willReturn(aResponse() .withBody(expectedBody))); SimpleGetApi simpleGetApi = RestClientBuilder.newBuilder() .baseUri(getServerURI()) .build(SimpleGetApi.class); Response response = simpleGetApi.executeGet(); String body = response.readEntity(String.class); response.close(); assertEquals(body, expectedBody); verify(1, getRequestedFor(urlEqualTo("/"))); }
Example #14
Source File: FaultToleranceTest.java From thorntail with Apache License 2.0 | 6 votes |
@Test public void testTimeout() throws InterruptedException, IllegalStateException, RestClientDefinitionException, MalformedURLException { HelloClient helloClient = RestClientBuilder.newBuilder().baseUrl(url).build(HelloClient.class); counter.reset(1); timer.reset(400); latch.reset(1); try { helloClient.helloTimeout(); fail(); } catch (TimeoutException expected) { } latch.await(); }
Example #15
Source File: AsyncMethodTest.java From microprofile-rest-client with Apache License 2.0 | 6 votes |
/** * Tests that a Rest Client interface method that returns a CompletionStage * where it's parameterized type is some Object type other than Response) is * invoked asychronously - checking that the thread ID of the response does * not match the thread ID of the calling thread. * * @throws Exception - indicates test failure */ @Test public void testInterfaceMethodWithCompletionStageObjectReturnIsInvokedAsynchronously() throws Exception{ final String expectedBody = "Hello, Future Async Client!!"; stubFor(get(urlEqualTo("/string")) .willReturn(aResponse() .withBody(expectedBody))); final String mainThreadId = "" + Thread.currentThread().getId(); ThreadedClientResponseFilter filter = new ThreadedClientResponseFilter(); StringResponseClientAsync client = RestClientBuilder.newBuilder() .baseUrl(getServerURL()) .register(filter) .build(StringResponseClientAsync.class); CompletionStage<String> future = client.get(); String body = future.toCompletableFuture().get(); String responseThreadId = filter.getResponseThreadId(); assertNotNull(responseThreadId); assertNotEquals(responseThreadId, mainThreadId); assertEquals(body, expectedBody); verify(1, getRequestedFor(urlEqualTo("/string"))); }
Example #16
Source File: SslMutualTest.java From microprofile-rest-client with Apache License 2.0 | 5 votes |
@Test(expectedExceptions = ProcessingException.class) public void shouldFailWithNoClientSignature() throws Exception { KeyStore trustStore = getKeyStore(clientTruststore); RestClientBuilder.newBuilder() .baseUri(BASE_URI) .trustStore(trustStore) .build(JsonPClient.class) .get("1"); }
Example #17
Source File: CDIManagedProviderTest.java From microprofile-rest-client with Apache License 2.0 | 5 votes |
@Test public void testCDIProviderSpecifiedViaRestClientBuilder() throws Exception { MyProgrammaticClient client = RestClientBuilder.newBuilder() .baseUri(URI.create(STUB_URI)) .register(MyFilter.class) .build(MyProgrammaticClient.class); Response r = client.executeGet(); assertEquals(r.getStatus(), 200); }
Example #18
Source File: InvokeWithBuiltProvidersTest.java From microprofile-rest-client with Apache License 2.0 | 5 votes |
private InterfaceWithoutProvidersDefined createClient() throws MalformedURLException{ return RestClientBuilder.newBuilder() .register(TestClientRequestFilter.class) .register(TestClientResponseFilter.class) .register(TestMessageBodyReader.class) .register(TestMessageBodyWriter.class) .register(TestParamConverterProvider.class) .register(TestReaderInterceptor.class) .register(TestWriterInterceptor.class) .baseUri(getServerURI()) .build(InterfaceWithoutProvidersDefined.class); }
Example #19
Source File: CDIManagedProviderTest.java From microprofile-rest-client with Apache License 2.0 | 5 votes |
@Test public void testInstanceProviderSpecifiedViaRestClientBuilderDoesNotUseCDIManagedProvider() throws Exception { MyProgrammaticClient client = RestClientBuilder.newBuilder() .baseUri(URI.create("http://localhost:9080/stub")) .register(new MyFilter()) .build(MyProgrammaticClient.class); Response r = client.executeGet(); assertEquals(r.getStatus(), 204); }
Example #20
Source File: AdditionalRegistrationTest.java From microprofile-rest-client with Apache License 2.0 | 5 votes |
@Test public void testPropertiesRegistered() { String key = "key"; Object value = new Object(); RestClientBuilder builder = RestClientBuilder.newBuilder().property(key, value); Configuration configuration = builder.getConfiguration(); assertTrue(configuration.getPropertyNames().contains(key), "The key "+key+" should be a property"); assertEquals(configuration.getProperty(key), value, "The value of "+key+" should be "+value); }
Example #21
Source File: InheritanceTest.java From microprofile-rest-client with Apache License 2.0 | 5 votes |
@Test public void canInvokeMethodOnBaseInterface() throws Exception { ReturnWithURLRequestFilter filter = new ReturnWithURLRequestFilter(); RestClientBuilder builder = RestClientBuilder.newBuilder().register(filter); BaseClient client = builder.baseUri(new URI("http://localhost/stub")).build(ChildClient.class); Response response = client.executeBaseGet(); assertEquals(response.getStatus(), 200, "Unexpected response status code"); String responseStr = response.readEntity(String.class); assertNotNull(responseStr, "Response entity is null"); assertTrue(responseStr.contains("GET ") && responseStr.contains("/base"), "Did not invoke expected method/URI. Expected GET .../base ; got " + responseStr); }
Example #22
Source File: SslTrustStoreTest.java From microprofile-rest-client with Apache License 2.0 | 5 votes |
@Test(expectedExceptions = ProcessingException.class) public void shouldFailWithSelfSignedKeystore() { RestClientBuilder.newBuilder() .baseUri(BASE_URI) .build(JsonPClient.class) .get("1"); }
Example #23
Source File: SslTrustStoreTest.java From microprofile-rest-client with Apache License 2.0 | 5 votes |
@Test public void shouldSucceedWithRegisteredSelfSignedKeystore() throws Exception { KeyStore trustStore = getKeyStore(clientTruststore); JsonPClient client = RestClientBuilder.newBuilder() .baseUri(BASE_URI) .trustStore(trustStore) .build(JsonPClient.class); assertEquals("bar", client.get("1").getString("foo")); }
Example #24
Source File: CustomHttpMethodTest.java From microprofile-rest-client with Apache License 2.0 | 5 votes |
@Test public void invokesUserDefinedHttpMethod() throws Exception { CustomHttpMethodFilter filter = new CustomHttpMethodFilter(); RestClientBuilder builder = RestClientBuilder.newBuilder().register(filter); CustomHttpMethod client = builder.baseUri(new URI("http://localhost/stub")).build(CustomHttpMethod.class); Response response = client.executeMyMethod(); assertEquals(response.getStatus(), 200, "Unexpected HTTP Method sent from client - " + "expected \"MYMETHOD\", was \"" + response.readEntity(String.class) + "\""); }
Example #25
Source File: SslTrustStoreTest.java From microprofile-rest-client with Apache License 2.0 | 5 votes |
@Test(expectedExceptions = ProcessingException.class) public void shouldFailWithNonMatchingKeystore() throws Exception { KeyStore ks = getKeyStore(anotherTruststore); RestClientBuilder.newBuilder() .baseUri(BASE_URI) .trustStore(ks) .build(JsonPClient.class) .get("1"); }
Example #26
Source File: SslContextTest.java From microprofile-rest-client with Apache License 2.0 | 5 votes |
@Test(expectedExceptions = ProcessingException.class) public void shouldFailedMutualSslWithoutSslContext() { RestClientBuilder.newBuilder() .baseUri(BASE_URI) .build(JsonPClient.class) .get("1"); }
Example #27
Source File: SslHostnameVerifierTest.java From microprofile-rest-client with Apache License 2.0 | 5 votes |
@Test(expectedExceptions = ProcessingException.class) public void shouldFailWithoutHostnameAndNoVerifier() throws Exception { KeyStore trustStore = getKeyStore(clientWrongHostnameTruststore); RestClientBuilder.newBuilder() .baseUri(BASE_URI) .trustStore(trustStore) .build(JsonPClient.class) .get("1"); }
Example #28
Source File: MetricsTest.java From thorntail with Apache License 2.0 | 5 votes |
@Test public void testCounted() throws IllegalStateException, RestClientDefinitionException { counter.reset(1); timer.reset(0); HelloMetricsClient helloClient = RestClientBuilder.newBuilder().baseUrl(url).build(HelloMetricsClient.class); assertEquals("OK1", helloClient.helloCounted()); assertEquals("OK2", helloClient.helloCounted()); assertEquals("OK3", helloClient.helloCounted()); org.eclipse.microprofile.metrics.Counter metricsCounter = registry.getCounters().get(new MetricID(HelloMetricsClient.COUNTED_NAME)); assertNotNull(metricsCounter); assertEquals(3, metricsCounter.getCount()); }
Example #29
Source File: CallMultipleMappersTest.java From microprofile-rest-client with Apache License 2.0 | 5 votes |
@Test public void testCallsTwoProvidersWithTwoRegisteredProvider() throws Exception { TestResponseExceptionMapper.reset(); TestResponseExceptionMapperHandles.reset(); stubFor(get(urlEqualTo("/")).willReturn(aResponse().withBody("body is ignored in this test"))); SimpleGetApi simpleGetApi = RestClientBuilder.newBuilder() .baseUri(getServerURI()) .register(TestResponseExceptionMapper.class) .register(TestResponseExceptionMapperHandles.class) .build(SimpleGetApi.class); try { simpleGetApi.executeGet(); fail("A "+WebApplicationException.class+" should have been thrown via the registered "+TestResponseExceptionMapper.class); } catch (WebApplicationException w) { assertEquals(w.getMessage(), TestResponseExceptionMapper.MESSAGE, "The message should be sourced from "+TestResponseExceptionMapper.class); assertTrue(TestResponseExceptionMapper.isHandlesCalled(), "The handles method should have been called on "+TestResponseExceptionMapper.class); assertTrue(TestResponseExceptionMapper.isThrowableCalled(), "The toThrowable method should have been called on "+TestResponseExceptionMapper.class); // it should still have called the other mapper assertTrue(TestResponseExceptionMapperHandles.isHandlesCalled(), "The handles method should have been called on "+TestResponseExceptionMapperHandles.class); assertTrue(TestResponseExceptionMapperHandles.isThrowableCalled(), "The toThrowable method should have been called on "+TestResponseExceptionMapperHandles.class); } }
Example #30
Source File: BasicReactiveStreamsTest.java From microprofile-rest-client with Apache License 2.0 | 5 votes |
@Test public void testNamedEventSse() throws Exception { CountDownLatch resultsLatch = new CountDownLatch(3); AtomicReference<Throwable> subscriptionException = new AtomicReference<>(); AtomicReference<Throwable> serverException = launchServer(resultsLatch, es -> { es.emitNamedEvent("1", "{\"date\":\"2020-01-21\", \"description\":\"Significant snowfall\"}"); sleep(500); es.emitNamedEvent("2", "{\"date\":\"2020-02-16\", \"description\":\"Hail storm\"}"); sleep(500); es.emitNamedEvent("3", "{\"date\":\"2020-04-12\", \"description\":\"Blizzard\"}"); }); RsSseClient client = RestClientBuilder.newBuilder() .baseUri(URI.create("http://localhost:" + PORT+ "/string/sse")) .build(RsSseClient.class); Publisher<InboundSseEvent> publisher = client.getEvents(); InboundSseEventSubscriber subscriber = new InboundSseEventSubscriber(3, resultsLatch); publisher.subscribe(subscriber); assertTrue(resultsLatch.await(40, TimeUnit.SECONDS)); assertEquals(subscriber.names, new HashSet<>(Arrays.asList("1", "2", "3"))); assertEquals(subscriber.data, new HashSet<>(Arrays.asList( "{\"date\":\"2020-01-21\", \"description\":\"Significant snowfall\"}", "{\"date\":\"2020-02-16\", \"description\":\"Hail storm\"}", "{\"date\":\"2020-04-12\", \"description\":\"Blizzard\"}"))); assertNull(serverException.get()); assertNull(subscriptionException.get()); }