Java Code Examples for org.apache.cxf.jaxrs.client.WebClient#close()

The following examples show how to use org.apache.cxf.jaxrs.client.WebClient#close() . 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: AbstractSwagger2ServiceDescriptionTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Test
@Ignore
public void testApiListingIsProperlyReturnedYAML() throws Exception {
    final WebClient client = createWebClient("/swagger.yaml");

    try {
        final Response r = client.get();
        assertEquals(Status.OK.getStatusCode(), r.getStatus());
        //REVISIT find a better way of reliably comparing two yaml instances.
        // I noticed that yaml.load instantiates a Map and
        // for an integer valued key, an Integer or a String is arbitrarily instantiated,
        // which leads to the assertion error. So, we serilialize the yamls and compare the re-serialized texts.
        Yaml yaml = new Yaml();
        assertEquals(yaml.load(getExpectedValue(getExpectedFileYaml(), getPort())).toString(),
                     yaml.load(IOUtils.readStringFromStream((InputStream)r.getEntity())).toString());

    } finally {
        client.close();
    }
}
 
Example 2
Source File: JAXRSAsyncClientTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetBookResponseProcessingException() throws Exception {
    String address = "http://localhost:" + PORT + "/bookstore/books/123";
    List<Object> providers = new ArrayList<>();
    providers.add(new FaultyBookReader());
    WebClient wc = WebClient.create(address, providers);

    Future<Book> future = wc.async().get(Book.class);
    try {
        future.get();
        fail("Exception expected");
    } catch (ExecutionException ex) {
        assertTrue(ex.getCause() instanceof ResponseProcessingException);
    }
    wc.close();
}
 
Example 3
Source File: JAXRSAsyncClientTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Test
public void testPostBookProcessingException() throws Exception {
    String address = "http://localhost:" + PORT + "/bookstore/";
    List<Object> providers = new ArrayList<>();
    providers.add(new FaultyBookWriter());
    WebClient wc = WebClient.create(address, providers);

    Future<Book> future = wc.async().post(Entity.xml(new Book()), Book.class);
    try {
        future.get();
        fail("Exception expected");
    } catch (ExecutionException ex) {
        assertTrue(ex.getCause() instanceof ProcessingException);
    }
    wc.close();
}
 
Example 4
Source File: RESTLoggingTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testBinary() throws IOException, InterruptedException {
    LoggingFeature loggingFeature = new LoggingFeature();
    TestEventSender sender = new TestEventSender();
    loggingFeature.setSender(sender);
    Server server = createService(SERVICE_URI_BINARY, new TestServiceRestBinary(), loggingFeature);
    server.start();
    WebClient client = createClient(SERVICE_URI_BINARY, loggingFeature);
    client.get(InputStream.class).close();
    loggingFeature.setLogBinary(true);
    client.get(InputStream.class).close();
    client.close();
    List<LogEvent> events = sender.getEvents();
    await().until(() -> events.size(), is(8));
    server.stop();
    server.destroy();

    Assert.assertEquals(8, events.size());
    
    // First call with binary logging false
    assertContentLogged(events.get(0));
    assertContentLogged(events.get(1));
    assertContentNotLogged(events.get(2));
    assertContentNotLogged(events.get(3));
    
    // Second call with binary logging true
    assertContentLogged(events.get(4));
    assertContentLogged(events.get(5));
    assertContentLogged(events.get(6));
    assertContentLogged(events.get(7));
}
 
Example 5
Source File: ClientImpl.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Override
public void close() {
    if (!closed) {
        synchronized (baseClients) {
            for (WebClient wc : baseClients) {
                wc.close();
            }
        }
        baseClients = null;
        closed = true;
    }

}
 
