Thursday, February 21, 2013

CXF Webservice example | Step by Step | Using Maven Project (A Web Application).

CXF Overview

Apache CXF is an open source, fully featured Web services framework, its name CXF is originated from two projects (Celtix and XFire) combined work together to Apache. CXF supports JAX-WS, Binding, DataBinding and Transport implementation, the nice feature is its embeddable Web service component.

We look though a step-by-step configuration for maven, tomcate with CXF to start the first web service project.

We will basically go through the following steps:
1) Download and install the required tools.
2) How do I configure Eclipse to develop and run web services with maven?
3) Develop a simple Hello World Web Service?
4) How to deploy your Web Service?
5) How to test your Web Service?


Download and install the required tools.


1) JDK ( Click Here) Download the latest version of JDK.
2) Apache Tomcat ( Click Here ) Download Binary Distributions ZIP.
3) Maven ( Click Here ) Download LINK (Binary zip).
4) Apache CXF ( Click Here ) Download FILE (Binary distribution) ZIP.
5) Eclipse IDE for Java EE version ( Click Here )
6) Eclipse Maven Plugin.
  • Start Eclipse create new Workspace.
  • Goto HELP >> Install New Software
  • Add URL ( http://m2eclipse.sonatype.org/sites/m2e ) and check "Maven Integration for Eclipse"
  • Click on Finish.

How do I configure Eclipse to develop and run web services with maven


1) Configure Default JDK
Open Eclipse and follow below instructions

  • Goto Window >> Preference
  • Select Java >> Installed JREs
  • Click on "Add", select "Standard VM".
  • Click on "Directory" and select JDK Home path where you have installed JDK.
  • Finish >> Now select the JDK we have added recently and click on OK.


2) Configure Tomcat

  • Goto Window >> Preference
  • Select Servers >> Runtime Environments
  • Click on "Add", select "Tomcate version" you have downloaded >> Next.
  • Click on Brows and provede the home directory of Tomcate.
  • Select JDK which we recently setup in above steps.
  • Click on Finish >> OK.


3) Configure Maven Local Repository

  • Goto Window >> Preference
  • Select Maven >> User Settings
  • click on "Brows" and select "settings.xml" from conf directory of maven ( e.g. D:\apache-maven-3.0.4\conf\settings.xml).
  • Once you provide the "settings.xml" you can see the Local Repository is read only, to change the location click on "open file" link provided beside the User Settings label.
  • Now go to "settings.xml" and Un-comment the Tag localRepository and provide your own local repository, where you want all JARs will be downloaded. ( e.g. D:\MavenRepository)
  • Verify the same path in "User Settings" and click on "Update Settings". It will downlod some Jars in Local Repository.


4) Configure CXF

  • Goto Window >> Preference
  • Select Web Services >> CXF 2.x Preferences (This option will be available in Eclipse 3.6 or above)
  • Click on "Add", we have downloaded CXF so we need to "Brows" the home directory of CXF. click on OK >> Finish.
  • Select the default CXF and click on OK.


Finally I also need to configure Tomcate to use the CXF Runtime. By default tomcate uses the Axis so i need to change it to CXF.

  • Goto Window >> Preference
  • Select Web Services >> Server and Runtime
  • Change the "Web service runtime" to Apache CXF 2.x.
  • Click OK to finalize the setup.


Develop a simple Hello World Web Service with Maven Project


Lets begin, First we will create a new Maven project.


  • Goto File >> New >> Other >> Maven >> Maven Project >> Click Next.

  • In "Select project name and location" wizard, hit "Next" to continue with default values, make sure that "Create a simple project (skip archetype selection)" option is UNCHECKED.

  • In "Select an Archetype" wizard, keep default selection "All Catalogs" at the "Catalog" drop down list, After the archetypes selection area is refreshed, select the "Artifact Id" as "maven-archetype-webapp" archetype and hit Next.

  • In the "Enter a group id for the artifact" wizard, you can define the name and main package of your project. We will set the "Group Id" as "com.b4interview.ws.provider" and the "Artifact Id" as "WSProvider".

  • Hit "Finish" to exit the wizard and to create your project.


Maven will create below folder structure.

1) /src/main/java : contains source files for the application.
2) /src/test/java : contains all source files for unit tests.
3) /src/main/webapp : contains essential files for creating a valid web application. (WEB-INF/web.xml)
4) /target : contains the compiled and packaged deliverable
5) The "pom.xml" is the project object model (POM) file, that contains all project related configuration.


