Вы находитесь на странице: 1из 78

L'environnementJavaEE: Principes,tatsdeslieuxetvolutions

GuillaumeSauthier(BullSAS) Guillaume.Sauthier@Bull.Net http://jonas.ow2.org

Plan
s Introductionl'environnementJavaEE s ComposantsJavaEE s Servicesfournisparl'environnement
x Rpartition x Transactions x Scurit

s ModlesdeprogrammationJavaEE
x Client/Web/EJB x Persistance

2008,G.Sauthier

Introduction

2008,G.Sauthier

ObjectisdeJavaEE1/2
s Infrastructureserveurpourlesupportd'applications

d'entreprise
x Ecommerce(B2B&B2C) x Systmesd'informations x Platesformesdeservices(Audiovisuel,telco,...)

s Architecturemultitiers
x Clientlger(basesurlesnavigateurs) y Web,WAP,vocale(synthse,reco) y ArtefactsXML(XHTML,WML,VoiceXML) x Clientslourds(GUIavances) x SOA(applicationrparties)

2008,G.Sauthier

ObjectifsdeJavaEE2/2
s QoS(Qualitdeservice)
x Transactions x Scurit(authentification,autorisation,confidentialit) x Gestiondesressources

s ConnexionstandardauxSIexternes(legacy)
x Supportdel'EAI x SupportXML

2008,G.Sauthier

CequedfinitJavaEE
s Spcificationdelaplateforme
x Composants,containers(programmation,assemblage,dploiement) x Serveuretservices(excution)

s Implmentationderfrenceoprationnelle(Glassfish) s Kitdeverificationdeconformitdesapplication(AVK) s Testsdecompatibilitdesimplmentations(TCK)


x CertificationSun x Processuspayantsaufpourlesproduitsopensource x Lourdmettreenoeuvre(+de20000tests)

s Conseilsdemiseenoeuvre
x JavaEEblueprints(petstore,adventurebuilder,...)

2008,G.Sauthier

Overviewdel'architectureJavaEE

2008,G.Sauthier

JavaEE5commebaseducours
s Simplificationdudveloppement
x Annotations(depuisJavaSE5) x Contraintesdeprogrammationdescomposantsassouplies

s Enrichissementfonctionnel
x TiersdeprsentationavecJavaServerFaces x TiersdedonnesavecJavaPersistenceAPI x volutionmajeuredesEJB y Sparationgestiondescomposants/gestiondesobjets persistants

2008,G.Sauthier

Exempledefilconducteur

2008,G.Sauthier

10

Inscriptionuneconfrence

2008,G.Sauthier

11

Dcompositiondel'application
s ApplicationICAR
x ApplicationJavaEE x Packaging:icar.ear x Contient2modules

s Prsentation
x SpcifiqueICAR x Packaging:icar.war

s Mtier
x Gestiond'unecole thmatique x Rutilisable x Packaging:school.jar x ContientlecodedesEJBet objetspersistants
2008,G.Sauthier 12

Composants: Dfinition,Assemblage, PackagingetDploiement

2008,G.Sauthier

13

Indpendance
s Recherched'uneind

pendancemaximaledu codeapplicatif
x Pasdeliaisonstatiqueentre lmentsdecodeapplicatif (composants) x Pasdeliaisonstatiqueentre lmentsdecodeapplicatifet servicesdelaplateforme x viterl'utilisationdecode techniquedanslecode applicatif(dclarativit/ transparence)

s Codeapplicatifplus

rutilisable!
2008,G.Sauthier 14

Rlesdesconteneurs
s Supportdudploiementdecomposants
x Installationd'applicationsetdelibrairies(.ear,.war,.rar,.jar) x Activationd'applicationsetdelibrairies

s Gestiondesliaisonsentrecomposants s Gestiondesliaisonsentrecomposantsetservicesde

l'environnement
s Supportdemodledeprogrammation
x Dfinitionetgestiondescyclesdevie x Transparencedemiseenoeuvredeservicestechniques (transactions,scurit,...)

2008,G.Sauthier

15

Principauxconteneurs
s Conteneurd'applicationclientes(clientslourds) s Conteneurd'applicationserveur
x Conteneurdeservlet x Conteneurd'EJB x Conteneurdeconnecteurs(ressourceadapters)

s Conteneurdepersistance
x IndpendantdeJavaEE x IntgrparleconteneurEJBdanslecadredeJavaEE

2008,G.Sauthier

16

ComposantsJavaEE
s Modulesdecoderutilisablequ'onpeutassembler
x Changementdeliaisonsentremodulesdecodeapplicatif y Sansimpactsurlecode x Configurationdesliaisonsentrecodeapplicatifetressources utilises y Sansimpactsurlecode

s Visionadhocnonsystmatique
x Sparationdesproccupationspasidale y Gestionstructuration/assemblage y Modledeprogrammation x Mtainformationsstructurellesnonhomogne:dfinitiondeliaison spcifiqueautypedeliaison(composant/composant, composant/ressource,...) x Packagingdiffrent(METAINFouWEBINF?)
2008,G.Sauthier 17

Dfinitiond'uncomposantJavaEE
s ComposantJavaEE
x CodeJava x Informationdescriptive(mtainformation)

s Codecontraintpardescontrats
x Implmentationd'interface(ouconformationdessignatures) x Cycledevie x Designpatterns y AbstractFactory y Accessor/JavaBean y ...

2008,G.Sauthier

18

Mtainformationd'uncomposant JavaEE
s Expressiondelamtainformation

x AnnotationJavaSE5 x DescripteursXML
s Typesdemtainformation

x Interfacesd'instancesoudefactory(home)
y Interfacesfournies

x Dfinitiondesdpendances:interfacesrequises
y Composant/Composant(Servlets,EJB,...) y Composant/Ressource(Services)
v Factory:JDBC,JMS,JCA,JavaMail,... v Resource:unedestinationJMS,unserviceweb v Casparticulier:UserTransaction,TimerService,ORB,...

x Dfinitiondepropritsparamtrables(nom,type,valeur) x Dfinitiondepropritsnonfonctionnelle(transaction, persistance,...) 2008,G.Sauthier


19

Utilisationdesannotations
s JavaEE5ncessiteJavaSE1.5pourlesupportdesannotations
x Manipulationsauniveausourceoul'excution(rflexion) x AssociauxconceptsJava(Type,Field,Method,Parameter,...)

s Descriptiondescomposantsdanslecode
x Touteslesinformationsdesdescripteurspeuventtreexprimssousla formed'annotationsdanslecode x Miseenoeuvrepluslgre:simplificationdudveloppement x 2typesd'informationspeuventtreutilisableindistinctementou simultanment(lesdescripteurssurchargentlesannotations)

s Principed'utilisation
x Certainesinformationsdescriptivesrelvedepropritsliesaucode(par exemplelecomportementtransactionnel,attributspersistants,...) x Annotationsutilisespourexprimerdesinformationspardfautoupourle dveloppement(propritsparamtrables,liaisons,...)

2008,G.Sauthier

20

Dfinitiond'uncomposant

2008,G.Sauthier

21

Exemplededfinitiond'uncomposant
@Stateful(name="Subscription") public class SubscriptionBean implements ISubscription { @Resource de private int maxParticipants = 10; @Resource private SessionContext sc;

Nom du bean dans l'espace nommage de l'ejbjar. Nom de la proprit dans l'espace de nommage du bean (java:comp/env)

/* or @Resource void setSessionContext(SessionContext c) { sc = c; } <session> Dfinition de la */ <ejb-name>Subscription</ejb-name> variable injecte } <business-local>org.ow2.icar.bean.ISubscription</business-local> <ejb-class>org.ow2.icar.bean.SubscriptionBean</ejb-class> <env-entry> Surcharge les <env-entry-name>property/maxParticipants</env-entry-name> annotations <env-entry-type>java.lang.Integer</env-entry-type> <env-entry-value>120</env-entry-value> <injection-target> <injection-target-name>maxParticipants</injection-target-name> </injection-target> </env-entry> </session>
2008,G.Sauthier 22

Dfinitiondesdpendances (rfrences)
s Rfrencesentrecomposantspackageensemble
x Dfinitiond'unnomlocal x Dfinitiondulieneffectif
y y Dsignationl'aidedunomlocalducomposant(dansl'espaceapplicatif) Dsignationl'aided'unnomJNDIpourrfrenceruncomposantdistant (attributmappedName)

s Rfrenceversuneressourceduserveur
x Dfinitiond'unnomlocal x Dfinitiondulieneffectif:spcifiqueenJ2EE1.4,dfinissableenJavaEE (attributmappedName)

s Conventiondenommage
x Nomdeproprit==nomdevariabledeclasseJava x Nomderessource(exejb)==nomdeclasseJava x Nomderfrenceprfixpartypederessource(ex:mail,ejb,...)
2008,G.Sauthier 23

Rfrenced'uncomposantEJB

@EJB(name="ejb/Subscription", beanName="icar.jar#Subscription") private ISubscription sessionSubscription;

<ejb-ref> <ejb-ref-name>ejb/Subscription</ejb-ref-name> <ejb-ref-type>org.ow2.icar.bean.ISubscription</ejb-ref-type> <ejb-link>icar.jar#Subscription</ejb-link> <injection-target> <injection-target-name>sessionSubscription</injection-target-name> </injection-target> </ejb-ref>

2008,G.Sauthier

24

RfrenceversuneDataSource JDBC

@Resource(name="jdbc/DBIcar", mappedName="jdbc_1") private DataSource dbIcar;

<resource-ref> <res-ref-name>jdbc/DBIcar</res-ref-name> <res-type>javax.sql.DataSource</res-type> <res-auth>Container</res-auth> <injection-target> <injection-target-name>dbIcar</injection-target-name> </injection-target> </resource-ref>

2008,G.Sauthier

25

RfrenceversuneressourceJMS

@Resource(name="jms/SubscriptionTopic", mappedName="IcarTopic") private Topic topic;

<resource-env-ref> <resource-env-ref-name>jms/SubscriptionTopic</resource-env-ref-name> <res-type>javax.jms.Topic</res-type> <injection-target> <injection-target-name>topic</injection-target-name> </injection-target> </resource-env-ref>

2008,G.Sauthier

26

Rfrenceversuneunitde persistanceJPA

@PersistenceUnit(name="persistence/DBSchool", unitName="icar.jar#SchoolData") private EntityManagerFactory emf;

<persistence-unit-ref> <persistence-unit-ref-name>persistence/DBSchool</persistence-unit-ref-name> <persistence-unit-name>icar.jar#DataSchool</persistence-unit-name> <injection-target> <injection-target-name>emf</injection-target-name> </injection-target> </persistence-unit-ref>

2008,G.Sauthier

27

Packageicar.ear
s Contenudel'archive: s Contenude

application.xml
<application> <display-name>ICAR'08</display-name> <description></description> <module> <web> <web-uri>icar.war</web-uri> <context-root>icar08</context-root> </web> </module> <module> <ejb>icar.jar</ejb> </module> </application>

META-INF/ MANIFEST.MF application.xml icar.war icar.jar

2008,G.Sauthier

28

Packageicar.jar
s Contenudel'archive:
x persistence.xml,cf sectionpersistance

s Contenudeejbjar.xml
x PasncessaireenEJB3.0

META-INF/ MANIFEST.MF ejb-jar.xml persistence.xml org/ school/ api/ *.class lib/ *Bean.class persistence/ *.class

<ejb-jar> <enterprise-beans> <session> <ejb-name>Subscription</ejb-name> <ejb-class> org.ow2.icar.bean.SubscriptionBean </ejb-class> <session-type>Stateful</session-type> [ . . . ] </session> </enterprise-beans> [ . . . ] </application>

2008,G.Sauthier

29

Supportdel'excutionrpartie

2008,G.Sauthier

30

Appeldemthodedistance

s RMI
x TransportJava(JRMP)ouCORBA(IIOP) x Standardd'interoprabilitinterserveursJavaEE(IIOP) x PropagationdecontextesoptionnelleenJavaEE5(transaction, scurit,...)

s WebServices
x Deuxmodles y JAXRPC1.1 y JAXWS2.x x BasesurunepileSOAPconfigurable y Supportdediffrentstypedetransport(SAAJ)

2008,G.Sauthier

31

Communicationasynchrone

s StandardJavaMessagingService(JMS)
x Clientsdepublicationetclientsdeconsommation y Modefiledemessages(queues):messageconsommparun uniqueconsommateur y Modetopic:messageconsommpartouslesconsommateurs inscrits x NiveauxdeQoSsurladlivranceetsurletraitement y Smantiqueaumoinsunefois,auplusunefois, exactementunefois y Persistance y Supporttransactionnel

2008,G.Sauthier

32

SystmedesconnecteursJCA

s Intgrationdessystmeslegacy
x Supportdeprotocolesdecommunicationddis x Supportdemessagessortantetentrants

s Contratsd'intgrationsystmes
x Gestionderservedeconnexions(dimensionnementdepool) x Gestiondestransactions x Gestiondelascurit

s UtilisaussipourintgrerdesservicesJavaEE
x ConnecteursJDBC x ConnecteursJMS

2008,G.Sauthier

33

Supportdestransactions

2008,G.Sauthier

34

Fonctionsdusupporttransactionnel (JTA)
s Gestiond'uncontextetransactionnel
x Dmarrage:begin() x Validation:commit() x Annulation:rollback()

s Associationducontextetransactionnelauthread

courant
x vitelepassageexplicited'unreprsentantdelatransactiondansle code x Attentionauxchangementsdecontexte:passaged'unthread l'autre

2008,G.Sauthier

35

Rleducontratclientdegestiondes transactions
s Interfacejavax.transaction.UserTransaction
x Gestionnairedetransactions x Vueclient

s Contrledelatransaction
x Dmarcation(begin,commit,rollback) x Gestiondetimeout x Demanded'annulationdiffrelaterminaison(rollbackonly) x Consultationdel'tat

2008,G.Sauthier

36

Miseenoeuvreducontratclientde gestiondestransactions
s Accsaugestionnairedetransactions
x Standardisdansl'environnementJavaEE x AccstraversJNDI x Nomstandard:java:comp/UserTransaction

UserTransactionutx=(UserTransaction)new InitialContext().lookup(java:comp/UserTransaction); utx.begin(); //... utx.commit(); //ouutx.rollback();

2008,G.Sauthier

37

Rleducontratsystmestandard degestiondestransactions
s Utilisparlescomposantsplutttechniques
x Connecteurs/ressourceadapters(JMS/JDO/...) x SystmesdepersistanceJPA x Etc

s Gestionnairedetransactionsvolu
x Permetl'interceptiondesvnementstransactionnels:enregistrement d'objetscallbacksjavax.transaction.Synchronisation(parexemple unetransactionJDO) x Permetdedfinirdesparamtresassocisaucontextetransactionnel x Utilisationdel'interface
javax.transaction.TransactionSynchronisationRegistry

2008,G.Sauthier

38

Miseenoeuvreducontratsystme standarddegestiondes transactions


s Accsaugestionnairedetransactionsvolu
x Standardisdansl'environnementJavaEE x AccstraversJNDI x Nomstandard:java:comp/TransactionSynchronisationRegistry

//Exemple:connecteurJCASpeedo TransactionSynchronisationRegistrytsr= (TransactionSynchronisationRegistry)new InitialContext().lookup(java:comp/ TransactionSynchronisationRegistry); JDOPOManagerpersistenceManager;//SpeedoPersistenceManager tsr.registerInterposedSynchronization(persistenceManager);

2008,G.Sauthier

39

Supportdelascurit

2008,G.Sauthier

40

Approchepourl'authentificationet l'autorisation
s Notionsdebase
x Principal=identifiant x Credential=principalauthentifi x Rle=profild'autorisation

s Gestiondelascurit
x Mtainformation(minimal) x Defaonprogrammatique (externalisation,gestion dynamique)

s Authentification
x Valideunprincipaletassocieun credentialsasession x Credentialpassausystme d'autorisation

s Autorisation
x Vrificationdedroitsd'utilisation aud'accs x Bassurlesrles x Rgle:accsautorissiun credentialestdansunrle autorisantl'accslaressource
2008,G.Sauthier 41

Composantsclientapplicatif (conteneurclient)

2008,G.Sauthier

42

Miseenoeuvreclientlourd1/2

s Deuxmoded'accsauserveur
x Appelsynchrone/RPC:RMI(JRMP/CORBA)ouWebServices x Appelasynchrone/publicationdemessages:JMS

s UtilisationdeRMI(transparencedelamiseenliaison

parrapportunaccslocaloudistant)
@EJB(name=ejb/Subscription, mappedName=Subscription) privateISubscriptionsub; //... InfoParticipantsub.infos(BillGates);

2008,G.Sauthier

43

Miseenoeuvreclientlourd2/2

s UtilisationdesWebServices

@WebServiceRef(name=ws/SubscriptionService, org.school.ws.ISubscriptionService.class) privateISubscriptionPortport; //... InfoParticipantport.infos(BillGates);

