Java源码示例:org.eclipse.microprofile.rest.client.RestClientBuilder

示例1
@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)!")
    );
}
 
示例2
@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));
}
 
示例3
@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"));
    
}
 
示例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();
    }
}
 
示例5
@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) {
    }
}
 
示例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);
}
 
示例7
/**
 * 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")));
}
 
示例8
@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();
}
 
示例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("/")));
}
 
示例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);
}
 
示例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);
    }
}
 
示例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);
    }
}
 
示例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);
    }
}
 
示例14
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);
}
 
示例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());
    }
}
 
示例16
@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());
}
 
示例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();
}
 
示例18
@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"));
}
 
示例19
@Before
public void setup() throws MalformedURLException {
    client = RestClientBuilder.newBuilder()
                    .baseUrl(new URL(baseUrl))
                    .register(ApiException.class)
                    .build(UserApi.class);
}
 
示例20
@Override
public RestClientBuilder executorService(ExecutorService executor) {
    if (null == executor) {
        throw new IllegalArgumentException("executor must not be null");
    }
    this.executorService = executor;
    return this;
}
 
示例21
@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();
}
 
示例22
@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();
}
 
示例23
@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();
}
 
示例24
@Override
public Response restClient() {
    RestService client = RestClientBuilder.newBuilder()
            .baseUri(uri.getBaseUri())
            .build(RestService.class);
    client.hello();
    return Response.ok().build();
}
 
示例25
@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));
}
 
示例26
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);
    }
}
 
示例27
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();
}
 
示例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");
}
 
示例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();
}
 
示例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"));
}