Example 6
Source File: JAXRSMultipartTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testLargerThanDefaultHeader() throws Exception {
    InputStream is1 =
        getClass().getResourceAsStream("/org/apache/cxf/systest/jaxrs/resources/java.jpg");
    String address = "http://localhost:" + PORT + "/bookstore/books/image";
    WebClient client = WebClient.create(address);
    client.type("multipart/mixed").accept("multipart/mixed");
    WebClient.getConfig(client).getRequestContext().put("support.type.as.multipart",
        "true");

    StringBuilder sb = new StringBuilder(64);
    sb.append("form-data;");
    for (int i = 0; i < 35; i++) {
        sb.append("aaaaaaaaaa");
    }

    MultivaluedMap<String, String> headers = new MultivaluedHashMap<>();
    headers.putSingle("Content-ID", "root");
    headers.putSingle("Content-Type", "application/octet-stream");
    headers.putSingle("Content-Disposition", sb.toString());
    DataHandler handler = new DataHandler(new InputStreamDataSource(is1, "application/octet-stream"));

    Attachment att = new Attachment(headers, handler, null);
    Response response = client.post(att);
    assertEquals(response.getStatus(), 200);

    client.close();
}
 
Example 7
Source File: JAXRSMultipartTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testLargeHeader() throws Exception {
    InputStream is1 =
        getClass().getResourceAsStream("/org/apache/cxf/systest/jaxrs/resources/java.jpg");
    String address = "http://localhost:" + PORT + "/bookstore/books/image";
    WebClient client = WebClient.create(address);
    client.type("multipart/mixed").accept("multipart/mixed");
    WebClient.getConfig(client).getRequestContext().put("support.type.as.multipart",
        "true");

    StringBuilder sb = new StringBuilder(100500);
    sb.append("form-data;");
    for (int i = 0; i < 10000; i++) {
        sb.append("aaaaaaaaaa");
    }

    MultivaluedMap<String, String> headers = new MultivaluedHashMap<>();
    headers.putSingle("Content-ID", "root");
    headers.putSingle("Content-Type", "application/octet-stream");
    headers.putSingle("Content-Disposition", sb.toString());
    DataHandler handler = new DataHandler(new InputStreamDataSource(is1, "application/octet-stream"));

    Attachment att = new Attachment(headers, handler, null);
    Response response = client.post(att);
    assertEquals(response.getStatus(), 413);

    client.close();
}
 
Example 8
Source File: JAXRSAsyncClientTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetBookAsync404Callback() throws Exception {
    String address = "http://localhost:" + PORT + "/bookstore/bookheaders/404";
    WebClient wc = createWebClient(address);
    final Holder<Object> holder = new Holder<>();
    InvocationCallback<Object> callback = createCallback(holder);
    try {
        wc.async().get(callback).get();
        fail("Exception expected");
    } catch (ExecutionException ex) {
        assertTrue(ex.getCause() instanceof NotFoundException);
        assertTrue(ex.getCause() == holder.value);
    }
    wc.close();
}
 
Example 9
Source File: WebClientBuilder.java    From peer-os with Apache License 2.0 5 votes vote down vote up
public static void close( WebClient webClient )
{
    if ( webClient != null )
    {
        try
        {
            webClient.close();
        }
        catch ( Exception e )
        {
            LOG.warn( e.getMessage() );
        }
    }
}
 
Example 10
Source File: JAXRSAsyncClientTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetBookAsync404() throws Exception {
    String address = "http://localhost:" + PORT + "/bookstore/bookheaders/404";
    WebClient wc = createWebClient(address);
    Future<Book> future = wc.async().get(Book.class);
    try {
        future.get();
        fail("Exception expected");
    } catch (ExecutionException ex) {
        assertTrue(ex.getCause() instanceof NotFoundException);
    }
    wc.close();
}
 
Example 11
Source File: JAXRSAsyncClientTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetBookAsyncResponse404() throws Exception {
    String address = "http://localhost:" + PORT + "/bookstore/bookheaders/404";
    WebClient wc = createWebClient(address);
    Future<Response> future = wc.async().get(Response.class);
    assertEquals(404, future.get().getStatus());
    wc.close();
}
 
