1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 
21 22 23 24 25 26 27 28 29 30 31 32 33 

EJB 2 - Les Entreprise Java Bean (JavaBeans)

6.6.Développement des clients

Dans l’application que nous développons, deux types de clients existent :
  • Le client console (ou Swing ou SWT, type client riche) : utilisé par les administrateurs par exemple
  • Le client web : utilisé par les clients de l’entreprise (afin de voir le catalogue par exemple …)

Ces deux types de clients se connectent sur les mêmes services métiers. Nous verrons comment ils se connectent, les points communs et les différences.

6.6.1.Client console (administrateur)

Voici le code du client console :

package client;

import java.util.Collection;
import java.util.HashSet;
import java.util.Hashtable;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.rmi.PortableRemoteObject;

import com.society.stockmanager.vo.ProductData;
import com.society.stockmanager.vo.ProviderData;

/**
* EJB Test Client
*/
public class StoragePeople {

public StoragePeople() throws Exception {
setUp();
}

/** Home interface */
protected com.society.stockmanager.interfaces.StorageServiceHome home;

/**
* Get the initial naming context
*/
protected Context getInitialContext() throws Exception {
Hashtable props = new Hashtable();
props.put(
Context.INITIAL_CONTEXT_FACTORY,
"org.jnp.interfaces.NamingContextFactory");
props.put(
Context.URL_PKG_PREFIXES,
"org.jboss.naming:org.jnp.interfaces");
props.put(Context.PROVIDER_URL, "jnp://localhost:1099");
Context ctx = new InitialContext(props);
return ctx;
}

/**
* Get the home interface
*/
protected com.society.stockmanager.interfaces.StorageServiceHome getHome() throws Exception {
Context ctx = this.getInitialContext();
Object o = ctx.lookup("ejb/StorageService");
com.society.stockmanager.interfaces.StorageServiceHome intf = (com.society.stockmanager.interfaces.StorageServiceHome) PortableRemoteObject
.narrow(o, com.society.stockmanager.interfaces.StorageServiceHome.class);
return intf;
}

/**
* Set up the test case
*/
protected void setUp() throws Exception {
this.home = this.getHome();
}

/**
* Test for ejb.StorageService.sayHello()
*/
public void testSayHello() throws Exception {
com.society.stockmanager.interfaces.StorageService instance;
java.lang.String result;

// Parameters

// Instance creation
instance = this.home.create();

// Method call
result = instance.sayHello();

System.out.println(result);

// Various assertions
// assertNotNull(result);
}

/**
* Test for ejb.StorageService.getAllId()
*/
public void testAddProducts() throws Exception {
com.society.stockmanager.interfaces.StorageService instance;

// Parameters

// Instance creation
instance = this.home.create();

instance.addProduct(new ProductData(new Integer(1),"designation1", "description1", new Integer(30)), new String("famille1"));
instance.addProduct(new ProductData(new Integer(2),"designation2", "description2", new Integer(40)), new String("famille1"));
instance.addProduct(new ProductData(new Integer(3),"designation3", "description3", new Integer(30)), new String("famille2"));

// Various assertions
// assertNotNull(result);
}


/**
* Test for ejb.StorageService.getAllId()
*/
public void testGetAllProductIds() throws Exception {
com.society.stockmanager.interfaces.StorageService instance;
Integer result[];

// Parameters

// Instance creation
instance = this.home.create();

// Method call
result = instance.getAllProductIds();

for(int i = 0; i < result.length; i++) {
System.out.println(i + " => " + result [i]);
}

// Various assertions
// assertNotNull(result);
}

/**
* Test for ejb.StorageService.getAllId()
*/
public void testAddProductFamily() throws Exception {
com.society.stockmanager.interfaces.StorageService instance;

// Parameters

// Instance creation
instance = this.home.create();

instance.addProductFamily("famille1", "La famille 1 designation");
instance.addProductFamily("famille2", "La famille 2 designation");

// Various assertions
// assertNotNull(result);
}

/**
* Test for ejb.StorageService.getAllId()
*/
public void testAddCountry() throws Exception {
com.society.stockmanager.interfaces.StorageService instance;

// Parameters

// Instance creation
instance = this.home.create();

instance.addCountry(new Integer(1), "France");
instance.addCountry(new Integer(2), "Allemagne");

// Various assertions
// assertNotNull(result);
}

/**
* Test for ejb.StorageService.getAllId()
*/
public void testAddCity() throws Exception {
com.society.stockmanager.interfaces.StorageService instance;

// Parameters

// Instance creation
instance = this.home.create();

instance.addCity(new Integer(1), "Paris", new Integer(1));
instance.addCity(new Integer(2), "Marseille", new Integer(1));
instance.addCity(new Integer(3), "Hannovre", new Integer(2));
instance.addCity(new Integer(4), "Berlin", new Integer(2));

// Various assertions
// assertNotNull(result);
}

/**
* Test for ejb.StorageService.getAllId()
*/
public void testAddProvider() throws Exception {
com.society.stockmanager.interfaces.StorageService instance;

// Parameters

// Instance creation
instance = this.home.create();

// Preparations
Collection productIds = new HashSet();
productIds.add(new Integer(1));
productIds.add(new Integer(2));

instance.addProvider(new ProviderData(new Integer(1), "LaboSun", "Sup's", "75010"), new Integer("1"), productIds);

productIds = new HashSet();
productIds.add(new Integer(1));
productIds.add(new Integer(3));

instance.addProvider(new ProviderData(new Integer(2), "Sun management", "Sun Microsystems", "455"), new Integer("3"), productIds);
}

/**
* Test for ejb.StorageService.getAllProductFamily()
*/
public void testGetAllProductFamily() throws Exception {
com.society.stockmanager.interfaces.StorageService instance;

// Parameters

// Instance creation
instance = this.home.create();

System.out.println(instance.getAllProductFamily());

// Various assertions
// assertNotNull(result);
}

/**
* Test for ejb.StorageService.getAllId()
*/
public void testGetProductFamily(String code) throws Exception {
com.society.stockmanager.interfaces.StorageService instance;

// Parameters

// Instance creation
instance = this.home.create();

System.out.println(instance.findProductFamily(code));

// Various assertions
// assertNotNull(result);
}

/**
* Test for ejb.StorageService.getAllProductFamily()
*/
public void testGetAllProductByCountryId(Integer countryId) throws Exception {
com.society.stockmanager.interfaces.StorageService instance;

// Parameters

// Instance creation
instance = this.home.create();

System.out.println(instance.findProductByCountryId(countryId));

// Various assertions
// assertNotNull(result);
}

public static void main(String[] args) {

StoragePeople people = null;
// Create a StoragePeople object
try {
people = new StoragePeople();
}
catch(Exception e) {
System.out.println("Impossible to create a StoragePeople object error : " + e);
System.exit(-1);
}

// Try to say Hello of the EJB
try {

people.testSayHello();
}
catch(Exception e) {
System.out.println("Error during : testSayHello" + e);
}

// Add some countries
try {
people.testAddCountry();
}
catch(Exception e) {
System.out.println("Error during : testAddCountry " + e);
}

// Add some cities
try {
people.testAddCity();
}
catch(Exception e) {
System.out.println("Error during : testAddCity " + e);
}

// Add some product families
try {
people.testAddProductFamily();
}
catch(Exception e) {
System.out.println("Error during : testAddProductFamily " + e);
}

// Try to get the famille1 object
try {
people.testGetProductFamily("famille1");
}
catch(Exception e) {
System.out.println("Error during : testGetProductFamily famille1 " + e);
}

// Try to get all product families
try {
people.testGetAllProductFamily();
}
catch(Exception e) {
System.out.println("Error during : testGetAllProductFamily " + e);
}

// Try to add some products
try {
people.testAddProducts();
}
catch(Exception e) {
System.out.println("Error during : testAddProducts " + e);
}

// Try to get all ids of products
try {
people.testGetAllProductIds();
}
catch(Exception e) {
System.out.println("Error during : testGetAllProductIds " + e);
}

// Try to add a provider
try {
people.testAddProvider();
}
catch(Exception e) {
System.out.println("Error during : testAddProvider " + e);
}

// Try to get product by countryId
try {
// France
people.testGetAllProductByCountryId(new Integer(1));
people.testGetAllProductByCountryId(new Integer(2));
}
catch(Exception e) {
System.out.println("Error during : testGetAllProductByCountryId " + e);
}
}
}


