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.4.Développement des Session Bean

Lors de la conception, nous avons défini deux services, représenté par deux session bean. Pour des raisons de simplification, nous allons présenter qu’un seul bean combinant l’ensemble des fonctionnalités.
Voici les fonctionnalités que ce service propose :
  • Récupérer l’ensemble des produits
  • Récupérer l’ensemble des produits à partir d’une famille
  • Récupérer l’ensemble des produits ayant un fournisseur d’un pays précis
  • Récupérer l’ensemble des familles de produit
  • Ajouter un produit
  • Supprimer un produit
  • Ajouter une famille de produit
  • Supprimer une famille de produit
  • Ajouter un fournisseur
  • Supprimer un fournisseur
  • Ajouter un pays
  • Supprimer un pays
  • Ajouter une ville
  • Supprimer une ville


Voici le code de ce bean :

package com.society.stockmanager.ejb;

import java.rmi.RemoteException;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;

import javax.ejb.CreateException;
import javax.ejb.EJBException;
import javax.ejb.FinderException;
import javax.ejb.SessionBean;
import javax.ejb.SessionContext;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.rmi.PortableRemoteObject;

import com.society.stockmanager.exceptions.NotFindException;
import com.society.stockmanager.interfaces.CityLocalHome;
import com.society.stockmanager.interfaces.CountryLocal;
import com.society.stockmanager.interfaces.CountryLocalHome;
import com.society.stockmanager.interfaces.ProductFamilyLocal;
import com.society.stockmanager.interfaces.ProductFamilyLocalHome;
import com.society.stockmanager.interfaces.ProductLocal;
import com.society.stockmanager.interfaces.ProductLocalHome;
import com.society.stockmanager.interfaces.ProviderLocal;
import com.society.stockmanager.interfaces.ProviderLocalHome;
import com.society.stockmanager.vo.ProductData;
import com.society.stockmanager.vo.ProductFamilyData;
import com.society.stockmanager.vo.ProviderData;


/**
* @ejb.bean name="StorageService"
* display-name="Name for StorageService"
* description="Description for StorageService"
* jndi-name="ejb/StorageService"
* type="Stateless"
* view-type="remote"
*
*
* @ejb.ejb-ref ejb-name = "Product" view-type = "local"
*
* @ejb.ejb-ref ejb-name = "ProductFamily" view-type = "local"
*
* @ejb.ejb-ref ejb-name = "Provider" view-type = "local"
*
* @ejb.ejb-ref ejb-name = "City" view-type = "local"
*
* @ejb.ejb-ref ejb-name = "Country" view-type = "local"
*
*/
public class StorageServiceBean implements SessionBean {

public StorageServiceBean() {
super();
}

public void setSessionContext(SessionContext ctx)
throws EJBException,
RemoteException {

}

public void ejbRemove() throws EJBException, RemoteException {

}

public void ejbActivate() throws EJBException, RemoteException {

}

public void ejbPassivate() throws EJBException, RemoteException {

}

/**
* Retourne l'interface home associÈe ‡ un nom JNDI. Il est ‡ noter qu'on
* obtient toujours l'interface locale aprËs un narrow.
*
* @param jndiNaming
* @param interfaceClassNarrowed
* @return
* @throws Exception
*/
private Object getHomeInterface(String jndiNaming,
Class interfaceClassNarrowed) throws Exception {
Context ctx = new InitialContext();
Object ref = ctx.lookup(jndiNaming);
Object interfaceNarrowed = PortableRemoteObject.narrow(ref,
interfaceClassNarrowed);
return interfaceNarrowed;
}

/**
* Get an objet ProductLocalHome by lookup.
*
* @return interface ProductLocalHome
* @throws Exception
*/
private ProductLocalHome getProductHome() throws Exception {
return (ProductLocalHome) getHomeInterface("java:comp/env/"
+ ProductLocalHome.JNDI_NAME, ProductLocalHome.class);
}

/**
* Get an objet ProductFamilyLocalHome by lookup
*
* @return interface ProductFamilyLocalHome
* @throws Exception
*/
private ProductFamilyLocalHome getProductFamilyHome() throws Exception {
return (ProductFamilyLocalHome) getHomeInterface("java:comp/env/"
+ ProductFamilyLocalHome.JNDI_NAME, ProductFamilyLocalHome.class);
}

/**
* Get an objet ProviderLocalHome by lookup
*
* @return interface ProviderLocalHome
* @throws Exception
*/
private ProviderLocalHome getProviderHome() throws Exception {
return (ProviderLocalHome) getHomeInterface("java:comp/env/"
+ ProviderLocalHome.JNDI_NAME, ProviderLocalHome.class);
}

/**
* Get an objet CityLocalHome by lookup
*
* @return interface CityLocalHome
* @throws Exception
*/
private CityLocalHome getCityHome() throws Exception {
return (CityLocalHome) getHomeInterface("java:comp/env/"
+ CityLocalHome.JNDI_NAME, CityLocalHome.class);
}

/**
* Get an objet CityLocalHome by lookup
*
* @return interface CityLocalHome
* @throws Exception
*/
private CountryLocalHome getCountryHome() throws Exception {
return (CountryLocalHome) getHomeInterface("java:comp/env/"
+ CountryLocalHome.JNDI_NAME, CountryLocalHome.class);
}

/**
* Default create method
*
* @throws CreateException
* @ejb.create-method
*/
public void ejbCreate() throws CreateException {

}

/**
* Business method
* @ejb.interface-method view-type = "remote"
*/
public String sayHello() {
return "say Hello ";
}

/**
* Business method
* @ejb.interface-method view-type = "remote"
*/
public Integer[] getAllProductIds() {
Integer[] result = null;
try {
System.out.println("Debut ");
Collection allProducts = getProductHome().findAll();
System.out.println("Size : " + allProducts.size());
result = new Integer[allProducts.size()];
Iterator it = allProducts.iterator();
int index = 0;
while(it.hasNext()) {
ProductLocal product = (ProductLocal)it.next();
result[index] = product.getId();
index++;
}
}
catch(Exception e) {

}
return result;
}

/**
* Business method
* @ejb.interface-method view-type = "remote"
*/
public Collection getAllProductData() throws NotFindException {
Collection result = new HashSet();
try {
Collection allProducts = getProductHome().findAll();
Iterator it = allProducts.iterator();
while(it.hasNext()) {
ProductLocal product = (ProductLocal)it.next();
result.add(product.getData());
}
}
catch(Exception e) {
throw new NotFindException(e);
}
return result;
}

/**
* Business method
* @ejb.interface-method view-type = "remote"
*/
public Collection getAllProductFamily() {
Collection returnAll = new HashSet ();
try {
System.out.println("Debut ");
Collection allProductFamily = getProductFamilyHome().findAll();
System.out.println("Size : " + allProductFamily.size());
Iterator it = allProductFamily.iterator();
int index = 0;
while(it.hasNext()) {
ProductFamilyLocal productFamily = (ProductFamilyLocal)it.next();
returnAll.add(productFamily.getData());
}
}
catch(Exception e) {
System.out.println("Erreur : " + e);
}
return returnAll;
}

/**
* Business method
* @ejb.interface-method view-type = "remote"
*/
public void addProduct(ProductData datas, String codeFamily) {
try {
ProductLocal product = getProductHome().create(datas, getProductFamilyHome().findByPrimaryKey(codeFamily));
System.out.println(" Add product with datas : " + datas);
}
catch(CreateException e) {
System.out.println(" Error during Add product with data : " + datas + " / " + e);
}
catch(FinderException e) {
System.out.println(" Error during finding productFamily with id : " + codeFamily + " / " + e);
}
catch(Exception e) {
System.out.println(e);
}
}

/**
* Business method
* @ejb.interface-method view-type = "remote"
*/
public void removeProduct(Integer productId) {
try {
ProductLocal product = getProductHome().findByPrimaryKey(productId);
product.remove();
System.out.println(" Remove product with id : " + productId);
return;
}
catch(FinderException e) {
System.out.println(" Error during finding product with id : " + productId + " / " + e);
}
catch(Exception e) {
System.out.println(e);
}
}

/**
* Business method
* @ejb.interface-method view-type = "remote"
*/
public void addProductFamily(String code, String designation) {
try {
getProductFamilyHome().create(code, designation);
System.out.println(" Add productFamily with id : " + code);
}
catch(Exception e) {
System.out.println(" Error during Add product family with id : " + code + " / " + e);
}
}

/**
* Business method
* @ejb.interface-method view-type = "remote"
*/
public void removeProductFamily(String code) {
try {
ProductFamilyLocal prodFamily = getProductFamilyHome().findByPrimaryKey(code);
System.out.println(" Remove productFamily with id : " + code);
}
catch(Exception e) {
System.out.println(" Error during remove product family with id : " + code + " / " + e);
}
}

/**
* Business method
* @ejb.interface-method view-type = "remote"
*/
public void addProvider(ProviderData datas, Integer cityId, Collection productIds) {
try {
// Prepare products collection
Collection products = new HashSet();
Iterator itProducts = productIds.iterator();
while(itProducts.hasNext()) {
Integer productId = (Integer) itProducts.next();
products.add(getProductHome().findByPrimaryKey(productId));
}

System.out.println("List of products : " + products);

getProviderHome().create(datas, getCityHome().findByPrimaryKey(cityId), products);
System.out.println(" Add provider with datas : " + datas);
}
catch(FinderException e) {
System.out.println("Disable to find product error : " + e);
}
catch(Exception e) {
System.out.println(" Error during Add provider with datas : " + datas + " / " + e);
}
}

/**
* Business method
* @ejb.interface-method view-type = "remote"
*/
public void removeProvider(Integer providerId) {
try {
ProviderLocal provider = getProviderHome().findByPrimaryKey(providerId);
System.out.println(" Remove provider with id : " + providerId);
}
catch(Exception e) {
System.out.println(" Error during remove provider with id : " + providerId + " / " + e);
}
}

/**
* Business method
* @ejb.interface-method view-type = "remote"
*/
public void addCountry(Integer countryId, String name) {
try {
getCountryHome().create(countryId, name);
System.out.println(" Add country with id : " + countryId);
}
catch(Exception e) {
System.out.println(" Error during Add country with id : " + countryId + " / " + e);
}
}

/**
* Business method
* @ejb.interface-method view-type = "remote"
*/
public void removeCountry(Integer countryId) {
try {
CountryLocal country = getCountryHome().findByPrimaryKey(countryId);
System.out.println(" Remove country with id : " + countryId);
}
catch(Exception e) {
System.out.println(" Error during remove country with id : " + countryId + " / " + e);
}
}

/**
* Business method
* @ejb.interface-method view-type = "remote"
*/
public void addCity(Integer cityId, String name, Integer countryId) {
try {
getCityHome().create(cityId, name, getCountryHome().findByPrimaryKey(countryId));
System.out.println(" Add city with id : " + countryId);
}
catch(FinderException e) {
System.out.println("Disable to find country error : " + e);
}
catch(Exception e) {
System.out.println(" Error during Add city with id : " + countryId + " / " + e);
}
}

/**
* Business method
* @ejb.interface-method view-type = "remote"
*/
public void removeCity(Integer cityId) {
try {
getCityHome().findByPrimaryKey(cityId);
System.out.println(" Remove city with id : " + cityId);
}
catch(FinderException e) {
System.out.println("Disable to find city error : " + e);
}
catch(Exception e) {
System.out.println(" Error during remove city with id : " + cityId + " / " + e);
}
}

/**
* Business method
* @ejb.interface-method view-type = "remote"
*/
public ProductFamilyData findProductFamily(String code) {
ProductFamilyData product = null;
try {
product = getProductFamilyHome().findByPrimaryKey(code).getData();
System.out.println(" find productFamily with id : " + code);
}
catch(Exception e) {
System.out.println(" Error during find product family with id : " + code + " / " + e);
}
return product;
}

/**
* Business method
* @ejb.interface-method view-type = "remote"
*/
public Collection findProductByCountryId(Integer countryId) {
Collection result = new HashSet();

try {
Collection foundProducts = getProductHome().findAllByCountryId(countryId);
Iterator it = foundProducts.iterator();
while(it.hasNext()) {
ProductLocal product = (ProductLocal)it.next();
result.add(product.getPrimaryKey());
}
}
catch(Exception e) {
System.out.println(" Error during find product with countryid : " + countryId + " / " + e);
}

return result;
}

}


  • ejb.ejb-ref : déclare une référence vers un autre EJB.
    • ejb-name : nom de l’EJB référence
    • view-type : type de vue de l’EJB

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