Example 12
Source File: JAXRSAsyncClientTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testRetrieveBookCustomMethodAsync() throws Exception {
    String address = "http://localhost:" + PORT + "/bookstore/retrieve";
    WebClient wc = WebClient.create(address);
    wc.accept("application/xml");
    Future<Book> book = wc.async().method("RETRIEVE", Entity.xml(new Book("Retrieve", 123L)),
                                          Book.class);
    assertEquals("Retrieve", book.get().getName());
    wc.close();
}
 
Example 13
Source File: JAXRSAsyncClientTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testDeleteWithBody() throws Exception {
    String address = "http://localhost:" + PORT + "/bookstore/deletebody";
    WebClient wc = WebClient.create(address);
    wc.type("application/xml").accept("application/xml");
    WebClient.getConfig(wc).getRequestContext().put("use.async.http.conduit", true);
    Book book = wc.invoke("DELETE", new Book("Delete", 123L), Book.class);
    assertEquals("Delete", book.getName());
    wc.close();
}
 
Example 14
Source File: JAXRSAsyncClientTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testPatchBookInputStream() throws Exception {
    String address = "http://localhost:" + PORT + "/bookstore/patch";
    WebClient wc = WebClient.create(address);
    wc.type("application/xml");
    WebClient.getConfig(wc).getRequestContext().put("use.async.http.conduit", true);
    Book book = wc.invoke("PATCH",
                          new ByteArrayInputStream(
                              "<Book><name>Patch</name><id>123</id></Book>".getBytes()),
                          Book.class);
    assertEquals("Patch", book.getName());
    wc.close();
}
 
Example 15
Source File: JAXRSAsyncClientTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testPatchBook() throws Exception {
    String address = "http://localhost:" + PORT + "/bookstore/patch";
    WebClient wc = WebClient.create(address);
    wc.type("application/xml");
    WebClient.getConfig(wc).getRequestContext().put("use.async.http.conduit", true);
    Book book = wc.invoke("PATCH", new Book("Patch", 123L), Book.class);
    assertEquals("Patch", book.getName());
    wc.close();
}
 
Example 16
Source File: JAXRSAsyncClientTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testRetrieveBookCustomMethodAsyncSync() throws Exception {
    String address = "http://localhost:" + PORT + "/bookstore/retrieve";
    WebClient wc = WebClient.create(address);
    // Setting this property is not needed given that
    // we have the async conduit loaded in the test module:
    // WebClient.getConfig(wc).getRequestContext().put("use.async.http.conduit", true);
    wc.type("application/xml").accept("application/xml");
    Book book = wc.invoke("RETRIEVE", new Book("Retrieve", 123L), Book.class);
    assertEquals("Retrieve", book.getName());
    wc.close();
}
 
Example 17
Source File: RestUtil.java    From peer-os with Apache License 2.0 5 votes vote down vote up
public static void close( WebClient webClient )
{
    if ( webClient != null )
    {
        try
        {
            webClient.close();
        }
        catch ( Exception ignore )
        {
            //ignore
        }
    }
}
 
