Learn in Java
 


   

Restful client using CXF

 
In our JAX-RS webservice using CXF tutorial, we have created a restful webservice that contains two methods. One method accepts text type input while the second one accepts a JsonBean type.

Remember, in our test case, HelloAngryWorldTest.java, by default, when the file was created using maven, there were two methods that tests both text and JsonBean return types. It is modified it a bit to have an extra method as below:

1. HelloAngryWorldTest.java :

package com.learninjava;

import static org.junit.Assert.assertEquals;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Invocation;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.Response;

import org.apache.cxf.helpers.IOUtils;
import org.apache.cxf.jaxrs.client.WebClient;
import org.apache.cxf.jaxrs.client.spec.InvocationBuilderImpl;
import org.codehaus.jackson.JsonParser;
import org.codehaus.jackson.map.MappingJsonFactory;
import org.junit.BeforeClass;
import org.junit.Test;

/**
 * @author learninjava.com
 * @see www.learninjava.com
 */
public class HelloAngryWorldTest {
    private static String endpointUrl;

    @BeforeClass
    public static void beforeClass() {
        endpointUrl = System.getProperty("service.url");
    }

    @Test
    public void testPing() throws Exception {
        
        WebClient client = WebClient.create(endpointUrl + "/helloAngryWorld/echo/Tweet");
        Response r = client.accept("text/plain").get();
        
        assertEquals(Response.Status.OK.getStatusCode(), r.getStatus());
        String value = IOUtils.toString((InputStream)r.getEntity());
        System.out.println("Response from web service is : " + value);
        assertEquals("Tweet", value);
    }

    @Test
    public void testPingUsingPureJaxRS() throws Exception {
    	
        Client client = ClientBuilder.newClient();
        WebTarget target = client.target(endpointUrl + "/helloAngryWorld/echo/Tweet");
        Invocation.Builder builder = target.request("text/plain"); 
        Response r = builder.get();
    	
        assertEquals(Response.Status.OK.getStatusCode(), r.getStatus());
        String value = IOUtils.toString((InputStream)r.getEntity());
        System.out.println("Response from web service is : " + value);
        assertEquals("Tweet", value);
    }

    @Test
    public void testJsonRoundtrip() throws Exception {
        
        List<Object> providers = new ArrayList<Object>();
        providers.add(new org.codehaus.jackson.jaxrs.JacksonJsonProvider());
        
        JsonBean inputBean = new JsonBean();
        inputBean.setVal1("Birds");
        
        WebClient client = WebClient.create(endpointUrl + "/helloAngryWorld/jsonBean", providers);
        Response r = client.accept("application/json")
            .type("application/json")
            .post(inputBean);
        
        assertEquals(Response.Status.OK.getStatusCode(), r.getStatus());
        
        MappingJsonFactory factory = new MappingJsonFactory();
        JsonParser parser = factory.createJsonParser((InputStream)r.getEntity());
        JsonBean output = parser.readValueAs(JsonBean.class);
        System.out.println("Response from web service is : " + output.getVal2()); 
        assertEquals("Birds", output.getVal2());
    }
}

In Apache CXF, there is a helper class called org.apache.cxf.jaxrs.client.WebClient. This helper class is used to create the client. This class reduces the code to create a response to just two lines (see testPing() method). Without this helper class, we would need to create a lot of objects.

An example restful client with(see, testPing()) and without(see, testPingUsingPureJaxRS()) using the helper class are shown in the above example. The third method, testJsonRoundtrip() demonstrates usage of jsonBean return type.

testPingUsingPureJaxRS() method uses pure JAX-RS classes for creating the response. Using pure JAX-RS classes the response creation will be as follows :

Client -> WebTarget -> Invocation.Builder -> Response

Using Apache CXF helper class the reponse creation becomes as simple as below :

WebClient -> Response

Testing the webservice:

There are number of ways you can test the Restful webservice. Before running any of the below, make sure the tomcat server is started and the webservice is running using,

mvn clean package -DskipTests=true tomcat7:run or
mvn clean package -DskipTests=true jetty:run

1. Using maven command :

i. Specify the service.url at command line :

mvn -Dservice.url=http://localhost:<port-number>/jaxrs-service test

This command uses a command line argument to specify the service.url. The service.url is used in the test case.

ii. Specify the service.url in pom.xml

    <service.url>http://localhost:${port.number}/jaxrs-service</service.url>
    
    <plugin>
      <groupId>org.apache.maven.plugins</groupId>
      <artifactId>maven-surefire-plugin</artifactId>
      <version>2.10</version>
      <configuration>
        <argLine>-Dservice.url=${service.url}</argLine>
      </configuration>
    </plugin>
    

Add the above configuration and use the below command to test the webservice,

mvn test

iii. Hard-code the service.url in HelloWorldTest.java and use the below command to run the tests.

mvn test

Output:
-------------------------------------------------------
 T E S T S
-------------------------------------------------------
Running com.learninjava.HelloAngryWorldTest
Response from web service is : Birds
Response from web service is : Tweet
Response from web service is : Tweet
Tests run: 3, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 41.107 sec

Results :

Tests run: 3, Failures: 0, Errors: 0, Skipped: 0

 

2. Using Poster plugin :

Poster is a plugin for firefox browser. This is a very useful and handy tool to test your restful webservices quickly.

i. To test the ping method of HelloAngryWorld, enter the following in Poster UI :

URL          :   http://localhost:<port-number>/jaxrs-service/helloAngryWorld/echo/tweet
Content Type :   application/text

and click on GET button as ping is a GET request type. The response is displayed in the Response window.



ii. To test the modifyJson method of HelloAngryWorld, enter the following in Poster UI :

URL                         :  http://localhost:<port-number>/jaxrs-service/helloAngryWorld/jsonBean
Content Type                :  application/json
Payload(Text Box at bottom) :  { "val1": "Birds", "val2": "Eggs" }

and click on POST button as modifyJson is a POST request type. The response is displayed in the Response window.

 
   

Related Articles

Restful WebService using CXF
SOAP WebService using CXF
SOAP Client using CXF
Restful WebService using Jersey
Restful Client using Jersey
 
   

Recommended Articles

User and Daemon Threads
Thread States
Java 8 Stream
Java 8 Functional Interfaces
Java 8 Lambda Expressions
Top 10 Free Tutorials




LIKE/SHARE
 
 
 
Download Source:

Comments:


 

Top Picks

1. Top 5 websites offering free e-books

2. Top 10 websites for free Java Articles and Tutorials

3. Top 5 websites for Java Certifications

4. Top 5 Softwares for Java developers




   
   
   
 
 
© Copyright 2017. All rights reserved. All trademarks and logos belongs to their owners.         Website Counter