NOTE : In above case a new maven web project is created, but still we will not be able to deploy the same on tomcat.
There is a bit confusion here to use the same project as Eclipse web project we must add WTP facet (follow the below instruction).

  • Right click on maven project >> Build Path >> Configure Build Path...
  • Select "Project Facets" >> Convert to faceted form...
      • OR
  • Right click on maven project >> Configure >> Convert to faceted form...
  • Select "Dynamic Web Module", by selecting the same you will be able to see the link "Further configuration available...".

  • Now click on "Further configuration available..." and change the location of "Content directory" ( WebContent ) as per the maven structure.

  • Then check "CXF 2.x Web Services" in Project Facets Dialog.
  • Click OK, project structure will be as below. Now we will be able to run project as "Run on Server".



Done! You're ready for the code. Let's code for a web service provider example.

1) First we will create some base by creating Model and Exception class.

Entity.java
package com.b4interview.ws.model;

public class Entity {
private String id;
private String desc;

// getter / setter Methods.
}

GenericException.java

package com.b4interview.ws.exception;

import javax.xml.ws.WebFault;

@WebFault(name="genericException") //Indicates a generic exception that the operation/web service method can throw.
public class GenericException extends Exception {
private static final long serialVersionUID = 1L;

private GenericException(){}
public GenericException(String message){
super(message);
}
public GenericException(String message, Throwable cause){
super(message, cause);
}
}
2) Write your Service Endpoint Interface (SEI), (a java interface) that will be exposed as a webservice.

EntityService.java

package com.b4interview.ws.service;

import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebService;
import com.b4interview.ws.exception.GenericException;
import com.b4interview.ws.model.Entity;

@WebService //Indicates its a webservice.
public interface EntityService {

@WebMethod(operationName="getEntityData") //Indicates a webservice method.
public Entity getEntityData(@WebParam(name="id")String id) throws GenericException; //Indicates a parameter used in the operations, argument to be displayed on the WSDL.
}

3) Create a Service Implementation as a webservice.

EntityServiceImpl.java

package com.b4interview.ws.service.impl;

import javax.jws.WebService;
import com.b4interview.ws.exception.GenericException;
import com.b4interview.ws.model.Entity;
import com.b4interview.ws.service.EntityService;

@WebService(endpointInterface="com.b4interview.ws.service.EntityService", serviceName="entityService")
public class EntityServiceImpl implements EntityService {

public Entity getEntityData(String id) throws GenericException {
Entity entity = new Entity();
entity.setId("123");
entity.setDesc("Hello World, Web Services");
return entity;
}
}

4) create a beans.xml, Configuration file for a webservices.
We will create it in a new package ( com.b4interview.ws.conf ).

beans.xml


5) Finally Its time to configure web.xml for CXF.

web.xml

6) Start the server, and access http://localhost:8080/WSProvider/services
You should be able to see the list of services. by clicking on it, WSDL will be displayed.


43 comments:

  1. Hi,
    Thank you for this tutorial, how did you generate beans.xml from eclipse ?
    Thanks

    ReplyDelete
    Replies
    1. It not being auto generated, we will have to create this xml manually.
      please post if you need more information.

      Delete
    2. This comment has been removed by a blog administrator.

      Delete
  2. Its a nice tutorial but im getting many errors out of it
    ::java compiler does not match version of installed java facet

    ReplyDelete
    Replies
    1. Thanks,

      You should change the jdk version for maven project and choose the latest one, or change the dynamic web module 2.5 and not 3.0

      Delete
    2. This step is quite tricky in Eclipse, possibly due to a bug. It seems to allow only one change at a time. At least, this is what worked for me. SO:

      1. Start with setting JDK. Close the dialog
      2. Open the dialog again. Set the Dynamic Web module. Pick the highest level it will allow. Close the dialog
      3. Open the dialog again. Finally select CXF version. Close the dialog

      Adding this since it took me a while to figure out.

      Delete
  3. Hello,
    Thanks much for the tutorial, it was helpful. However, I got some problem there, when I type the URL http://localhost:8080/WSProvider/services/entityService?wsdl it gives me HTTP Status 404 - /WSProvider/services/entityService .. but when I type http://localhost:8080/WSProvider/ it works fine, it gives the Hello World ! message, any idea on how I can fix it?
    Thanks

    ReplyDelete
    Replies
    1. Try accessing by your CFXServlet url-pattern param

      Delete
  4. Try accessing by your CFXServlet url-pattern param.

    ReplyDelete
  5. Hi, can you place pom.xml with all the spring dependencies for this example?

    ReplyDelete
  6. Hey, would you mind if I share your blog with my twitter group? There’s a lot of folks that I think would enjoy your content. Please let me know. Thank you.

    python training in chennai
    python course in chennai
    python training in bangalore

    ReplyDelete
  7. href="https://istanbulolala.biz/">https://istanbulolala.biz/
    NB3C27

    ReplyDelete