Le client n’a rien de spécial, il se connecte à l’EJB Session et appelle les différentes méthodes de celui-ci à distance.

6.6.2.Client web (client de l’entreprise)

Lorsque l’on souhaite se connecter à un EJB depuis une application Web (Servlet / JSP) nous sommes obliger de déclarer les références des EJB utilisés.



Dans un souci d’utilisation du pattern MVC, voici l’exemple utilisé pour lister l’ensemble des produits disponibles :



  1. La servlet appelle la méthode findAll() de l’EJB Session (partie Modèle)
  2. La servlet enregistre les données dans la requête (via request.setAttribute(…))
  3. La servlet passe « la main » à la page list.jsp qui permettra de faire le rendu HTML pour le client

Voici le code de la servlet :


package com.society.stockmanager.web;

import java.io.IOException;
import java.util.HashSet;

import javax.ejb.CreateException;
import javax.ejb.Handle;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.rmi.PortableRemoteObject;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.society.stockmanager.exceptions.NotFindException;
import com.society.stockmanager.interfaces.StorageService;
import com.society.stockmanager.interfaces.StorageServiceHome;

/**
* List Product Servlet Class
*
* @web.servlet name="ListProduct" display-name="Name for ListProduct"
* description="Description for ListProduct"
* @web.servlet-mapping url-pattern="/ListProduct"
* @web.servlet-init-param name="parameter1" value="A value"
*
* @web.ejb-ref name="ejb/StorageService" type="Session"
* home="com.society.stockmanager.interfaces.StorageServiceHome"
* remote="com.society.stockmanager.interfaces.StorageService"
* description="Reference to the StorageService EJB"
*
* @jboss.ejb-ref-jndi ref-name = "ejb/StorageService" jndi-name =
* "ejb/StorageService"
*
*/
public class ListProductServlet extends HttpServlet {

private StorageServiceHome home;

public ListProductServlet() {
super();
}

public void init(ServletConfig config) throws ServletException {
super.init(config);
try {
Context context = new InitialContext();
Object ref = context.lookup("java:comp/env/"
+ StorageServiceHome.JNDI_NAME);
Handle handle = (Handle) ref;
System.out.println("Handle OK : " + handle);

Class[] interfaces = ref.getClass().getInterfaces();
for (int i = 0; i < interfaces.length; i++) {
System.out.println(i + " = " + interfaces[i]);
}

home = (StorageServiceHome) PortableRemoteObject.narrow(ref,
StorageServiceHome.class);

System.out.println("StorageServiceHome OK");
} catch (Exception e) {
throw new ServletException("Lookup of "
+ StorageServiceHome.COMP_NAME + " failed (" + e + ")");
}
}

protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
resp.getWriter().print("home : " + home);

try {
StorageService storageService = home.create();
req.setAttribute("listProduct", storageService.getAllProductData());
} catch (CreateException e) {
throw new ServletException(e);
} catch (NotFindException e) {
req.setAttribute("listProduct", new HashSet());
}

RequestDispatcher disp = getServletContext().getRequestDispatcher(
"/pages/listProduct.jsp");
disp.forward(req, resp);

}

