пʼятниця, 22 січня 2016 р.

How to create APACHE CXF REST service Calculator


  1. Create a Java Project
  2. Configure to Maven project
  3. in pom file add JAX RS and  APACHE CXF dependencies
  4. Create a Java class ‘CalcREST’ and type the following code. 

1. pom
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>RestCalcProject</groupId>
  <artifactId>RestCalcProject</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <properties>
  <cxf.version>2.2.3</cxf.version>
</properties>
<repositories>
 <repository>
      <id>apache-snapshots</id>
      <name>Apache SNAPSHOT Repository</name>
      <url>http://repository.apache.org/snapshots/</url>
      <snapshots>
         <enabled>true</enabled>
      </snapshots>
   </repository>
   </repositories>
<dependencies>
 <dependency>
<groupId>javax.ws.rs</groupId>
<artifactId>javax.ws.rs-api</artifactId>
<version>2.0.1</version>
</dependency>
 <dependency>
   <groupId>org.apache.cxf</groupId>
   <artifactId>cxf-api</artifactId>
   <version>${cxf.version}</version>
   <type>jar</type>
</dependency>

   <dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-bundle-jaxrs</artifactId>
<version>2.2.3</version>
  </dependency>
<dependency>
       <groupId>org.apache.cxf</groupId>
       <artifactId>cxf-rt-frontend-jaxws</artifactId>
       <version>${cxf.version}</version>
</dependency>
   <dependency>
       <groupId>org.apache.cxf</groupId>
       <artifactId>cxf-rt-transports-http</artifactId>
       <version>${cxf.version}</version>
   </dependency>
       <!-- Jetty is needed if you're are not using the CXFServlet -->
   <dependency>
        <groupId>org.apache.cxf</groupId>
        <artifactId>cxf-rt-transports-http-jetty</artifactId>
        <version>${cxf.version}</version>
    </dependency>
</dependencies>
  <build>
    <sourceDirectory>src</sourceDirectory>
    <plugins>
      <plugin>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.3</version>
        <configuration>
          <source>1.8</source>
          <target>1.8</target>
        </configuration>
      </plugin>
    </plugins>
  </build>
</project>

  1. @Path("/calc")
    public class CalcREST {
        @GET
        @Path("/add/{a}/{b}")
        @Produces(MediaType.TEXT_PLAIN)
        public String addPlainText(@PathParam("a") double a, @PathParam("b") double b) {
            return (a + b) + "";
        }
         
    @GET
        @Path("/sub/{a}/{b}")
        @Produces(MediaType.TEXT_PLAIN)
        public String subPlainText(@PathParam("a") double a, @PathParam("b") double b) {
            return (a - b) + "";
        }
        @GET
        @Path("/add/{a}/{b}")
        @Produces(MediaType.TEXT_XML)
        public String add(@PathParam("a") double a, @PathParam("b") double b) {
            return "<?xml version=\"1.0\"?>" + "<result>" +  (a + b) + "</result>";
        }
         
        @GET
        @Path("/sub/{a}/{b}")
        @Produces(MediaType.TEXT_XML)
        public String sub(@PathParam("a") double a, @PathParam("b") double b) {
            return "<?xml version=\"1.0\"?>" + "<result>" +  (a - b) + "</result>";
        }
    }
5. Now we need to start a HTTP server to publish our web service and accept requests.
6. Create a class “CalcRESTStartUp” and type the following code.
public class CalcRESTStartUp {
    public static void main(String[] args) {
         JAXRSServerFactoryBean sf = new JAXRSServerFactoryBean();
            sf.setResourceClasses(CalcREST.class);
            sf.setResourceProvider(CalcREST.class,
                new SingletonResourceProvider(new CalcREST()));
            sf.setAddress("http://localhost:9999/calcrest/");
            Server server = sf.create();
             
            // destroy the server
            // uncomment when you want to close/destroy it
            // server.destroy();
             
    }
7. Make sure that port number 9999 is not used by any other application. If so, use any other unused port
8. Run this class “CalcRESTStartup” as Java Application.
9. Our class “CalcREST” should be identified as root resource class and should be deployed.
10. To test it, open a browser and type the following URL
http://localhost:9999/calcrest/calc?_wadl
A Web Application Description Language (WADL) should be displayed.
11. To test the service we can type the following URLs in the browser
http://localhost:9999/calcrest/calc/add/20/30/
and
http://localhost:9999/calcrest/calc/sub/20/30/
12. The output on the browser will be in XML format even though we have our service produce plain text. This is because of the accept type HTTP header sent by the browser. By default the browser sends the text/html accept type and other xhtml and xml types. 
13. create client
static final String REST_URI = "http://localhost:9999/calcrest/";
    static final String ADD_PATH = "calc/add";
    static final String SUB_PATH = "calc/sub";
    static final String MUL_PATH = "calc/mul";
    static final String DIV_PATH = "calc/div";
     
    public static void main(String[] args) {
        int a = 122;
        int b = 34;
        String s = "";
         
        WebClient plainAddClient = WebClient.create(REST_URI);
        plainAddClient.path(ADD_PATH).path(a + "/" + b).accept("text/plain");
        s = plainAddClient.get(String.class);
        System.out.println(s);
         
        WebClient xmlAddClient = WebClient.create(REST_URI);
        xmlAddClient.path(ADD_PATH).path(a + "/" + b).accept("text/xml");
        s = xmlAddClient.get(String.class);
        System.out.println(s);
         
        WebClient plainSubClient = WebClient.create(REST_URI);
        plainSubClient.path(SUB_PATH).path(a + "/" + b).accept("text/plain");
        s = plainSubClient.get(String.class);
        System.out.println(s);
         
        WebClient xmlSubClient = WebClient.create(REST_URI);
        xmlSubClient.path(SUB_PATH).path(a + "/" + b).accept("text/xml");
        s = xmlSubClient.get(String.class);
        System.out.println(s);

    }

Немає коментарів:

Дописати коментар