Java Code Examples for org.eclipse.microprofile.rest.client.RestClientBuilder

The following examples show how to use org.eclipse.microprofile.rest.client.RestClientBuilder. These examples are extracted from open source projects. 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 Project: microprofile1.4-samples   Source File: ClientServerAsyncTest.java    License: MIT License 6 votes vote down vote up
@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 2
Source Project: cxf   Source File: AsyncTest.java    License: Apache License 2.0 6 votes vote down vote up
@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 3
Source Project: cxf   Source File: ClientHeadersTest.java    License: Apache License 2.0 6 votes vote down vote up
@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 4
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 5
Source Project: thorntail   Source File: RestClientProxyTest.java    License: Apache License 2.0 6 votes vote down vote up
@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 6
@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 7
Source Project: microprofile-rest-client   Source File: AsyncMethodTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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 8
Source Project: thorntail   Source File: FaultToleranceTest.java    License: Apache License 2.0 6 votes vote down vote up
@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 9
@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 10
@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 11
@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
@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 13
@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 14
Source Project: cxf   Source File: MicroProfileClientFactoryBean.java    License: Apache License 2.0 6 votes vote down vote up
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 15
@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 16
Source Project: thorntail   Source File: MetricsTest.java    License: Apache License 2.0 5 votes vote down vote up
@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 17
@GET
@Path("/proxyUserTZ")
@Produces(MediaType.APPLICATION_JSON)
public Now proxyUserTZ() {
    UserTimeService remoteApi = RestClientBuilder.newBuilder()
            .baseUri(URI.create(targetBaseUri))
            .build(UserTimeService.class);
    return remoteApi.userNow();
}
 
Example 18
Source Project: cxf   Source File: CxfTypeSafeClientBuilderTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testProxyAddressSetsProperty() {
    CxfTypeSafeClientBuilder builder = (CxfTypeSafeClientBuilder)
        RestClientBuilder.newBuilder().proxyAddress("cxf.apache.org", 8080);
    assertEquals("cxf.apache.org", builder.getConfiguration().getProperty("http.proxy.server.uri"));
    assertEquals(8080, builder.getConfiguration().getProperty("http.proxy.server.port"));
}
 
Example 19
Source Project: openapi-generator   Source File: UserApiTest.java    License: Apache License 2.0 5 votes vote down vote up
@Before
public void setup() throws MalformedURLException {
    client = RestClientBuilder.newBuilder()
                    .baseUrl(new URL(baseUrl))
                    .register(ApiException.class)
                    .build(UserApi.class);
}
 
Example 20
Source Project: cxf   Source File: CxfTypeSafeClientBuilder.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public RestClientBuilder executorService(ExecutorService executor) {
    if (null == executor) {
        throw new IllegalArgumentException("executor must not be null");
    }
    this.executorService = executor;
    return this;
}
 
Example 21
Source Project: quarkus   Source File: ClientResource.java    License: Apache License 2.0 5 votes vote down vote up
@GET
@Path("/manual")
public String manual() throws Exception {
    ProgrammaticRestInterface iface = RestClientBuilder.newBuilder()
            .baseUrl(new URL(ConfigProvider.getConfig().getValue("test.url", String.class)))
            .build(ProgrammaticRestInterface.class);
    return iface.get();
}
 
Example 22
Source Project: quarkus   Source File: ClientResource.java    License: Apache License 2.0 5 votes vote down vote up
@GET
@Path("/manual/complex")
@Produces("application/json")
public List<ComponentType> complexManual() throws Exception {
    ProgrammaticRestInterface iface = RestClientBuilder.newBuilder()
            .baseUrl(new URL(ConfigProvider.getConfig().getValue("test.url", String.class)))
            .build(ProgrammaticRestInterface.class);
    System.out.println(iface.complex());
    return iface.complex();
}
 