protected void doPut(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doGet(req, resp);
}
}


Tags utilisés :
  • web.servlet : définit une servlet dans le descripteur de déploiement web
    • name : définit un nom pour votre servlet
    • display-name : nom plus descriptif pour votre servlet
    • description : description plus complète pour votre servlet
  • web.servlet-mapping : définit un mapping pour la servlet
    • url-mapping : url à laquelle la servlet est mappée
  • web.servlet-init-param : déclare un paramètre d’initialisation à la servlet
    • name : nom du paramètre
    • value : valeur du paramètre
  • web.ejb-ref : déclare une référence vers un EJB
    • name : nom de l’ejb référencé
    • type : type de l’ejb référencé
    • home : interface home à utiliser
    • remote : interface remote à utiliser
    • description : description de la référence
  • jboss.ejb-ref-jndi : déclare une référence JNDI vers un EJB pour la configuration JBoss
    • ref-name : nom JNDI de l’ejb référencé
    • jndi-name : nom JNDI utilisé dans l’application web


Voici le code la page listProduct.jsp :

<%@page contentType="text/html" %>
<%@page import="java.util.Collection" %>
<%@page import="java.util.Iterator" %>
<%@page import="com.society.stockmanager.vo.ProductData" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title>List of products</title>
</head>

<body bgcolor="#FFFFFF">
Liste of products : <br/>
<table>
<tr>
<td>Id</td>
<td>Designation</td>
<td>Description</td>
<td>Stock</td>
</tr>
<%
Collection allProducts = (Collection)request.getAttribute("listProduct");

