Imprimer

Nous allons dans cet article :

Fonctionnellement, le web service permettra de déclarer un projet dans la base de données. Pour faire simple, notre objet "Projet" a comme seul attribut un nom et un identifiant.

 

Le projet Maven Prj1WebServiceWar hébergeant le web service

Le fichier pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<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>com.mycompany.prj1</groupId>
<artifactId>Prj1WebService</artifactId>
<version>1.0</version>
<packaging>war</packaging>
<name>Prj1WebServiceWar</name>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.7</maven.compiler.source>
<maven.compiler.target>1.7</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-api</artifactId>
<version>7.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.16</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.10</version>
<scope>test</scope>
</dependency>
</dependencies>

<build>

<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>2.4</version>
<configuration>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
</plugins>
</build>

</project>

Le bean métier Project

 
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.mycompany.prj1.beans;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;

/**
 *
 * @author thierry
 */
@Entity
@Table(name = "PROJECT")

@NamedQueries({
    @NamedQuery(name = Project.FIND_ALL_PROJECTS, query = "SELECT dto FROM Project dto"),
    @NamedQuery(name = Project.FIND_BY_NAME, query = "SELECT dto FROM Project dto where upper(dto.name) like upper (:pName)")
})

public class Project {

    public static final String FIND_ALL_PROJECTS = "PROJECT_FIND_ALL";

    public static final String FIND_BY_NAME = "PROJECT_FIND_BY_NAME";

    public Project() {
    }

    @Id
    @Column(name = "PROJECT_ID")
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long projectId;

    @Column(name = "NAME", unique = true, nullable = false)
    private String name;

    public Long getProjectId() {
        return projectId;
    }

    public void setProjectId(Long projectId) {
        this.projectId = projectId;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String toString() {
        return "Project : name=" + name;
    }

}

L'interface métier

 
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.mycompany.prj1.inter;

import com.mycompany.prj1.beans.Project;
import java.util.List;

/**
 *
 * @author thierry
 */
public interface InterfaceProjectDao {

    public Project insertProject(Project dto);

    public List getAllProjects();

}

Le web service

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.mycompany.prj1.webservice;

import com.mycompany.prj1.beans.Project;
import com.mycompany.prj1.inter.InterfaceProjectDao;
import java.util.List;
import javax.jws.WebService;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.apache.log4j.Logger;

/**
 *
 * @author thierry
 */
@WebService
public class ProjectDaoBean implements InterfaceProjectDao {

    private static final Logger logger = Logger.getLogger(ProjectDaoBean.class);

    @PersistenceContext(unitName = "puBdProject")
    private EntityManager entityManager;

    public Project insertProject(Project project) {

        logger.info("Sauvegarde du projet : [" + project.getName() + "]");
        if (project.getProjectId() == null) {
            saveNewProject(project);
        } else {
            updateProject(project);
        }
        return project;
    }

    public List getAllProjects() {
        List list = null;
        try {
            list = entityManager.createNamedQuery(Project.FIND_ALL_PROJECTS).getResultList();
        } catch (Exception e) {
            logger.error("Exception, message d'erreur : " + e.toString());
            e.printStackTrace();
        }
        return list;
    }

    private void updateProject(Project project) {
        logger.info("In updateProject");
        entityManager.merge(project);
    }

    private void saveNewProject(Project project) {
        logger.info("In saveNewProject");
        entityManager.persist(project);
    }

}

Le wsdl du web service est alors disponible à : http://localhost:8080/Prj1WebServiceWar/ProjectDaoBeanService?wsdl

 

Le projet Maven Prj1WebServiceWarClient hébergeant le client java du web service

Le client java doit récupérer les classes java indispensables pour contacter le web service.

Ces classes peuvent être générées par l'utilitaire glassfish wsimport

http://localhost:8080/Prj1WebServiceWar/ProjectDaoBeanService?wsdl

Cette commande crée les classes suivantes :

GetAllProjects.class          package-info.class
GetAllProjectsResponse.class  Project.class
InsertProject.class           ProjectDaoBean.class
InsertProjectResponse.class   ProjectDaoBeanService.class
ObjectFactory.class

Il faut configurer votre IDE afin que votre projet client connaisse ces classes, ce qui se déclare dans le pom.xml.

 

Le fichier pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<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>com.mycompany.prj1</groupId>
<artifactId>Prj1TestClientWebService</artifactId>
<version>1.0</version>
<packaging>jar</packaging>
<name>Prj1WebServiceWarClient</name>
<dependencies>
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-api</artifactId>
<version>7.0</version>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<finalName>calculatorserviceclient</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-antrun-plugin</artifactId>
<executions>
<execution>
<phase>generate-sources</phase>
<configuration>
<tasks>
<property name="target.dir" value="target" />
<delete dir="${target.dir}/classes/com/testapp/ws/client" />
<delete dir="${target.dir}/generated-sources/main/java/com/testapp/ws/client" />
<mkdir dir="${target.dir}/classes" />
<mkdir dir="${target.dir}/generated-sources/main/java" />
<taskdef name="wsimport" classname="com.sun.tools.ws.ant.WsImport">
<classpath path="/home/thierry/glassfish-4.0/glassfish/modules/webservices-osgi.jar" />
<classpath path="/home/thierry/glassfish-4.0/glassfish/modules/jaxb-osgi.jar" />
<classpath path="/home/thierry/glassfish-4.0/glassfish/lib/javaee.jar" />
</taskdef>
<!-- ProjectDaoBeanService -->
<wsimport wsdl="http://localhost:8080/Prj1WebServiceWar/ProjectDaoBeanService?wsdl"
destdir="${target.dir}/classes" verbose="true"
keep="true" sourceDestDir="${target.dir}/generated-sources/main/java" xendorsed="true" />
</tasks>
<sourceRoot>${project.build.directory}/generated-
sources/main/java</sourceRoot>
</configuration>
<goals>
<goal>run</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>2.5</version>
<configuration>
<archive>
<manifest>
<mainClass>com.mycompany.prj1.prj1testclientwebservice.TestAppelWebService</mainClass>
<addClasspath>true</addClasspath>
</manifest>
</archive>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
</plugins>
</build>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.7</maven.compiler.source>
<maven.compiler.target>1.7</maven.compiler.target>
</properties>
</project>

La classe d'appel de votre web service

/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.mycompany.prj1.prj1testclientwebservice;

import com.mycompany.prj1.webservice.Project;
import com.mycompany.prj1.webservice.ProjectDaoBean;
import com.mycompany.prj1.webservice.ProjectDaoBeanService;
import java.util.List;
import javax.xml.ws.WebServiceRef;

/**
*
* @author thierry
*/
public class TestAppelWebServiceProject {

@WebServiceRef(wsdlLocation = "http://localhost:8080/Prj1WebServiceWar/ProjectDaoBeanService?wsdl")
private static ProjectDaoBeanService webService;

public static void main(String[] args) {

Project project = new Project();
project.setName("testPrj1");

ProjectDaoBean service = new ProjectDaoBeanService().getProjectDaoBeanPort();
List<Project> list = service.getAllProjects();
System.out.println("nombre de projet :" + list.size());

}

}

Code source

Prj1WebServiceWar.zip

Prj1WebServiceWarClient.zip

Bibliographie

http://fr.openclassrooms.com/informatique/cours/les-services-web

http://docs.oracle.com/javaee/5/tutorial/doc/bnayn.html