lunes, abril 28, 2014

Configurando Eclipse con MAVEN



Creación de un WebService desde Cero con CXF y Maven

Introducción
En la presente guía construiremos un Web Service básico desde cero, utilizando Maven y un framework open source para la construcción de servicios: Apache CXF.
CXF se para sobre el estándar de Java para Web Services: JAX-WS, que, a su vez, hace uso de otros estándares, como, por ejemplo, JAXB para el proceso de Binding (la asociación entre una clase Java y su correspondiente definición en el XML de los mensajes a transmitir).
Como siempre, podemos utilizar directamente JAX-WS para nuestros servicios web (como también podríamos usar JDBC si quisiéramos acceder a una base de datos en la forma más básica, o la especificación de Servlets/JSP para crear aplicaciones web), sin embargo CXF nos facilita varias cuestiones, y está integrado con otros Frameworks, como Spring, que mencionaremos en apartados posteriores, y que aceleran procesos tediosos, como la publicación y la generación de clientes.
Para realizar la guía necesitaremos una instalación activa de Maven en nuestra máquina, emplearemos Eclipse como IDE y Apache Tomcat, como Web Server.
A su vez, se sugiere tener instalado el plugin de Maven: m2Eclipse, ya que facilitará muchas de las acciones que llevemos a cabo por medio de esta herramienta.

En esta URL recuperamos donde esta el repositorio de MAVEN
http://eclipse.org/m2e/download/






Installing Apache CXF in Eclipse

Paso 1: Descargar y descomprima la ultima version de CXF.
Paso 2: Inicie Eclipse -> abrir Window -> Preferences
Paso 3: Ubique y expanda “Web Services” del menu izquierdo -> Seleccione “CXF 2.x “Preferences”
Step 4: Click en el boton Add
Step 5: Revisar la carpeta donde se ubica CXF para asignar “CXF Home”, este asigna automaticamente la “Version” and “Type”, luego damos click en “Finish”
Step 6: Check the check-box for CXF version
Step 7: Go to other tabs and check that the tabs are not empty, if step 5 is not done then all the tabs will remain empty
Step 8: Click OK, the installation is done

Update Sites


Latest m2e release (recommended)

http://download.eclipse.org/technology/m2e/releases   

En el ECLIPSE, seleccionamos HELP, INSTALL NEW SOFTWARE, click boton ADD, colocamos un nombre pueder: MAVEN , en la URL :
http://download.eclipse.org/technology/m2e/releases 
Click en el boton Select All.
Luego click boton Next y Finish.

Esperar que se actualice y reiniciar el ECLIPSE.

Aqui tenemos otro tutorial de como realizar un servicio web con CXF.
Tutorial para configurar ECLIPSE Y CXF, practica crear un servicio web



 Servicio web con CXF utilizando Maven.

Que es CXF:

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.



















No hay comentarios: