Pages

mercredi 20 janvier 2016

Code Review Benefits & Rules

Aller directement à la fin des métadonnées
(It was only supposed to take one hour)
Code review is systematic examination (often known as peer review) of computer source code. It is intended to find and fix mistakes overlooked in the initial development phase, improving both the overall quality of software and the developers’ skills. It's a thorough technical and logical line-by-line review of a code module. During a peer review, code is inspected to identify possible improvements and ensure that business requirements are met. If necessary, a meeting is held to discuss any issues that come out of the review process. Although some programmers complain that the reviews take too much time, the drawbacks are usually outweighed by the benefits, such as fewer bugs, less rework, more pride, and better team communication and cohesiveness. This guide will outline some of the positives of the process and how the actors should behave. This guide will give a suggestion of rules that can be used for code reviews.

Why code Review?

  1. Team cohesiveness : Code review can be a real team building exercise, It increase and improves communication between team members. Though Code review must be given only keeping positives in mind, instead of criticizing other developer. Working together helps draw team members closer. It also provides a brief respite from the isolation that coding often brings 
  2. Code review also increase knowledge sharing between team members and all the team remains in same page and ready to backup each other. This can be a huge plus for Manager, who needs to manage leaves and resources. Uniformity in understanding will help interchangeability of team members in case of non-availability of any one of them.
  3. Code review promotes a better code quality, reduce testing time and less number of bugs. Code review helps to spot and fix defects early  & often in the process. 
  4. Helps to maintain a level of consistency in design and implementation.
  5. Code review would save half the cost of fixing the bugs. Plus they would have found x additional bugs.
  6. Builds confidence of stakeholders about technical quality of the execution.
  7. A different perspective. “Another set of eyes” adds objectivity.

Code reviews are often misused and painful for everyone, but they don't have to be. Some simple steps can convert torture into teaching and improve the long-term outlook for code quality in your organization. So let's start by defining the way a developer and reviewer should behave before setting the review rules.

Tips for the Developer:

  1. The primary reviewer is the author i.e. YOU.
  2. Create a checklist for yourself of the things that the code reviews tend to focus on. Run through your code with the checklist and fix whatever you find. Not only will you reduce the number of things that the team finds, you’ll reduce the time to complete the code review meeting—and everyone will be happy to spend less time in the review.
  3. You are not your code. Remember that the entire point of a review is to find problems, and problems will be found. Don’t take it personally when one is uncovered.
  4. Understand and accept that you will make mistakes. The point is to find them early, before they make it into production. Fortunately, except for the few of us developing rocket guidance software at JPL, mistakes are rarely fatal in our industry, so we can, and should, learn, laugh, and move on.
  5. No matter how much “karate” you know, someone else will always know more. Such an individual can teach you some new moves if you ask. Seek and accept input from others, especially when you think it’s not needed.
  6. Don’t rewrite code without consultation. There’s a fine line between “fixing code” and “rewriting code.” Know the difference, and pursue stylistic changes within the framework of a code review, not as a lone enforcer.
  7. The only constant in the world is change. Be open to it and accept it with a smile. Look at each change to your requirements, platform, or tool as a new challenge, not as some serious inconvenience to be fought.
  8. Fight for what you believe, but gracefully accept defeat. Understand that sometimes your ideas will be overruled. Even if you do turn out to be right, don’t take revenge or say, “I told you so” more than a few times at most, and don’t make your dearly departed idea a martyr or rallying cry.
  9. Don’t be “the guy in the room.” Don’t be the guy coding in the dark office emerging only to buy cola. The guy in the room is out of touch, out of sight, and out of control and has no place in an open, collaborative environment.
  10. Please note that Review meetings are NOT problem solving meetings.
  11. Help to maintain the coding standards. Offer to add to the coding standards for things discussed that aren’t in the coding standards. One of the challenges that a developer has in an organization with combative code review practices is that they frequently don’t know where the next problem will come from. If you document each issue into the coding standards, you can check for it with your checklist the next time you come up for code reviews. It also will help cement the concept into your mind so that you’re less likely to miss opportunities to use the feedback.

 Tips for the Reviewer

  1. Critique code instead of people – be kind to the coder, not to the code. As much as possible, make all of your comments positive and oriented to improving the code. Relate comments to local standards, program specs, increased performance, etc.
  2. Treat people who know less than you with respect, deference, and patience. Nontechnical people who deal with developers on a regular basis almost universally hold the opinion that we are prima donnas at best and crybabies at worst. Don’t reinforce this stereotype with anger and impatience.
  3. The only true authority stems from knowledge, not from position. Knowledge engenders authority, and authority engenders respect – so if you want respect in an egoless environment, cultivate knowledge.
  4. Please note that Review meetings are NOT problem solving meetings.
  5. Ask questions rather than make statements. A statement is accusatory. “You didn’t follow the standard here” is an attack—whether intentional or not. The question, “What was the reasoning behind the approached you used?” is seeking more information. Obviously, that question can’t be said with a sarcastic or condescending tone; but, done correctly, it can often open the developer up to stating their thinking and then asking if there was a better way.
  6. Avoid the “Why” questions. Although extremely difficult at times, avoiding the”Why” questions can substantially improve the mood. Just as a statement is accusatory—so is a why question. Most “Why” questions can be reworded to a question that doesn’t include the word “Why” and the results can be dramatic. For example, “Why didn’t you follow the standards here…” versus “What was the reasoning behind the deviation from the standards here…”
  7. Remember to praise. The purposes of code reviews are not focused at telling developers how they can improve, and not necessarily that they did a good job. Human nature is such that we want and need to be acknowledged for our successes, not just shown our faults. Because development is necessarily a creative work that developers pour their soul into, it often can be close to their hearts. This makes the need for praise even more critical.
  8. Make sure you have good coding standards to reference. Code reviews find their foundation in the coding standards of the organization. Coding standards are supposed to be the shared agreement that the developers have with one another to produce quality, maintainable code. If you’re discussing an item that isn’t in your coding standards, you have some work to do to get the item in the coding standards. You should regularly ask yourself whether the item being discussed is in your coding standards.
  9. Remember that there is often more than one way to approach a solution. Although the developer might have coded something differently from how you would have, it isn’t necessarily wrong. The goal is quality, maintainable code. If it meets those goals and follows the coding standards, that’s all you can ask for.
  10. You shouldn’t rush through a code review - but also, you need to do it promptly. Your coworkers are waiting for you.
  11. Review fewer than 200-400 lines of code at a time.
  12. The best reviews include thinking questions. Questions such as "Would it be better to implement a provider pattern here?" don't necessarily need a response. Make it clear to the developer that some comments are simply to provoke thinking. This allows you to identify areas where you want to make sure the developer is considering alternatives without raising them to the point of being an issue with the code. Getting developers to think about the code they are writing doesn't improve the quality of the code they've already written, but it does have a long-term positive impact on code quality.

Code review Rules (To be discussed and improved) :

The GOLDEN rules that are mandatory to be checked/enforced during code review :
  1. Verify code compiles and includes javadoc where appropriate 
  2. Verify code meets functional requirement: first and foremost does code meets all requirements which it should met, point out if anything has been left out.
  3. Verify is there any Side effect of this change
  4. Readability and maintenance:  does code is readable? Verify that whether code is configurable or not, look for any hard coding, find out what is going to be changed in near future etc.
  5. Verify Corner cases and workarounds (framework limitations) are well documented 
  6. Verify that comments are comprehensible and add something to the maintainability of the code(Comments are neither too numerous nor verbose)
  7. Intention-Revealing Names Meaningful Names (Naming of variables and methodes and classes is very important so they should be selected carefully)
  8. Functions should not take too many input parameters (1 parameter is enougth, 2 is acceptable, avoid more then 3)
  9. Verify The code complies to coding standards
  10. Verify Access modifiers (default, public, private, protected) are correct 
  11. Verify methods and classes focus on doing one thing. and are short as possible.
  12. Verify return types (Return empty arrays or collections, not nulls )
  13. Verify that hashCode is overiden when you override equals (Otherwise a violation of the general contract for Object.hashCode will occur, which can have unexpected repercussions when your class is in conjunction with all hash-based collections.)
  14. Verify that the code is using the same formatter checkstyle agreed by the team.
  15. Never write specific logic on the Facades / Controllers / DTO / Daos
  16. Respect the layers (services should not call services from other modules -> avoid module dependencies)
  17. Verify that the service layer does not return entities but only DTOs
  18. Verify transactional use cases (reasonly , propagation, isolation)
  19. Verify the use of an interface for every spring component, Refer to objects by their interfaces
  20. Promote “stateless” functionality
  21. Check the validation exists and is correct for input objects. Ask the question : does code handles bad input and exception? Throw exceptions appropriate to the abstraction. Do not use generic messages in exceptions.
  22. Reuse of existing code : Check if we are re-using existing functionality, avoid duplications , refactor if necessary
  23. Avoid excessive synchronization, Keep Synchronized Sections Small
  24. Verify Performance was considered
  25. Verify NPEs and AIOBs are handled
  26.  Promote usage of Java 8 language whenever possible
  27. Verify needless and commented code is removed  (IDE helps)
  28. Verify inexistence of unused imports and  IDE warnings  (IDE helps)
  29. Verify Unit Test/ integration tests exists for the task and verify Failure/Success (mvn test)
  30. Ensure that the unit tests are written properly. Don’t write unit tests for the sake of writing one. Describe the scenario you are testing in a comment if it's not obvious
  31. Check how the test verifies the existence of the bug (run on existing code
  32. Examine edge cases are covered by tests

References:

  1. Clean Code Book
  2. http://blog.codinghorror.com/the-ten-commandments-of-egoless-programming/
  3. http://www.developer.com/tech/article.php/3579756/Effective-Code-Reviews-Without-the-Pain.htm

mardi 16 avril 2013

WS Tutorial Part II JAX-WS webservice client




Before you start
About this tutorial

Objectives

In this section, you learn how to create web service clients from WSDL. JAX-WS comes with a tool called wsimport that's used to generate JAX-WS portable artifacts from WSDL. The portable artifacts typically generated include the following:


·         SEI
·         Service (the service implementation class you need to implement)
·         JAXB-generated classes from schema types
·         Exception class mapped from wsdl:fault (if any)

Clients use the artifacts generated to invoke the web service. The web service clients don't need to deal with any SOAP format, like creating or parsing SOAP messages. Rather, this is handled by the JAX-WS run time, which uses the generated artifact code (the JAXB-generated class). The web service client in turn deals with the Java object (the JAXB-generated class), which eases the development of web service clients and invoking operations on the web service.
  • We will build it with Maven
  • We will not copy jars to the Tomcat. All dependencies will be managed by Maven
Plan :
   1- Web service maven project
   2- Web services artifacts for client generation with wsimport
     3- A factory, a manager and a main class for test

Prerequisites
To complete this tutorial successfully, you should have a basic understanding of web services technology and have some proficiency in Java programming.

You should also have accomplished the first part of  the tutorial that you can find here : 
http://amaraaymen.blogspot.be/2012/10/creating-jax-ws-webservice-using-wsgen.html

System requirements

To run the examples in this tutorial, you need :
  • Eclipse WTP 3.4 
  • Maven 3.0 
  • JAXWS RT 2.1.3 
  • JAVA 6 
  • TOMCAT 6

1- Web service Client maven project

In command Line type to generate a java client project with maven using this commands :
1-      mvn archetype:create -DgroupId=com.aam.jaxws.client -DartifactId=PersonManagementClient
2-      mvn eclipse:eclipse => to be able to import it to eclipse


2- Generate web services artifacts for client with wsimport :

To generate artifacts we will use maven wsimport plugin, let’s update our pom.xml by adding this build fragment and execute mvn clean install command line under the PersonManagementClient folder.

 <build>
     <plugins>
       <plugin>
               <groupId>org.codehaus.mojo</groupId>
               <artifactId>jaxws-maven-plugin</artifactId>
               <version>1.10</version>
               <executions>
                      <execution>
                            <goals>
                                   <goal>wsimport</goal>
                            </goals>
                      </execution>
               </executions>
       <configuration>
       <packageName>com.aam.jaxws.client.generated</packageName>


<wsdlUrls>
  <wsdlUrl>http://localhost:8080/PersonManagementServer/PersonManagementService?wsdl       </wsdlUrl>
</wsdlUrls>
       <sourceDestDir>${basedir}/src/main/java</sourceDestDir>
       <destDir>${basedir}/src/main/java</destDir>
       <phase>generate-sources</phase>
       <encoding>UTF-8</encoding>
       <extension>true</extension>
      </configuration>
   </plugin>
</plugins>
</build>

Maven wsimport pluggin has generated the artifiacts in the specified package :



3- A factory, a manager and a main class for test:

Let’s create a factory of our webservice that gives an instance of our Service whenever it’s needed.

package com.aam.jaxws.client;

import java.net.URL;
import javax.xml.namespace.QName;
import com.aam.jaxws.client.generated.PersonManagementService;
import com.aam.jaxws.client.generated.PersonManagementService_Service;

/**
 * @author AMARA Aymen
 */

public class PersonManagementServiceFactory {

       protected URL wsdlLocation = null;

       public PersonManagementServiceFactory(URL wsdlLocation) {
              this.wsdlLocation = wsdlLocation;
       }

       public PersonManagementService getPersonManagementService() {
              try {

PersonManagementService_Service serviceImplService = new PersonManagementService_Service (wsdlLocationnew QName("http://com.aam.jaxws.server","PersonManagementService") );

return serviceImplService .getPersonManagementServicePort();
              } catch (Exception e) {
                     return null;
              }
       }
}

Let’s create a manger that will use this factory and search for a person by CIN.

package com.aam.jaxws.client;
import java.net.URL;
import org.apache.log4j.Logger;
import com.aam.jaxws.client.generated.PersonException_Exception;
import com.aam.jaxws.client.generated.PersonManagementService;
import com.aam.jaxws.client.generated.PersonOut;

public class PersonManager {

       protected Logger log = Logger.getLogger(PersonManager.class);
       protected PersonManagementService personManagementService = null;

protected PersonManager(String wsdlLocation) {
try {
PersonManagementServiceFactory service = new PersonManagementServiceFactory(
                                  new URL(wsdlLocation));
this.personManagementService = service.getPersonManagementService();
catch (Exception e) {
log.error("Unable to initialize " + PersonManager.class.getName()+ ".", e);
}
       }

public PersonOut findPerson(String CIN) {

              try {
                     return personManagementService.findPersonByCIN(CIN);
              } catch (PersonException_Exception e) {
                     e.printStackTrace();
              }
              return null;

       }
}



A main class to call the webservice TestPersonManagementClient.java :

package com.aam.jaxws.client;

import com.aam.jaxws.client.generated.PersonOut;


public class TestPersonManagementClient {
       public static void main(String[] args) {
              String CIN = "p1";
              PersonManager manager = new PersonManager("http://localhost:8080/PersonManagementServer/PersonManagementService?wsdl");
             
PersonOut person = manager.findPerson("p1");

if (person != null)
       System.out.println("Person Found = firstName :"
                                  + person.getFirstName() + " Name:" + person.getName());

              else
                     System.out.println("Person with CIN =" + CIN + "ISNOT FOUND");
       }
}


Result  :

Person Found = firstName :aam Name:aam



As you see in the client code, you don't deal with any SOAP or XML-based format for invoking web service operations; instead you deal with generated JAXB classes for input and output messages and use the service interface and service class objects, which act as stubs for web service invocation. The stubs are responsible for creating SOAP requests from JAXB annotations and converting the SOAP response back to the Java object.

You can use this links to Download source code
  DOWNLOAD CLIENT PROJECT
  DOWNLOAD SERVER PROJECT

After downloading, execute mvn clean install command in both folders and  import projects to your eclipse. You can after deploy the WebService in your favorite server and run the main client.

END. 

mardi 23 octobre 2012

WS Tutorial Part I Creating JAX-WS webservice using wsgen


Before you start
About this tutorial

Objectives
In this tutorial, you design and develop a simple application with maven that exposes its functionality as web services  in a platform-independent manner. After going through this tutorial, you can apply the concepts and knowledge to develop web services for your application using JAX-WS technology and maven.
  • We will build it with Maven
  • We will not copy jars to the Tomcat. All dependencies will be managed by Maven
Plan :
   1- Develop a web service maven project
   2- Develop a JAXWS web service with SOAP 1.2
           2.1 Develop a Person Management web service
           2.2 Generate web services artifacts with wsgen
           2.3 Update web.xml 
           2.4 Create web service deployment descriptor sun-jaxws.xml
           2.5 Deployment
           2.6 Test with SOAPUI 4.5.1 :
   3- Develop a web service Client maven project
           3.1 create maven project
           3.2 Generate web services artifacts for client with wsimport
           3.3 A factory, a manager and a main class for test

Prerequisites
To complete this tutorial successfully, you should have a basic understanding of web services technology and have some proficiency in Java programming.

System requirements

To run the examples in this tutorial, you need :
  • Eclipse WTP 3.4 
  • Maven 3.0 
  • JAXWS RT 2.1.3 
  • JAVA 6 
  • TOMCAT 6

Introduction to JAX-WS
Why JAX-WS?

Java API for XML Web Services (JAX-WS), JSR 224, is an important part of the Java EE 5 and EE 6 platforms. A follow-up to the release of Java API for XML-based RPC 1.1(JAX-RPC), JAX-WS simplifies the task of developing web services using Java technology. It addresses some of the issues in JAX-RPC 1.1 by providing support for multiple protocols such as SOAP 1.1, SOAP 1.2, XML, and by providing a facility for supporting additional protocols along with HTTP. JAX-WS uses JAXB 2.0 for data binding and supports customizations to control generated service endpoint interfaces. With its support for annotations, JAX-WS simplifies web service development and reduces the size of runtime JAR files. 

Introduction to Maven
Why Maven?
Maven's primary goal is to allow a developer to comprehend the complete state of a development effort in the shortest period of time. In order to attain this goal there are several areas of concern that Maven attempts to deal with:
  • Making the build process easy
  • Providing a uniform build system
  • Providing quality project information
  • Providing guidelines for best practices development
  • Allowing transparent migration to new features
 1- Develop a web service maven project

·         In command Line type to generate a web project with maven using this command :
mvn archetype:generate -DgroupId=com.aam.jaxws.server -DartifactId=PersonManagementServer -DarchetypeArtifactId=maven-archetype-webapp



·         Maven has generated a folder project called  PersonManagementServer



·         Add Jaxws dependency to pom.xml

<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/maven-v4_0_0.xsd">
        <modelVersion>4.0.0</modelVersion>
        <groupId>com.aam.jaxws.server</groupId>
        <artifactId>PersonManagementServer</artifactId>
        <packaging>war</packaging>
        <version>1.0</version>
        <name>PersonManagementServer Maven Webapp</name>
        <url>http://maven.apache.org</url>
        <dependencies>
               <dependency>
                       <groupId>junit</groupId>
                       <artifactId>junit</artifactId>
                       <version>3.8.1</version>
                       <scope>test</scope>
               </dependency>
               <dependency>
                       <groupId>com.sun.xml.ws</groupId>
                       <artifactId>jaxws-rt</artifactId>
                       <version>2.1.3</version>
               </dependency>
        </dependencies>
        <build>
               <finalName>PersonManagementServer</finalName>
        </build>
</project>    

·         In command line and under  /PersonManagementServer, type mvn eclipse:eclipse to be able to import the project into eclipse.
·         Import the existing maven project to your workspace.

2- Develop a JAXWS web service with SOAP 1.2

Contract-first approach versus code-first approach

A good way to get initiated into JAX-WS is to first develop a web service. You can develop a web service using one of two approaches:
  • Contract first: Start with a WSDL contract, and generate a Java class to implement the service.
  • Code first: Start with a Java class, and use annotations to generate both a WSDL file and a Java interface.
The contract-first WSDL approach requires a good understanding of WSDL and XSD (XML Schema Definition) for defining message formats. It's a good idea to start with the code-first approach if you're fairly new to web services, which is what you'll use in this tutorial to develop web services.

Code-first web services development

Using the code-first approach, you start with a Java class, or classes, that implements features you want to expose as services. The code-first approach is particularly useful when Java implementations are already available and you need to expose implementations as services.

Requirements of a JAX-WS Endpoint

 JAX-WS endpoints must follow these requirements :

·         The implementing class must be annotated with either the javax.jws.WebService or the javax.jws.WebServiceProvider annotation.
·         The implementing class may explicitly reference an SEI through the endpointInterface element of the @WebService annotation but is not required to do so. If no endpointInterface is specified in@WebService, an SEI is implicitly defined for the implementing class.
·         The business methods of the implementing class must be public and must not be declared static or final.
·         Business methods that are exposed to web service clients must be annotated with javax.jws.WebMethod.
·         Business methods that are exposed to web service clients must have JAXB-compatible parameters and return types. See the list of JAXB default data type bindings athttp://docs.oracle.com/javaee/5/tutorial/doc/bnazq.html#bnazs.
·         The implementing class must not be declared final and must not be abstract.
·         The implementing class must have a default public constructor.
·         The implementing class must not define the finalize method.
·         The implementing class may use the javax.annotation.PostConstruct or the javax.annotation.PreDestroy annotations on its methods for lifecycle event callbacks.

2.1 Develop a Person Management web service

Let's start by creating a person management web service that accepts CIN ID and generates person information as a response. The code for the service is provided Listing 1-2-3-4. This is a dummy implementation that prints the person CIN ID and number of items at the console, then returns a dummy PersonOut response.

Listing 1 : File : PersonManagementService.java
package com.aam.jaxws.server;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.jws.WebService;
import javax.xml.ws.BindingType;

@WebService(endpointInterface = "com.aam.jaxws.server.PersonManagement", serviceName = "PersonManagementService", targetNamespace = "http://com.aam.jaxws.server/")
@BindingType(value = "http://java.sun.com/xml/ns/jaxws/2003/05/soap/bindings/HTTP/")
public class PersonManagementService implements PersonManagement {

private static Map<String, PersonOut> persons = new HashMap<String, PersonOut>() {
              {put("p1", new PersonOut("p1", "aam", "aam", new Date()));}
              {put("p2", new PersonOut("p2", "bob", "bob", new Date()));}
       };

@Override
public PersonOut findPersonByCIN(String CIN) throws PersonException {
              return persons.get(CIN);
       };
}


Listing 2 : File : PersonManagement.java

package com.aam.jaxws.server;

import javax.jws.WebParam;
import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;
import javax.jws.soap.SOAPBinding.Style;
import javax.jws.soap.SOAPBinding.Use;

@WebService(name = "PersonManagementService")
@SOAPBinding(style = Style.DOCUMENT, use = Use.LITERAL)
public interface PersonManagement {

public PersonOut findPersonByCIN(@WebParam(name = "CIN") String CIN) throws PersonException;

}


Listing 3 : File : PersonOut.java

package com.aam.jaxws.server;

import java.util.Date;

public class PersonOut {

       private String CIN;
       private String name;
       private String firstName;
       private Date birthDate;
      
      //very important to JAXB
       public PersonOut() {

       }

       public PersonOut(String cIN, String name, String firstName, Date birthDate) {
              super();
              CIN = cIN;
              this.name = name;
              this.firstName = firstName;
              this.birthDate = birthDate;
       }
/* Getters & Setters */
}


Listing 4 : File : PersonException.java

package com.aam.jaxws.server;

public class PersonException extends Exception {

}


@WebService (name = "PersonManagementService")
The starting point for developing a JAX-WS web service is a Java class annotated with the javax.jws.WebService annotation. The JAX-WS annotations used are part of the Web Services Metadata for the Java Platform specification (JSR-181). As you have probably noticed, PersonManagementService is annotated with the WebService annotation, which defines the class as a web service endpoint.

@BindingType(value = "http://java.sun.com/xml/ns/jaxws/2003/05/soap/bindings/HTTP/")
Using this annotation we can specify witch binding we want use (Default SOAP 1.1) and in our case is SOAP 1.2.

@SOAPBinding(style = Style.DOCUMENT, use = Use.LITERAL)
The @SOAPBinding annotation is defined by the javax.jws.soap.SOAPBinding interface. It provides details about the SOAP binding used by the service when it is deployed. If the @SOAPBinding annotation is not specified, a service is published using a wrapped doc/literal SOAP binding.

After the web service is implemented, you need to generate any artifacts required to deploy the service, then package the web service as a deployed artifact—typically as a WAR file—and deploy the WAR file to any compliant server that supports the JAX-WS 2.0 specification. Typical artifacts generated are classes that provide conversion of Java objects to XML, and the WSDL file and XSD schema based on the service interface.

2.2 Generate web services artifacts with wsgen

To generate artifacts we will use maven wsgen plugin, let’s update our pom.xml by adding this build fragment and execute mvn clean install command line under the PersonManagementServer folder.

       <build>
              <finalName>PersonManagementServer</finalName>
       <plugins>
           <plugin>
               <groupId>org.codehaus.mojo</groupId>
               <artifactId>jaxws-maven-plugin</artifactId>
               <version>1.10</version>
               <executions>
                   <execution>
                       <phase>process-classes</phase>
                       <goals>
                           <goal>wsgen</goal>
                       </goals>
                   </execution>
               </executions>
               <configuration>
                   <sei>com.aam.jaxws.server.PersonManagementService</sei>
                   <genWsdl>true</genWsdl>
                   <keep>true</keep>
               <resourceDestDir>${basedir}/src/main/webapp/WEB-INF/wsdl</resourceDestDir>
                   <sourceDestDir>${basedir}/src/main/java</sourceDestDir>
               </configuration>
           </plugin>
       </plugins>
  </build>
  



The wsgen plugin has generated artifacts and wsdl :




2.3 Update web.xml :

Update web.xml deployment descriptor for the deployment. Defines WSServletContextListener as listener class, WSServlet as your PersonManagementService servlet.

<web-app>
       <display-name>Archetype Created Web Application</display-name>

<listener>
     <listener-class>
        com.sun.xml.ws.transport.http.servlet.WSServletContextListener
      </listener-class>
</listener>

       <servlet>
              <servlet-name>PersonManagementService</servlet-name>
              <servlet-class>
                    com.sun.xml.ws.transport.http.servlet.WSServlet
              </servlet-class>
              <load-on-startup>1</load-on-startup>
       </servlet>

       <servlet-mapping>
              <servlet-name>PersonManagementService</servlet-name>
              <url-pattern>/PersonManagementService</url-pattern>
       </servlet-mapping>

       <mime-mapping>
              <extension>txt</extension>
              <mime-type>text/xml</mime-type>
       </mime-mapping>

</web-app>

2.4 Create web service deployment descriptor sun-jaxws.xml:

    Create a web service deployment descriptor, which is also known as JAX-WS RI deployment descriptor – sun-jaxws.xml.

<?xml version="1.0" encoding="UTF-8"?>
<endpoints version="2.0"
       xmlns="http://java.sun.com/xml/ns/jax-ws/ri/runtime">

       <endpoint implementation="com.aam.jaxws.server.PersonManagementService"
              name="PersonManagementService"
              url-pattern="/PersonManagementService"     
      />

</endpoints>


2.5 Deployment :
Copy the generated WAR file to {$TOMCAT}/webapps/ folder and start the Tomcat server.

29-oct.-2012 11:13:59 org.apache.tomcat.util.digester.SetPropertiesRule begin
29-oct.-2012 11:13:59 org.apache.coyote.http11.Http11Protocol init
INFO: Initialisation de Coyote HTTP/1.1 sur http-8080
29-oct.-2012 11:13:59 org.apache.catalina.startup.Catalina load
INFO: Initialization processed in 364 ms
29-oct.-2012 11:13:59 org.apache.catalina.core.StandardService start
INFO: Démarrage du service Catalina
29-oct.-2012 11:13:59 org.apache.catalina.core.StandardEngine start
INFO: Starting Servlet Engine: Apache Tomcat/6.0.35
29-oct.-2012 11:13:59 com.sun.xml.ws.transport.http.servlet.WSServletContextListener contextInitialized
INFO: WSSERVLET12: JAX-WS context listener initializing
29-oct.-2012 11:14:00 com.sun.xml.ws.transport.http.servlet.WSServletDelegate <init>
INFO: WSSERVLET14: JAX-WS servlet initializing
29-oct.-2012 11:14:00 org.apache.coyote.http11.Http11Protocol start
INFO: Démarrage de Coyote HTTP/1.1 sur http-8080
29-oct.-2012 11:14:00 org.apache.jk.common.ChannelSocket init
INFO: JK: ajp13 listening on /0.0.0.0:8009
29-oct.-2012 11:14:00 org.apache.jk.server.JkMain start
INFO: Jk running ID=0 time=0/19  config=null
29-oct.-2012 11:14:00 org.apache.catalina.startup.Catalina start
INFO: Server startup in 1088 ms

For testing, you can access this URL http://localhost:8080/PersonManagementServer/PersonManagementService  , if you see following page, it means web services are deploy successfully.



 <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<!-- Generated by JAX-WS RI at http://jax-ws.dev.java.net. RI's version is JAX-WS RI 2.1.3-b02-. -->
<definitions targetNamespace="http://com.aam.jaxws.server/" name="PersonManagementService" xmlns="http://schemas.xmlsoap.org/wsdl/" xmlns:tns="http://com.aam.jaxws.server/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap12="http://schemas.xmlsoap.org/wsdl/soap12/">
  <import namespace="http://server.jaxws.aam.com/" location="PersonManagementServicePortType.wsdl"/>
  <binding name="PersonManagementServicePortBinding" type="ns1:PersonManagementService" xmlns:ns1="http://server.jaxws.aam.com/">
    <soap12:binding transport="http://www.w3.org/2003/05/soap/bindings/HTTP/" style="document"/>
    <operation name="findPersonByCIN">
      <soap12:operation soapAction=""/>
      <input>
        <soap12:body use="literal"/>
      </input>
      <output>
        <soap12:body use="literal"/>
      </output>
      <fault name="PersonException">
        <soap12:fault name="PersonException" use="literal"/>
      </fault>
    </operation>
  </binding>
  <service name="PersonManagementService">
    <port name="PersonManagementServicePort" binding="tns:PersonManagementServicePortBinding">
      <soap12:address location="REPLACE_WITH_ACTUAL_URL"/>
    </port>
  </service>
</definitions>


2.6 Test with SOAPUI 4.5.1 :

You have now successfully created and published your web service and Testd it using Soap UI.

You can use this links to Download source code
  DOWNLOAD SERVER PROJECT

After downloading, execute mvn clean install command  and  import the prjectto your eclipse. You can after deploy the WebService in your favorite server and use Soap UI or move on to the next article to generate a java client project using jaxws and maven

END.