Example 18
Source File: AbstractSwagger2ServiceDescriptionTest.java    From cxf with Apache License 2.0 4 votes vote down vote up
protected static void doTestApiListingIsProperlyReturnedJSON(final WebClient client,
                                                      XForwarded useXForwarded) throws Exception {
    if (useXForwarded == XForwarded.ONE_HOST) {
        client.header("USE_XFORWARDED", true);
    } else if (useXForwarded == XForwarded.MANY_HOSTS) {
        client.header("USE_XFORWARDED_MANY_HOSTS", true);
    }

    try {
        String swaggerJson = client.get(String.class);
        UserApplication ap = SwaggerParseUtils.getUserApplicationFromJson(swaggerJson);
        assertNotNull(ap);
        assertEquals(useXForwarded.isSet() ? "/reverse" : "/", ap.getBasePath());

        List<UserResource> urs = ap.getResources();
        assertNotNull(urs);
        assertEquals(1, urs.size());
        UserResource r = urs.get(0);
        String basePath = "";
        if (!"/".equals(r.getPath())) {
            basePath = r.getPath();
        }
        Map<String, UserOperation> map = r.getOperationsAsMap();
        assertEquals(3, map.size());
        UserOperation getBooksOp = map.get("getBooks");
        assertEquals(HttpMethod.GET, getBooksOp.getVerb());
        assertEquals("/bookstore", basePath + getBooksOp.getPath());
        assertEquals(MediaType.APPLICATION_JSON, getBooksOp.getProduces());
        List<Parameter> getBooksOpParams = getBooksOp.getParameters();
        assertEquals(1, getBooksOpParams.size());
        assertEquals(ParameterType.QUERY, getBooksOpParams.get(0).getType());
        UserOperation getBookOp = map.get("getBook");
        assertEquals(HttpMethod.GET, getBookOp.getVerb());
        assertEquals("/bookstore/{id}", basePath + getBookOp.getPath());
        assertEquals(MediaType.APPLICATION_JSON, getBookOp.getProduces());
        List<Parameter> getBookOpParams = getBookOp.getParameters();
        assertEquals(1, getBookOpParams.size());
        assertEquals(ParameterType.PATH, getBookOpParams.get(0).getType());
        UserOperation deleteOp = map.get("delete");
        assertEquals(HttpMethod.DELETE, deleteOp.getVerb());
        assertEquals("/bookstore/{id}", basePath + deleteOp.getPath());
        List<Parameter> delOpParams = deleteOp.getParameters();
        assertEquals(1, delOpParams.size());
        assertEquals(ParameterType.PATH, delOpParams.get(0).getType());

        assertThat(swaggerJson, CoreMatchers.containsString(CONTACT));
        assertThat(swaggerJson, CoreMatchers.containsString(TITLE));
        assertThat(swaggerJson, CoreMatchers.containsString(DESCRIPTION));
        assertThat(swaggerJson, CoreMatchers.containsString(LICENSE));
        assertThat(swaggerJson, CoreMatchers.containsString(LICENSE_URL));
        assertThat(swaggerJson, CoreMatchers.containsString(SECURITY_DEFINITION_NAME));
    } finally {
        client.close();
    }
}
 
Example 19
Source File: AbstractOpenApiServiceDescriptionTest.java    From cxf with Apache License 2.0 4 votes vote down vote up
protected void doTestApiListingIsProperlyReturnedJSON(final WebClient client,
        boolean useXForwarded, String basePath) throws Exception {
    if (useXForwarded) {
        client.header("USE_XFORWARDED", true);
    }
    try {
        String swaggerJson = client.get(String.class);
        UserApplication ap = OpenApiParseUtils.getUserApplicationFromJson(swaggerJson);
        assertNotNull(ap);

        if (basePath == null) {
            assertEquals(useXForwarded ? "/reverse" : "/", ap.getBasePath());
        } else {
            assertEquals(basePath, ap.getBasePath());
        }

        List<UserResource> urs = ap.getResources();
        assertNotNull(urs);
        assertEquals(1, urs.size());
        UserResource r = urs.get(0);

        Map<String, UserOperation> map = r.getOperationsAsMap();
        assertEquals(3, map.size());
        UserOperation getBooksOp = map.get("getBooks");
        assertEquals(HttpMethod.GET, getBooksOp.getVerb());
        assertEquals(getApplicationPath() + "/bookstore", getBooksOp.getPath());
        assertEquals(MediaType.APPLICATION_JSON, getBooksOp.getProduces());
        List<Parameter> getBooksOpParams = getBooksOp.getParameters();
        assertEquals(1, getBooksOpParams.size());
        assertEquals(ParameterType.QUERY, getBooksOpParams.get(0).getType());
        UserOperation getBookOp = map.get("getBook");
        assertEquals(HttpMethod.GET, getBookOp.getVerb());
        assertEquals(getApplicationPath() + "/bookstore/{id}", getBookOp.getPath());
        assertEquals(MediaType.APPLICATION_JSON, getBookOp.getProduces());
        List<Parameter> getBookOpParams = getBookOp.getParameters();
        assertEquals(1, getBookOpParams.size());
        assertEquals(ParameterType.PATH, getBookOpParams.get(0).getType());
        UserOperation deleteOp = map.get("delete");
        assertEquals(HttpMethod.DELETE, deleteOp.getVerb());
        assertEquals(getApplicationPath() + "/bookstore/{id}", deleteOp.getPath());
        List<Parameter> delOpParams = deleteOp.getParameters();
        assertEquals(1, delOpParams.size());
        assertEquals(ParameterType.PATH, delOpParams.get(0).getType());

        assertThat(swaggerJson, CoreMatchers.containsString(getContract()));
        assertThat(swaggerJson, CoreMatchers.containsString(getTitle()));
        assertThat(swaggerJson, CoreMatchers.containsString(getDescription()));
        assertThat(swaggerJson, CoreMatchers.containsString(getLicense()));
        assertThat(swaggerJson, CoreMatchers.containsString(getLicenseUrl()));
        assertThat(swaggerJson, CoreMatchers.containsString(getSecurityDefinitionName()));
        assertThat(swaggerJson, CoreMatchers.containsString(getTags()));
    } finally {
        client.close();
    }
}
 
Example 20
Source File: CxfClientIT.java    From pinpoint with Apache License 2.0 2 votes vote down vote up
@Test
    public void test() throws Exception {

        String address = webServer.getCallHttpUrl();

        String json = "{\"id\" : 12345, \"name\" : \"victor\"}";

        WebClient client = WebClient.create(address, true);

        ClientConfiguration configuration = WebClient.getConfig(client);

        // add logging interceptor
        configuration.getInInterceptors().add(new LoggingInInterceptor());
        configuration.getOutInterceptors().add(new LoggingOutInterceptor());

        client.path("/test1").accept("application/json").type("application/json; charset=UTF-8").post(json).close();

        PluginTestVerifier verifier = PluginTestVerifierHolder.getInstance();

        verifier.printCache();

        verifier.ignoreServiceType("JDK_HTTPURLCONNECTOR");

        verifier.verifyTrace(event("CXF_MESSAGE_SENDER", MessageSenderInterceptor.class.getDeclaredMethod("handleMessage", Message.class)));

        verifier.verifyTrace(event("CXF_LOGGING_OUT", LoggingOutInterceptor.class.getDeclaredMethod("formatLoggingMessage", LoggingMessage.class),
                annotation("cxf.address", address + "/test1"),
                annotation("cxf.http.method", "POST"),
                annotation("cxf.content.type", "application/json; charset=UTF-8"),
                annotation("cxf.headers", "{Accept=[application/json], Content-Type=[application/json; charset=UTF-8]}"),
                annotation("cxf.payload", "{\"id\" : 12345, \"name\" : \"victor\"}")
        ));

//        verifier.verifyTrace(event("CXF_LOGGING_IN", LoggingInInterceptor.class.getDeclaredMethod("formatLoggingMessage", LoggingMessage.class),
//                annotation("cxf.response.code", "200"),
//                annotation("cxf.encoding", "ISO-8859-1"),
//                annotation("cxf.content.type", "text/html"),
//                annotation("cxf.headers", "{connection=[keep-alive], Content-Length=[2], content-type=[text/html], Date=[" + new Date() + "]}"),
//                annotation("cxf.payload", "{}")
//        ));

        verifier.verifyTraceCount(1);

        client.close();

    }