Iterator it = allProducts.iterator();
while(it.hasNext()) {
ProductData product = (ProductData)it.next();
%>

<tr>
<td><%= product.getId() %></td>
<td><%= product.getDesignation() %></td>
<td><%= product.getDescription() %></td>
<td><%= product.getQuantity() %></td>
</tr>
<%
}

%>
</table>
<br/>
</body>
</html>


6.6.3.Client JMS (application tierce)

Le client JMS est totalement indépendant de l’EJB Message Driven Bean. Pour plus d’informations concernant le code ci-dessous, vous pouvez vous reporter à l’essentiel portant sur JMS.


package client;

import java.util.Hashtable;

import javax.jms.ObjectMessage;
import javax.jms.Queue;
import javax.jms.QueueConnection;
import javax.jms.QueueConnectionFactory;
import javax.jms.QueueSender;
import javax.jms.QueueSession;
import javax.jms.Session;
import javax.naming.Context;
import javax.naming.InitialContext;

import com.society.stockmanager.vo.ProductMessageDrivenData;

public class ClientProductAddMessage {

/**
* Get the initial naming context
*/
protected Context getInitialContext() throws Exception {
Hashtable props = new Hashtable();
props.put(Context.INITIAL_CONTEXT_FACTORY,
"org.jnp.interfaces.NamingContextFactory");
props.put(Context.URL_PKG_PREFIXES,
"org.jboss.naming:org.jnp.interfaces");
props.put(Context.PROVIDER_URL, "localhost");
return new InitialContext(props);
}

public static void main(String[] args) {
ClientProductAddMessage client = new ClientProductAddMessage();
try {
Context jndiContext = client.getInitialContext();
// Context jndiContext = new InitialContext();
QueueConnectionFactory queueConnectionFactory = (QueueConnectionFactory) jndiContext
.lookup("ConnectionFactory");
Queue queue = (Queue) jndiContext
.lookup("queue/StockManager/ProductAddQueue");

QueueConnection queueConnection = queueConnectionFactory
.createQueueConnection();
QueueSession queueSession = queueConnection.createQueueSession(
false, Session.AUTO_ACKNOWLEDGE);
QueueSender queueSender = queueSession.createSender(queue);

ObjectMessage message = queueSession.createObjectMessage();

message.setObject(new ProductMessageDrivenData(new Integer(40),
"Description JMS", "Designation JMS", new Integer(500),
"famille2"));

queueSender.send(message);
} catch (Exception e) {
System.out.println(" Error : " + e);
}
}

}



1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 
21 22 23 24 25 26 27 28 29 30 31 32 33 

Retrouvez ci-dessous les autres sections du Laboratoire Sun
Exemples de code
JavaManipuler les looks and feel (lister et affecter)10/15/07
JavaFaire sa propre injection de dépendance avec les annotations5/9/06
JavaSplash screen avec progress Bar5/5/06
JavaFaire un splash screen en swing5/5/06