2008,G.Sauthier

44

Composantsdeprsentation (conteneurdeServlets)

2008,G.Sauthier

45

Serviceoffertparlaconteneurweb

s NotiondeServlet
x Gnrationdecontenuwebdynamique(pageHTMLouXML) x Activationdethreadpourtraitementd'unerequteparunobjet Servlet x Projectiond'URLsversunobjet

s Fonctionsdeplushautniveau
x JSP(JavaServerPages) y MlangeJava/HTML/XML(contenustatique+tags+directives) y CompilationenServletaudploiement x JSF(JavaServerFaces)(utiliseJSP) y Meilleursparationprsentation/contrle(Servletdecontrle) y Dfinitiond'ungraphed'enchanementdepages

2008,G.Sauthier

46

Servletenaction

@EJB(name=ejb/Subscription, beanName=icar.jar#Subscription) publicclassProcessFormServletextendsHttpServlet{ publicvoiddoGet(HttpServletRequestreq, HttpServletResponseresp){ InfoParticipantinfo=newInfoParticipant(); info.nom=req.getParameter(nom); //... ISubscriptionsub= ictx.lookup(java:comp/env/ejb/Subscription); sub.register(info); resp.setContentType(text/html); PrintWriterpw=resp.getWriter(); pr.println(html); //... } }

2008,G.Sauthier

47

Composantsmtiernon persistants(conteneurEJB)

2008,G.Sauthier

48

Supportdel'tagelogiquemtier1/2

s EJB=Composantsdfinissantlalogiqueapplicative s Version3reprsenteunevolutionnonngligeable
x Assurelacompatibilitascendante/2.1 x Resteconceptuellementcompatibleaveclaversion2.1 x Relchecertainescontraintesauniveaudumodledeprogrammation

s Principalobjectif:Simplifierlaviedudveloppeur
x LogiquePOJO x Pasd'implmentationdecontratsprogrammatique(SessionBean),mais respectdesignature x Pasncessairededfiniretdemanipulerdesfactory:miseenliaison automatique(injection) x Plusdecomposantspersistants:seulementdesPOJOssansdpendances

2008,G.Sauthier

49

Supportdel'tagelogiquemtier2/2
s Supportdelapersistancesparen2spcifications
x EJB3core:Intgrationdefournisseurdepersistanceindpendant x EJB3Persistence:JPA(javax.persistenceetnondansjavax.ejb)

s Pourl'essentieldescomposantsgrantdessessions

decommunicationavecunclientdel'application activ
x Parl'arrived'unmessaged'unclient y CommunicationsynchronetypeRPC y CommunicationasynchronetraversdescomposantsJCA x Pardesvnementstemporels(chanciers/timers)

2008,G.Sauthier

50

Lestypesdecomposantsmtiers
s Deuxmodesdecommunicationsupports
x Appeldeprocduredistance(RPC):RMI/CORBAouWebServices x Envoiedemessageasynchrone(pasd'attentebloquantectclient)

s Possibilitdegrerundialoguevoluentreunclient

etl'applicationserveur
x Sessiontraitantplusieursappelsconscutifs x Gestiond'informationsreprsentantl'tatdudialogue

s Troisprofilsdesession
x Composantsanstat y Sessionsanstat(StateLessSessionBean,SLSB) y Composantsractifs(MessageDrivenBean,MDB) x Sessionavectat,seulementRPC(StateFulSessionBean,SFSB)

2008,G.Sauthier

51

Cycledevievueduclientd'unEJB session(SLSBouSFSB)

2008,G.Sauthier

52

Vueclientd'uncomposantmtier EJB3.0
s Vueclientpourlescomposantsractifs
x APIJMS:publicationdemessagessurunequeueouuntopic x Formatdemessageaccordentreleclientetleserveur(APImtier)

s Vueclientpourlessessions(SLSBetSFSB)
x APIJavamtier y InterfaceJava y PasuneinterfaceRemote x Transparencedelamiseenrelation y Visvisdelarpartition y VisvisdutypedeRPC(RMIouWS)

s Injectiond'unedpendanceversunEJB
x Utilisationdel'annotation@EJB

2008,G.Sauthier

53

Cycledevied'uncomposantsans tat(SLSBouMDB)
s Allocationd'instances
x Allocationladiscrtiondu conteneur(pool) x Invocationdesintercepteurs PostConstruct/PreDestroy

s Utilisationd'instances
x Invocationdesmthodesmtiers y Mthodesdesinterfaces SLSB y Mthodesdesinterfaces messagelistener y Srialisationdel'excution garantieparleconteneur x Dfinitiond'chanciers(service timer)

2008,G.Sauthier

54

Cycledevied'unesessiontat (SFSB)

2008,G.Sauthier

55

Gestiondclarativedestransactions (containermanaged)
s Comportementassociauxmthodes
x Dmarcation==appeldemthode

s Comportementspossibles(requiredpardfaut)
x NotSupported:sitransactionactive,transactionsuspendue x Required:sipasdetransactionactive,nouvelletransaction x RequiresNew:nouvelletransaction(sitransactionactive, transactionsuspendueetractivelafindelanouvelle) x Mandatory:exceptionsipasdetransactionactive x Supports:rienfaire(sitransactionactive,l'utiliser) x Never:exceptionsitransactionactive

s SeulsRequiredetNotSupportedvalablespourles

composantsractifs
2008,G.Sauthier 56

Dfinitiondel'interfacedu composantsession SubscriptionBeanEJB2.1


public interface IEJB2Subscription extends EJBObject { void register(InfoParticipant participant) throws RemoteException; InfoParticipant infos(String name) throws RemoteException;

public interface IEJB2SubscriptionHome extends EJBHome { } IEJB2Subscription create() throws CreateException, RemoteException;

public class InfoParticipant { // Data Transfert Object (DTO) public String nom; public String address; } // ...

2008,G.Sauthier

57

Dfinitiondel'interfacedu composantsession SubscriptionBeanEJB3.0

@Remote public interface IEJB3Subscription { void register(InfoParticipant participant); InfoParticipant infos(String name); }

public class InfoParticipant { public String nom; public String address; } // ...

2008,G.Sauthier

58

Implmentationducomposant sessionSubscriptionBean EJB2.1


public class EJB2SubscriptionBean implements SessionBean { private ParticipantHome participantHome; public void ejbActivate() throws EJBException, RemoteException {} public void ejbPassivate() throws EJBException, RemoteException {} public void ejbRemove() throws EJBException, RemoteException {} public void setSessionContext(SessionContext arg0) throws EJBException, RemoteException { Object ph = new InitialContext().lookup("java:comp/env/ejb/Participant"); participantHome = PortableRemoteObject.narrow(ph, ParticipantHome.class); } public void register(InfoParticipant info) { Participant p = participantHome.create(info.nom, info.address); /* JMS publication: next slide */ } public InfoParticipant infos(String name) { Participant p = participantHome.findByPK(name); return p.getInfoParticipant(); } }
2008,G.Sauthier 59

Implmentationducomposant sessionSubscriptionBean EJB3.0


@PersistenceContext(name="persistence/DBSchool") @Stateless public class EJB3SubscriptionBean implements IEJB3Subscription { @Resource private SessionContext sc; @TransactionAttribute(TransactionAttributeType.REQUIRED) public void register(InfoParticipant info) { Participant p = new Participant(info.nom, info.address); EntityManager em = (EntityManager) sc.lookup("persistence/DBSchool"); em.persist(p); em.close(); // JMS publish: see MDB slides } public InfoParticipant infos(String name) { EntityManager em = (EntityManager) sc.lookup("persistence/DBSchool"); Query q = em.createQuery("SELECT OBJECT(i) from Subscription i WHERE i.nom = :pn"); q.setParameter("pn", name); Participant p = (Participant) q.getSingleResult(); InfoParticipant ip = p.getInfoParticipant(); em.close(); return ip; }
60

2008,G.Sauthier

Descriptionducomposantsession SubscriptionEJB2.1
<ejb-jar xmlns="http://java.sun.com/xml/ns/j2ee" version="2.1"> <display-name>ICAR Sessions</display-name> <enterprise-beans> <session> <ejb-name>Subscription</ejb-name> <home>org.school.api.IEJB2SubscriptionHome</home> <remote>org.school.api.IEJB2Subscription</remote> <ejb-class>org.school.lib.EJB2SubscriptionBean</ejb-class> <session-type>Stateless</session-type> <transaction-type>Container</transaction-type> <ejb-ref> <ejb-ref-name>ejb/Participant</ejb-ref-name> <ejb-ref-type>Entity</ejb-ref-type> <home>org.school.api.ParticipantHome</home> <remote>org.school.api.ParticipantHome</remote> <ejb-link>icar.jar#Participant</ejb-link> </ejb-ref> <resource-ref> <res-ref-name>jms/ConnFactory</res-ref-name> <res-type>javax.jms.TopicConnectionFactory</res-type> <res-auth>Container</res-auth> </resource-ref> . . .
2008,G.Sauthier 61

Descriptionducomposantsession SubscriptionEJB2.1

. . . <resource-env-ref> <resource-env-ref-name>jms/SubscriptionTopic</resource-env-ref-name> <resource-env-ref-type>javax.jms.Topic</resource-env-ref-type> </resource-env-ref> </session> </enterprise-beans> <assembly-descriptor> <container-transaction> <method> <ejb-name>Subscription</ejb-name> <method-name>register</method-name> </method> <trans-attribute>Required</trans-attribute> </container-transaction> </assembly-descriptor> </ejb-jar>

2008,G.Sauthier

62

Exempled'unepublicationde messagepartird'unSLSB

@Resource(name="jms/SubscriptionTopic", mappedName="SubscriptionTopic") private Topic topic; // In EJB 2.1: topic = (Topic) new InitialContext().lookup("java:comp/env/jms/SubscriptionTopic") // in register(InfoParticipant) TopicConnectionFactory tcf = null; TopicConnection tc = tcf.createTopicConnection(); TopicSession session = tc.createTopicSession(false, Session.AUTO_ACKNOWLEDGE); TopicPublisher tp = session.createPublisher(topic); MapMessage mm = session.createMapMessage(); mm.setString("participant.name", info.nom); tp.publish(mm);

2008,G.Sauthier

63

ExposerSubscriptionBean commeunWebService

@WebService(name="Subscription", wsdlLocation="META-INF/wsdl/subscription.wsdl", serviceName="SubscriptiopnService", portName="SubscriptionPort") @Stateless public class EJB3SubscriptionBean implements IEJB3Subscription { @Resource private SessionContext sc; @WebMethod @TransactionAttribute(TransactionAttributeType.REQUIRED) public void register(InfoParticipant info) { Participant p = new Participant(info.nom, info.address); EntityManager em = (EntityManager) sc.lookup("persistence/DBSchool"); em.persist(p); em.close(); }

2008,G.Sauthier

64

ExempledecomposantractifMDB
@MessageDriven(messageListenerInterface=MessageListener.class, mappedName="TopicIcar08") public class NewSubscriptionBean implements MessageListener { @Resource private String school = "Thematic School"; @Resource private String secretary = "school.secretary@myorg.fr"; @Resource private Session session; private InternetAddress[] addresses; @PostConstruct void init() { addresses = new InternetAddress[] {new InternetAddress(secretary)}; } public void onMessage(Message m) { MapMessage mm = (MapMessage) m; javax.mail.Message mail = new MimeMessage(session); mail.setRecipients(javax.mail.Message.RecipientType.TO, addresses); mail.setSubject("New subscription - " + school); mail.setContent("Participant name: " + mm.getString("participant.name"), "text/plain"); Transport.send(mail); }

2008,G.Sauthier

65

Supportdeschanciers1/2
s Dfinitiond'vnementstemporels
x chanceuniqueoupriodique x Dfinitionspersistantes

s Composantlessupportant
x SLSLetMDB x EJB2.1Entities

s vnementsapplicatifs
x Activationd'uneinstanceducomposant x Diffrentsdestimeoutassocisl'excutiond'instance particulires(vnementsfurtifs)

2008,G.Sauthier

66

Supportdeschanciers2/2
s Dfinitiond'unintercepteurd'chances
@Timeout public void process(Timer t) { // ... }

s Dfinitiond'unchancier

@Resource private TimerService timerService; // Fire timeout every hours starting from now timerService.createTimer(System.currentTimeMillis(), 3600000, "+1 heure");

2008,G.Sauthier

67

Composantsmtierspersistants (ConteneurJPA)

2008,G.Sauthier

68

Supportdel'tagedonnesmtiers
s StandardJPA1.0
x Partied'EJB3.0(JSR220) x CompatibleJavaSEetJavaEE x ProcheJDO(objectifetapproche)

s Donnesmtier:POJO
x Auchoixdel'utilisateurd'abstraire(oupas)l'accsau donnes/sessions x Pluttunproblmed'organisationdel'tagesession

s Cenesontpasdescomposants
x PascommelesEntitiesEJB2.1

s StandardisationdumappingObjet/Relationnel

2008,G.Sauthier

69

Modlesdepersistance
s Objetspersistants(entities)
x Instancesdeclassespersistantes x Renduspersistantsexplicitement(actionpersist) x Renduspersistantsparattachement(liendepropagation configurables) x Dtruitexplicitement(actionremove) x Dtruitparpropagation(cascadeconfigurable)

s APIdusystemedepersistence
x EntityManagerFactory:reprsenteunespacedepersistance(une BD) x EntityManager:reprsenteuncontexted'excution(unetransaction) x Query:reprsenteunerequteEJBQL(dfinitionetexcution) x EntityTransaction:reprsentelatransactionassocieun contexted'excution(mmesfonctionsqueUserTransaction)
2008,G.Sauthier 70

Modlesdedonnes
s Entit=ensembled'attributspersistants
x 2modesdedfinitiond'attributs y Field:simplevariabledeclasse y Property(JavaBeanlike):mthodessetteretgetter

s Typessupportspourlesattributs
x Typesprimitifs(etleurswrappers) x Rfrencesd'entities(relation?1) x Collectionderfrencesd'entities(relation?n)

s Supportdel'hritage s Supportdesclassesabstraites s Supportdesclassesincluses(liencomposite)

2008,G.Sauthier

71

Exemplesdeclassesentities

@Entity @Table(name="PARTICIPANT") public class Participant { @Id @GeneratedValue @Column(name="PID") private long id; @Basic private String name; @Embedded private Address address; @ManyToMany(mappedBy="participants") private Set<School> schools; }

@Entity @Table(name="SCHOOL") public class School { @Id @GeneratedValue private long id; @Embedded private Address place; @ManyToMany(cascade=CascadeType.PERSIST) @JoinTable(name="PARTICIP_SCHOOL", joinColumns={ @JoinColumn(referencedColumnName="id")}, inverseJoinColumns={ @JoinColumn(referencedColumnName="PID")}) private Set<Participant> participants; }

2008,G.Sauthier

72

Dfinitiondesunitsdepersistance

<persistence xmlns="http://java.sun.com/xml/ns/persistence" version="1.0"> <persistence-unit name="DataSchool" transaction-type="JTA"> <jta-data-source>jdbc_1</jta-data-source> <class>org.school.persistence.Address</class> <class>org.school.persistence.School</class> <class>org.school.persistence.Participant</class> <!-- . . . --> </persistence-unit> </persistence>

2008,G.Sauthier

73

Lesrequtes
s Requtesensemblistes
x Supportbased'EJBQLtendu x SupportderequtesSQLnatives(attentionlaportabilit)

s Requetesnommes
x Factorisationdedfinition x PasderecompilationEJBchaqueexcution

@NamedQuery(name="faithful", query="SELECT OBJECT(p) FROM Participant p, IN " + "(p.participations) e GROUP BY p HAVING COUNT(e) > :nbSchools") public class Participant { /* . . .*/ }

Query q = em.createNamedQuery("faithful"); q.setParameter("nbSchools", 1); List<Participant> p = q.getResultList();

2008,G.Sauthier

74

Future

2008,G.Sauthier

75

Future
s volutiondesspcifications
x EJB3.1: y Appelsdemthodeasynchrone y Singleton x JCA1.6: y RelchementdescontraintesdeClassLoader(visibilitdes librairies) x JPA2.0: y PriseencomptedesproblmesrelevsavecJPA1.0 x Servlet3.0: y Webframeworkpluggability+dynamicchanges y Asynchsupport

2008,G.Sauthier

76

Conclusion

2008,G.Sauthier

77

Conclusion
s Solutionindustrielleparmilesplusabouties
x Niveauxd'indpendance(HW,OS,DB,RPC,...) x Spectrefonctionneltrslarge

s Evolutiondesspcifications
x Maturationetstabilisation x Modlesdecomposants(nonhomogne) x Modlesdeprogrammationsimplifiantledveloppement(codeplus propre)

s Miseenoeuvre
x Environnementpuissantmaiscomplexe x Outildeproductivitpourutilisateursaguerris x Outillageimportant(Eclipse,NetBeans,IDEA)

2008,G.Sauthier

78

Questions/Rponses

2008,G.Sauthier

79