|
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 :  - La servlet appelle la méthode findAll() de l’EJB Session (partie Modèle)
- La servlet enregistre les données dans la requête (via request.setAttribute(…))
- 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); } } }
|
|
 |