Essentiels de cours Java
JavaEJB 3 - Les Entreprise Java Bean version 3 (JavaBeans)
Cet essentiel est la suite de « Entreprise JavaBean 2.1 ». Cependant, nous allons étudier les nouvelles spécifications 3.0 qui simplifient énormément le développement par rapport aux EJB 2.6/20/06
JavaSWT - Créer des interfaces graphiques performantes
SWT (Standard Widget Toolkit) est une librairie graphique qui vous permet de réaliser des applications graphiques Java beaucoup plus avancées et surtout plus rapide à l’exécution.1/29/06
JavaStruts - Un framework MVC pour vos applications J2EE
Struts est un framework open-source qui vous permet de gagner du temps, mais qui permet aussi de voir des applications complexes comme une suite de composants de base : Vues, Actions, Modèles. Vous gagnez ainsi en évolutivité et en lisibilité du code.1/13/06
JavaHibernate - Persistance objet - relationnel
Cet essentiel explique comment utiliser Hibernate afin de gérer la persistance objet relationnel au sein de vos applications Java.12/14/05
JavaIntroduction J2EE - Applications d'entreprise
Cours d'introduction aux diverses technologies et outils que l'on peut rencontrer dans le monde du Java orienté entreprise J2EE12/14/05
JavaEJB 2 - Les Entreprise Java Bean (JavaBeans)
L'objectif avec EJB2 (Entreprise JavaBeans) est d'introduire les concepts de l’Ingénierie Logicielle Basée sur les Composants.12/14/05
JavaDesign Pattern - Améliorez l'architecture de vos programmes
Afin de répondre a des situation récurrentes en programmation, les "design pattern" apportent une solution type à beaucoup de contraintes liées à la programmation objet.12/14/05
JavaArchitecture J2EE - Comment organiser son application J2EE
Ce cours explique comment créer un code modulable, lisible et évolutif afin d'assurer la pérénité de son application.12/14/05
JavaLes web-services - Publication de services
Le développement tend vers les technologies du Web. Il est difficile de faire la distinction entre les différents logiciels qui sont de plus en plus intégrés au Web. Les Web Services rentrent dans l’optique de différencier bien précisément les couches.12/14/05
JavaAnt - L'automatisation des tâches du programmeur
Ecrire des scripts afin d'exécuter les tâches récurrentes10/31/05
JavaIntroduction au langage Java - Présentation & historique
Présentation des origines du langage, ainsi que se buts premiers8/11/05
JavaLa Syntaxe Java - Bases & nomenclatures
Bases de la syntaxe du langage Java8/11/05
JavaLes Classes - Concepts & héritage
Base du développement objet en Java grâce aux classes8/11/05
JavaLes Exceptions - Gestion d'erreurs
Gérer les erreurs liés à la programmation8/11/05

Articles
Eclipse Europa : le successeur de Callisto
Après Eclipse Callisto (Eclipse 3.2), la fondation Eclipse sort la nouvelle mouture d'Eclipse appelée Europa (Eclipse 3.3) faisant ainsi passer le nombre de projets embarqués de 10 à 21. Que ceux qui sont réticents aux « distributions » d'Eclipse se rassu12/21/07
JavaCruiseControl : l’outil d’intégration continue à avoir dans sa boite à outils
CruiseControl est un projet open-source offrant de multiples fonctionnalités pour l’intégration, que ce soit pour des développements Java ou .Net. Il est courant sur un projet d’être plusieurs développeurs avec des tâches de développement réparties. Dans7/2/07
JavaEJB3 - Des concepts à l'écriture du code - Editions DUNOD
Consulter le résumé du premier ouvrage du laboratoire Sun de SUPINFO : EJB3 - Des concepts à l'écriture du code. Guide du développeur, éditions DUNOD.5/27/07
JavaPassage de certification Java Web (SCWCD)
Passer une certification est toujours un moment important car cela permet de mieux faire reconnaître ses compétences face à un recruteur ou un employeur.5/12/07
JavaGoogle Web Toolkit
Google Web Toolkit est un framework java pour générer du javascript et des requêtes Ajax à partir d’un code java. Voilà comment il fonctionne.5/10/07
JavaJ2ME Vs SDE
Demain, les terminaux « légers » seront plus nombreux que les ordinateurs personnels, ce qui entraîne une bataille sur le choix d’une plateforme identique à tous ces terminaux… Aujourd’hui nous retrouvons le J2ME ainsi que le SDE qui s’offrent une rude b4/22/07

Tips du laboratoire
EclipseVisual Editor avec Eclipse Europa, c'est possible3/28/08
EclipseGérer les projets dans un workspace.10/16/07
JavaManager votre server d'application avec Eclipse4/21/07
JavaVue des sub-packages avec Eclipse4/21/07
JavaGlisser-déposer avec Eclipse4/21/07

Laboratoire SUPINFO des technologies Sun
labo-sun@supinfo.com


Conditions d'utilisation et © Copyright SUPINFO International University
23, rue de Château Landon - 75010 PARIS - Tél : +33 (0) 153359700 Fax : +33 (0) 153359701
Respect de la vie privée