Example 23
Source Project: quarkus   Source File: ClientResource.java    License: Apache License 2.0 5 votes vote down vote up
@GET
@Path("/manual/headers")
@Produces("application/json")
public Map<String, String> getAllHeaders(String headerValue) throws Exception {
    ProgrammaticRestInterface client = RestClientBuilder.newBuilder()
            .baseUrl(new URL(ConfigProvider.getConfig().getValue("test.url", String.class)))
            .build(ProgrammaticRestInterface.class);
    return client.getAllHeaders();
}
 
Example 24
Source Project: quarkus   Source File: TestResource.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Response restClient() {
    RestService client = RestClientBuilder.newBuilder()
            .baseUri(uri.getBaseUri())
            .build(RestService.class);
    client.hello();
    return Response.ok().build();
}
 
Example 25
Source Project: cxf   Source File: CxfTypeSafeClientBuilderTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testCanInvokeDefaultInterfaceMethods() throws Exception {
    MyClient client = RestClientBuilder.newBuilder()
        .register(InvokedMethodClientRequestFilter.class)
        .baseUri(new URI("http://localhost:8080/neverUsed"))
        .build(MyClient.class);
    assertEquals("defaultValue", client.myDefaultMethod(false));
}
 
Example 26
Source Project: quarkus   Source File: RestClientBase.java    License: Apache License 2.0 5 votes vote down vote up
private void configureTimeouts(RestClientBuilder builder) {
    Optional<Long> connectTimeout = getOptionalProperty(REST_CONNECT_TIMEOUT_FORMAT, Long.class);
    if (connectTimeout.isPresent()) {
        builder.connectTimeout(connectTimeout.get(), TimeUnit.MILLISECONDS);
    }

    Optional<Long> readTimeout = getOptionalProperty(REST_READ_TIMEOUT_FORMAT, Long.class);
    if (readTimeout.isPresent()) {
        builder.readTimeout(readTimeout.get(), TimeUnit.MILLISECONDS);
    }
}
 
Example 27
Source Project: microprofile-sandbox   Source File: BridgeBoundary.java    License: Apache License 2.0 5 votes vote down vote up
private API target(@QueryParam("mode") Mode mode) {
    switch (mode) {
        case jaxRs:
            return this::jaxRsCall;
        case mMpRest:
            return RestClientBuilder.newBuilder().baseUri(URI.create(BASE_URI)).build(API.class);
        case iMpRest:
            return this.target;
    }
    throw new UnsupportedOperationException();
}
 
Example 28
@Test
public void shouldRegisterInstance() {
    TestClientRequestFilter instance = new TestClientRequestFilter();
    RestClientBuilder builder = RestClientBuilder.newBuilder().register(instance);
    Configuration configuration = builder.getConfiguration();
    assertTrue(configuration.isRegistered(TestClientRequestFilter.class), TestClientRequestFilter.class + " should be registered");
    assertTrue(configuration.isRegistered(instance), TestClientRequestFilter.class + " should be registered");
}
 
Example 29
@GET
@Path(REST_MP_REST_CLIENT_DISABLED_TRACING_METHOD)
@Produces(MediaType.TEXT_PLAIN)
public Response restClientMethodTracingDisabled() throws MalformedURLException {
    URL webServicesUrl = new URL(getBaseURL().toString() + "rest/" + TestServerWebServices.REST_TEST_SERVICE_PATH);
    ClientServices client = RestClientBuilder.newBuilder()
        .baseUrl(webServicesUrl)
        .build(ClientServices.class);
    client.disabledTracing();
    return Response.ok().build();
}
 
Example 30
@Test
public void shouldSucceedWithAcceptingHostnameVerifier() throws Exception {
    KeyStore trustStore = getKeyStore(clientWrongHostnameTruststore);
    JsonPClient client = RestClientBuilder.newBuilder()
        .baseUri(BASE_URI)
        .trustStore(trustStore)
        .hostnameVerifier((s, sslSession) -> true)
        .build(JsonPClient.class);

    assertEquals("bar", client.get("1").getString("foo"));
}