1 documents > j2se apis > j2ee apisj2se apisj2ee apis

250
1 Documents http://ltiwww.epfl.ch/ProgrammationI nternet > J2SE APIs > J2EE APIs http://ltiwww.epfl.ch/WebLang > Bibliographical references > Description of All Components

Upload: josette-carvalho

Post on 04-Apr-2015

115 views

Category:

Documents


2 download

TRANSCRIPT

Page 1: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

1

Documents

http://ltiwww.epfl.ch/ProgrammationInternet> J2SE APIs > J2EE APIs

http://ltiwww.epfl.ch/WebLang>  Bibliographical references> Description of All Components

Page 2: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

2

Applications Web

Page 3: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

3

JavaJavascript

JSPtaglib

XML

RMI

Struts

HTML

MDBean

Entity BeanServlet

Cookie

Visual Age

Eclipse

Tomcat

JBoss

ant

CVSWebsphere

Weblogic

php

.net

MySQL

JDOHybernate

J2EE

http://www.topjobs.ch/Rechercher: J2EE, PHP, Apache

JSF

Page 4: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

4

LAMP (pas présenté)

Browser

PHP<html> <head>  <title>Test PHP</title> </head> <body> <?php echo ‘Bonjour '; ?></body></html>

Network

ClientServer

DB

Linux, Apache, MySQL, PHP

Page 5: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

5

JBossTomcat

Application Web sur J2EE

EntityEJB

Browser EntityEJB

SessionEJB

x.htmlNetwork

Client

Server

DB

Servlet

proxy

proxy

proxy

Page 6: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

6

Pages HTML et Servlettes

Livre Software EngineeringSections 7.5, 7.7

Page 7: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

7

Page HTML

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>

    <head>

        <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>

        <title>Tests/test</title>

        <script type="text/javascript">

         function init() { // Javascript

             alert("Bonjour")

         }

       </script>

    </head>

    <body onload="init()">

Contenu de la page

    </body>

</html>

Page 8: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

8

Elements HTML

        <h1>Un grand titre</h1>

        <p>Un paragraphe</p>

        <table cellspacing="6" cellpadding="6" 

border="1" bgcolor="yellow">

            <tr>

                <td bgcolor="#FFE0E0">

ligne1 <br>

 colonne 1</td>

                <td bgcolor="#E0E0FF">

ligne1, colonne 2</td>

            </tr>

        </table>

Page 9: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

9

Elements actifs dans une form

        <form method="get" name="record" action="http://localhost:8080/xxxx">

            <input type="text" name="txInput1"/> <br>

            <input type="text" name="txInput2" value="initial"/>

            <input type="button" name="something" value="button"/>

            <input type="checkbox" name="checkB1" value="aaa"/>AAA

            <input type="checkbox" name="checkB2" value="bbb"/>BBB

            <input type="radio" name="radioB" value="ccc"/>CCC

            <input type="radio" name="radioB" value="ddd"/>DDD

Page 10: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

10

Sélections            <p>

                <select name="simpleSelection">

                    <option value="eee">EEE

                    </option>

                    <option value="fff">FFF

                    </option>

                </select>

            </p>

            <p>

                <select multiple name="multipleSelection">

                    <option value="hhh">HHH

                    </option>

                    <option value="jjj">JJJ

                    </option>

                </select>

            </p>

Page 11: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

11

Autres éléments            <p><input type="hidden" name="myValue" value="not_seen"/>            </p>            <p>                <textarea name="thetext" rows="8" cols="80">                    ha ! ha ! ha !                </textarea>            </p>            <p>                <button name="button" value="button" type="button"/> Click<br>                 <img width="100" src="green.gif“ alt="wow"> </button>            </p>            <p><input type="submit" name="button"/>  <input type="reset"/>            </p>        </form>

Page 12: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

12

Form

       <form method="get" name="record" action="http://localhost:8080/xxxx">

. . . elements des pages précédentes . . .

        </form>

Envoyé au serveur (une seule ligne)

http://localhost:8080/xxxx?txInput1=

&txInput2=initial

&simpleSelection=eee

&myValue=not_seen

&thetext=+++++ha+!+ha+!+ha+!%0D%0A++

&button=Envoyer

Page 13: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

13

Upload de fichiers

        <form method="post" name="upform" 

action="http://localhost:8080/check"

             enctype="multipart/form-data">

            <input type="file" name="uploading"/>

            <input type="submit"/>

        </form>

Page 14: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

14

HTML: Test.html

Tomcat, Apache . . .(serveur)

Browser(client)

Accès au serveur HTML

<A HREF="URL">link</a>

Internet

Page 15: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

15

Servlet

• Objet généralisé• Possède une méthode doGet• Est exécuté dans un serveur Web• Appelé par un browser

Browser ServletdoGet() { …}

Serveur Web

URL avec paramètres

Page 16: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

16

Servletqui lit les données entrées dans des champs

Bouton submit

Page 17: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

17

Formulaire HTML

<form action=“http://localhost:8080/test">

<input type=“submit” name=“add“>

<input type=“text” name=“val">

</form>

Page 18: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

18

Formulaire HTML

(Paragraphe 7.5.2)

<form action=“http://localhost:8080/test">

add: <input type=“submit” name=“add"> <p> val: <input type=“text” name=“val">

</form>

Page 19: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

19

HTML page

<form action="URL"> <input type = "text" name="field"></form>

servlet: Test.java

Serveur JBossBrowser

Appeler une servlette

Internet

page HTML

Exécutionde Java

Page 20: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

20

Servlette: traitement des données

public class Test extends HttpServlet {

public void doGet ( HttpServletRequest request,

HttpServletResponse response )

throws ServletException, IOException {

PrintWriter out = response.getWriter();

response.setContentType("text/html");

out.println ("<html><body>");

out.println ("<h1>Title</h1></body>");

}

} La page html est produite automatiquement quand la méthode se termine.

Javadoc J2EE

Page 22: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

22

Décodage d’un paramètre dans une servlette(voir J2EE Javadoc)

<input type = text name = "txtInp">

yyy

Servlette

<form action="http:www.epfl.ch/servletName//">

http://www.epfl.ch/servletName?txtInp=yyy

Page 23: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

23

Décodage d’un paramètre dans une servlette(voir J2EE Javadoc)

valueParam = request.getParameter("txtInp"); dans la servlette

valueParam.equals("yyy") Java

http://www.epfl.ch/servletName?txtInp=yyy

Navigateur

Page 24: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

24

Production du contenu d’une page HTMLpar une servlette

java.io.PrintWriter out = response.getWriter();

out.println(“<h1>Titre</h1>”);

Page 25: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

25

WebLang

Crée les sources des composants, les fichiers auxiliaires et les fichiers ant

Page 26: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

26

Fichier .cg

@@deploypath="C:/jboss-4.2.3.GA/server/default/deploy/"

servlet SomeServlet {

package servletPack;

public void someCall (PrintWriter out,

String name,

double number) {

out.println(name + " " + number);

}

}

http://ltiwww.epfl.ch/WebLang/Modules.html#servlets

Page 27: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

27

Module servlet en WebLang

servlet TestServlet {

package packageName;

int attribute; // dangereux

public void add ( PrintWriter out, int number) { attribute += number; out.println(attribute); }

public void sub (int number) {

attribute = number; }}

determine la form HTML

Page 28: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

28

WebLang génère les fichiers:

servlet: Test.java

doGet() { . . .}

m1(int a, String b) { ... } m2(String c, long d) { ... }

html: InputForms

<FORM action= "test">ab

m1

cb

m2

Page 29: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

29

Avec plus de détails

servlette: Test.java

doGet() { a = getParameters(“a”); m1(a, b); or m2(c, d); }

m1(int a, String b) { ... } m2(String c, long d) { ... }

html: InputForms

<form action= "test"> <input ... name="a"> <input ... name="b"> <submit name="m1"></form>

<form action= "test"> <input ... name="c"> <input ... name="b"> <submit name="m2"></form>

Page 30: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

30

Préparation et chargement d’une servlette

Serveur

web.xmlmyServlet.javamyPage.html

Navigateur

Eclipsefichier.cg CodeGenmyServlet.java@webdoGet() { }

xdoclet packagingweb.xml projet.ear

WebLang

Page 31: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

31

bouton droit de la souris

Compilation d’un fichier.cg

Page 32: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

32

Déploiement d’un projet

WebLang

Run As… > CGxdoclet.xml

Run As… > CGpackaging.xml

Page 33: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

33

Démarrer le serveur JBoss

http://ltiwww.epfl.ch/WebLang/JBossInit

Il est possible de gérer le serveur JBoss, ou d’autres serveurs à partir d’Eclipse. Les manipulations de préparation sont présentées ci-dessous.

Ces manipulations préparent en même temps les librairies nécessaires aux projets J2EE

Page 34: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

34

Nettoyer les programmes dans JBoss

Eliminez les programmes et structures laissés par l'étudiant précédent.

Pensez à le faire dans les leçons suivantes également !

1. Effacez les répertoires tmp, data, log et work qui se trouvent dans C:\jboss-4.2.3.GA\server\default

2. Effacez tous les fichiers se terminant par .ear (pour archive) ou .war se trouvant dans C:\jboss-4.2.3.GA\server\default\deploy

Pour arrêter JBoss, cliquer le carré rouge dans la fenêtre serveur et attendez qu’il se termine!

Page 35: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

35

Singleton (pour l’exercice)

public class BD { private static BD localBD = null;

public static BD getBD() {if (localBD==null) {

localBD = new BD();}return localBD;

}

private String name; // autres paramètres}

// utilisationBD.getBD().list();

Une seule instanciation, à la première utilisation.

Page 36: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

36

Définition d’une classe en WebLang

class MyClass { package aPackage; import java.util; access remote; // optional, default is local outputchannel myCh (queue, A); // future Bean bean; public void aMethod() throws Exception { System.out.println("a method called"); Bean b = beanHome.create(); // future b.method(); }}

Génère une classe habituelle et introduit les références et fonctions qui permettront de la charger dans le serveur.

Page 37: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

37

Affichage pour dépanner

System.out.print(“xxx”);

affiche ses sorties dans la console d’Eclipse

Page 38: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

38

Exercice 1: une application Web

Singleton

(à la place d’une base de données)

Servlet

store(String x)list()quit()

Page HTML

entrée

Servlet

login()cancel()

correct

nom incorrect

Page HTML

entrée

transition entre états

introduction de données

Page 39: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

39

Structure et scripts d’un projet JEE

Page 40: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

40

Structure d’un projet JEE

servlets

librairies JEE

fichier d’appel de tous les objets générés

fichiers d’appel des méthodes des servlets

JSP

définition des servlets

scripts ant de préparation

tout est génére à partir de ce fichier

Page 41: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

41

xDoclets

Outil standard pour créer une partie des fichiers indiqués dans les pages précé-dentes

http://xdoclet.sourceforge.net/xdoclet/index.html

Page 42: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

42

xDoclet crée le fichier web.xml

import javax.rmi.PortableRemoteObject; . . ./** * @web.servlet * name = "MyServletServlet" * display-name = "TestServlet" * description = "A simple Servlet" * @web.servlet-mapping * url-pattern = "/MyServlet" */public class TestServlet extends HttpServlet {

public void doGet (HttpServletRequest request, . . .

Page 43: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

43

Script ant pour appeler XDocletgénéré automatiquement par WebLang

<?xml version="1.0" encoding="UTF-8" ?> <project default="N2" name="XDoclet Generator">

<path id="xdoclet.classpath"><pathelement location="C:/jboss-4.0.4.GA/server/default/lib/javax.servlet.jar"/> <fileset dir="C:\eclipse\xdoclet_lib/">

<include name="*.jar" /> </fileset>

</path><target name="N2" description="Servlet/Taglib">

<taskdef classpathref="xdoclet.classpath“ classname="xdoclet.modules.web.WebDocletTask“

name="webdoclet" /> <webdoclet destDir="WEB-INF" verbose="true" mergeDir="WEB-INF/merge">

<fileset dir="src"> <include name="package/AServlet.java" /> </fileset> <deploymentdescriptor Servletspec="2.3" />

</webdoclet></target>

</project>

Page 44: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

44

<servlet> <servlet-name>MyServletServlet</servlet-name> <display-name>MyServlet</display-name> <description><![CDATA[A simple Servlet]]></description> <servlet-class>serv.MyServlet</servlet-class></servlet>

<servlet-mapping> <servlet-name>MyServletServlet</servlet-name> <url-pattern>/MyServlet</url-pattern></servlet-mapping>

<!-- look for "servlet-name" tutorial in Google! -->

Contenu de web.xml généré automatiquement par xdoclet

Page 45: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

45

CGPackaging.xml<!--********************WEB class*******************--> <target name="WEB" description="Lecon3.war"> <jar destfile="lib/Lecon3.war"> <zipfileset dir="WebContent/WEB-INF" prefix="WEB-INF"> <include name="*.xml"/> <include name="*.wsdd"/> </zipfileset> <zipfileset dir="WebContent/WEB-INF/lib" prefix="WEB-INF/lib" includes="**/*.jar"/> <zipfileset dir="bin" prefix="WEB-INF/classes"> <include name="applicationWeb/Login*.class"/> <include name="applicationWeb/Manage*.class"/> </zipfileset> <zipfileset dir="lib" prefix="WEB-INF/lib"> <include name="Lecon3-CL.jar"/> </zipfileset> <zipfileset dir="WebContent" prefix=""> <include name="appliWeb/Manager.jsp"/> </zipfileset> <zipfileset dir="WebContent" prefix=""> <include name="applicationWeb/Login.html"/> <include name="applicationWeb/Manage.html"/> </zipfileset> </jar></target>

Page 46: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

46

Session de client

(Paragraphe 7.8.5)

• Chaque client a une zone pour ses variables

• Lié à la session par les cookies• La servlette retrouve les variables de

l’appelant automatiquement

Page 47: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

47

Serveur

Objets de session dans des servlettes

Client 1(cookie)

Client 2(cookie)

Java bean

Client 2

Servlet

y = session.getAttribute("xx");

Java bean

Client 21

“xx”

“xx”

Page 48: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

48

Trouver les Java beans dans la session

public public void doGet ( HttpServletRequest request, HttpServletResponse response) {

HttpSession session = request.getSession();

MyObject myObject = new MyObject ();

session.setAttribute("myObject", myObject);

x = session.getAttribute("myObject");

. . .

Page 49: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

49

JSP: Java Server Page

(Section 7.8)

• JSP (exécuté sur le serveur)

≠ Javascript (exécuté dans le browser)

http://java.sun.com/products/jsp/docs.htmlvoir Servlets and JavaServer Pages: A Tutorial

Page 50: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

50

Comparaison servlettes - JSPs

public class Test extends HttpServlet {public void doGet (request, response) {

out.println ("<html><body>");out.println ("<h1>");out.println ( x.toString() );out.println ("</h1></body>");

} }

<html><body><h1><%= x.toString() %></h1></body

Servlette

JSP

Page 51: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

51

Création d’une JSP

JSP

( code )( + )( html )

htmlServlet

Java code

serveur browser

http://www.ch/xxxx.jsp

html

Servlet

Java source

JSP compilateur Java compilateur Exécution

Réseau

Page 52: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

52

<html><head><title>File</title></head><body><h1>Example</h1>

<%! declarations %><% code Java%>

Nouvelle valeur de l'attribut: <%= attribute %><p>

<form action="http://localhost:8080/Exercice3-WEB/File.jsp"> <input type="text" name="attribute"/> <input type="submit"/></form>

</body></html>

Exemple d’une page JSP

(Vue globale)

Page 53: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

53

<%! declarations %>

<!-- déclaration d’attributs Attention, le même objet servlette est partagé par tous les clients -->

Page JSP: déclaration

Page 54: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

54

Affichage d’une valeur de variable: <%= variable %>

Affichage du retour d’une méthode: <%= myClass.text() %>

<% // Java code out.println( "Text <p>" );%>

Page JSP: affichage

Page 55: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

55

Conditional statements

<% if (error!=null) { %>

<b>Error: <

%=error.message()%><b>

<% } %>

Page 56: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

56

Conditional statements(code généré)

if (error!=null) {

out.print(“<b>Error:”);

out.print(error.message();

}

Page 57: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

57

http://localhost:8080/Exercice3/File.jsp

URL d’une JSP

Page 58: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

58

<%@ pageimport="packName.*" %>

request, response et session sont définis par défaut dans une JSP

Autres instructions JSP

Page 59: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

59

Standard Tags JSP

jsp:include jsp:useBeanjsp:setProperty jsp:getProperty jsp:forward jsp:plugin

http://java.sun.com/products/jsp/docs.htmlVoir 2.0 PDF ou HTMLet Servlets and JavaServer Pages: A Tutorial

Page 60: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

60

<jsp:plugin type="applet"

code="package.HorlogeApplet"

width="370"

height="50">

</jsp:plugin>

Applet

Page 61: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

61

Session / Java bean<jsp:useBean id = "myForm"

scope = "session"class = "app.InputForm" />

<jsp:setProperty name = "myForm"property = "attribute"value ="<%= x %>" />

class InputForm { int attribute; // getter/setter créés au moyen d’Eclipse}

Page 62: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

62

Définition:<%@ taglib uri = "pack/myTag.tld" prefix = "tag"%>

Utilisation:

<tag:myTag/>

Utiliser un tag non standard

Page 63: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

63

package pack;

import java.io.IOException;

/**

* @jsp.tag

* name = "myTag"

* description = "A test class for tags"

*/

public class myTag extends TagSupport {

public int doStartTag() {

JspWriter out = pageContext.getOut();

out.println("I am a tag");

return 33;

} }

Classe tag Correspondante

Page 64: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

64

?xml version="1.0" encoding="UTF-8"?><!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN" "http://java.sun.com/dtd/web-jsptaglibrary_1_2.dtd">

<taglib> <tlib-version>1.0</tlib-version> <jsp-version>1.2</jsp-version> <short-name>xdoclet-build</short-name>

<tag> <name>myTag</name> <tag-class>pack.myTag</tag-class> <description><![CDATA[A test class for tags]]></description> </tag></taglib>

Créé par les xDocletsDescription d’un tag: MyTag.tld

Page 65: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

65

Où se retrouve le fichier JSP compilé en Java?

C:\jboss-4.0.0\server\default\work…

(n’est compilé que lorsqu’on l’appelle)

Page 66: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

66

Java beanpackage p;

public class Result implements Serializable {

public Result() { } // optionnel

int xxx;

public int getXxx() {

return xxx;

}

public void setXxx(int xxx) {

this.xxx = xxx;

}

}

Dans Eclipse:

sélectionner int xxx

clic-droit sur la sélection

Source > Generate Getter…

Page 67: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

67

Utilisation d’une session et d’un Java bean

Page HTML Servlet Page JSP Servlet

Java bean Java bean Java bean

sendRedirect

Session client (cookies)

Page 68: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

68

Java Bean

Résultat

Architecture de l’exercice 1

Page.jsp

Affichage résultat

Nouvelle entrée

Servlette.java

Calcul

Page 69: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

69

Même Page.jsp

Java bean

Résultat

Architecture de l’exercice 2

Page.jsp

Calcul +

Affichage résultat

Nouvelle entrée

Page.jsp

Calcul +

Affichage résultat

Nouvelle entrée

Page 70: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

70

Database access with the helpof persistent objects

EJB: Enterprise Java Beans

Page 71: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

71

Web Application (J2EE)

JBoss

Container

Container

Container

EntityEJB

Browser EntityEJB

SessionEJB

Tomcat

x.htmlNetwork

Client

Server

DB

Servlet

proxies

Page 72: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

72

Client-server Application (J2EE)

JBoss

Container

Container

Container

EntityEJB

Client

EntityEJB

SessionEJB

Network

Server

Client

DB

proxies

Page 73: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

73

CMP entity beans

(Container Managed Persistency)

BMP, Bean Managed Persistency will not be studied as there are better alternatives

Page 74: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

74

Specification of CMP entity

beans in WebLang

CMP bean: relations

methods

attributes

finders / creators

Page 75: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

75

Definition of an object in WebLang

cmpbean Town {package geo;String name; // DB attributesint numero;public void myMet (String s) {

System.out.println(s);}

// creators - finders}

Page 76: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

76

cmpbean Person { package beans; String firstName; String lastName; // attributes = DB columns int age; public Person createPerson ( String firstName, String lastName ); // age not initialised }// the arguments of the create must correspond // to the attributes. They are stored in the latter.

CMP Bean: method create

Page 77: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

77

Creation and use of an object in WebLang

Town t ;

Country c ;

t = townHome.create("Lausanne");

c = countryHome.create("Switzerland");

System.out.println( t.getName() );

c.setName( "Suisse" );

Page 78: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

78

CMP Bean: finder method

Town findByName (String s) {

query = "SELECT OBJECT(o) FROM Town o

WHERE o.name=?1"}

// more details later

Page 79: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

79

Find an object in WebLang

Town t ;

try {

t = townHome.findByName("Lausanne");

} catch (javax.ejb.FinderException fe) {

t = townHome.create("Lausanne");

}

System.out.println( t.getNumber() );

Page 80: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

80

Servlet using a beanservlet myservlet { package servlets;

public void newPerson ( PrintWriter out, String firstName, String lastName, int age)

throws Exception { Person aPers; aPers = personHome.createPerson (firstName, lastName);

aPers.setAge(age);}

} // it is a simple means to test CMP beans, an html // file that calls this servlet is created automatically

Page 81: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

81

Java Client (remote)jclient Ouf {

package clientPack;

public void method1 (String s1, String s2) {

Person aPers;

Course aCourse;

aPers = personHome.createPerson("a", s1);

aCourse = courseHome.createCourse("prof", s2);

}

}

// WebLang generates automatically a remote access

Page 82: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

82

Reading the HSQLDB database

http://localhost:8080/jmx-console

Select: service=Hypersonic (fifth line under jboss)

Select invoke (below startDatabaseManager)

Look at the task bar and let the DB window appear.

Click View/Refresh tree in this window

Examine the tables (Command > Select …)

Page 83: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

83

Fichiers auxiliaires des CMP entity beans

(générés par WebLang et par XDoclet)

Page 84: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

84

Files generatedby WebLang

and by the xDoclets

src/control

Game.java

GameCMP.java

GameLocalHome.java

GameLocal.java

GameHome.java

GameUtil.java

sources of the beans

interfaces of the proxies

Page 85: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

85

servlet

other EJB

Parts of a CMP entity bean

XxxxLocal userMethods

XxxxLocalHome

create findByPrimaryKey

EJBContainer

XxxxEntityBean

Xxxx

ejbCreate ejbPostCreate

ejbFindByPrimaryKey ejbLoad ejbStore

userMethods

Page 86: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

86

XxxxHomeProxy

create findByPrimaryKey

EJBXxxxObjectProxy

userMethods

Instantiation of a persistent object

client

servlet

bean

InitialContext lookup

EJBXxxxObjectProxy

userMethods

XxxxObjectProxy

userMethodsEJB

1

2

3

Page 87: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

87

Lookup to get a home proxy

TownLocalHomeProxy townLocalHomeProxy = null;

Context context = new InitialContext();

Object ref = context.lookup("store_PersonLocal");

townLocalHomeProxy = (TownLocalHomeProxy)

PortableRemoteObject.narrow (

ref, TownLocalHomeProxy.class

);

// narrow = cast from object to TownLocalHomeProxy

Page 88: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

88

Class specifying a CMP entity bean

package store.ejb;import javax.ejb.EntityBean;import javax.rmi.PortableRemoteObject;/** * @ejb.bean * name = "Customer" * display-name = "CMP Entity Bean" * description = "Description of the CMP Entity Bean" * view-type = "both" * type = "CMP" * primkey-field = "pk" * jndi-name = "store_CustomerRemote"  * local-jndi-name = "store_CustomerLocal" * @ejb.pk * class ="java.lang.Long" */public abstract class Customer implements EntityBean {

EntityContext entityContext; . . .

Page 89: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

89

CMP entity bean (primary key)

/** * Attribute Pk is used as primary key by default. * @ejb.persistent-field */public abstract java.lang.Long getPk();public abstract void setPk(java.lang.Long pk);/** * Default remove method * @throws RemoveException * @ejb.remove-method */public void ejbRemove() throws RemoveException { }

Page 90: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

90

CMP entity bean: Attributes/** * A pair of getter / setter for each attribute * * @ejb.persistent-field * @ejb.interface-method * view-type = "both" */ public abstract String getAtt() ; /** * @ejb.interface-method * view-type = "both" */public abstract void setAtt(String att) ;

Page 91: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

91

Control files generated by the xDoclets

META-INF

ejb-jar.xml

jboss.xml

jbosscmp-jdbc.xml

Page 92: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

92

Extrait de ejb-jar.xml

(src/META-INF)

<display-name>CMP Entity Bean</display-name>

<ejb-name>Patient</ejb-name>

<home>predimed.PatientHome</home>

<remote>predimed.Patient</remote>

<local-home> predimed.PatientLocalHome </local-home>

Page 93: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

93

Fichier.ear deploy

application.xml // références les fichiers ci-dessous

Fichier.jar // contient les EJBs

Fichier.war // contient les servlettes, passé à Tomat

<module><ejb>Test.jar</ejb>

</module><module> data/jboss-app/application.xml

<web><web-uri>Test.war</web-uri><context-root>/Test</context-root>

</web></module>

Fichier.ear

Page 94: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

94

Session beans(Pattern de façade)

Page 95: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

95

Collections gérées par une session bean

collection

JBoss

EntityEJB

Browser

EntityEJB

SessionEJB

Network

Client

Server

Servlet

proxiesproxies

proxies

EntityEJB

EntityEJB

Les collections (relations) doivent être gérées dans des session ou CMP beans

Page 96: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

96

Une session bean en WebLang

sbean ControllerSession {

package beans;

state Stateful; // optionnel

String st;

public ControllerSession create (String st);

public void newPerson (String firstName, String lastName, int age) throws Exception {

Person aPers;

aPers = personHome.createPerson(firstName, lastName, age);

}}

Page 97: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

97

Bean Managed Transactionsbean ControllerSession {

package beans; (Container managed transaction)

transaction Bean; // optionnel, par défaut une CMT est créée

state Stateful; // optionnel

String st;

public ControllerSession create (String st);

public void newPerson (String firstName, String lastName, int age) throws Exception {

Person aPers;

beanContext.getUserTransaction().begin(); // optionnel

aPers = personHome.createPerson(firstName, lastName, age);

beanContext.getUserTransaction().commit(); // abort() }}

Page 98: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

98

Relations entre CMP beans

Page 99: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

99

1:N Relation

23

4

8

5

23

23

23

WebLang, object view:cmpbean X { relation <hasY 1:N hasX> Y;}

X

Y

N

1

Page 100: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

100

1:1 Relation (bidirectionnelle)

23 423

WebLang:cmpbean X { relation <hasY 1:1 target hasX> Y;}cmpbean Y { relation <hasX 1:1 hasY> X;}

X Y

Page 101: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

101

N:M Relation

23 4

8

5

X Y27

24

424

827

823

523

Page 102: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

102

N:M Relation (toujours bidirectionnelle)

WebLang:cmpbean X { relation <possessesY N:M hasX> Y; …attributes…}

cmpbean Y { relation <hasX N:M possessesY> X; …attributes…}

Page 103: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

103

xdocletspour les relations

/** * Implementation of the relationship: getCollection * @ejb.interface-method * view-type = "local"  * @ejb.relation * name="Courses-Students-NM" * role-name="Courses-N-role" * target-ejb="Students" * target-role-name="Students-M-role" * target-multiple="yes" * @jboss.relation-mapping * style="relation-table" * @jboss.relation-table * table-name="CoursesXStudents" * @jboss.relation * related-pk-field = "pk" * fk-column="students_pk" * fk-constraints = "false" * @jboss.target-relation * related-pk-field = "pk" * fk-column = "courses_pk" * fk-constraints = "false" */ public abstract java.util.Collection getStudentsN();

Page 104: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

104

Operations concernant les relations entre beans

(WebLang)

Page 105: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

105

Relations utilisées dans les pages suivantes

cmpbean Country {

relation <hasCapital 1:1 isCapitalOf> Town;

relation <hasTown 1:N isLocatedIn> Town;

}

cmpbean Town {

relation <isCapitalOf 1:1 hasCapital> Country;

relation <isLocatedIn N:1 hasTown> Country;

}

Page 106: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

106

Utilisation d’une référence bidirectionnelle 1:1

Town t = townHome.create("Bern");

Country c = countryHome.create("Switzerland");

t.setIsLocatedIn(c);

System.out.println( t.getIsLocatedIn().getName() );

// setIsLocatedIn est automatiquement définie

quand on spécifie la relation isLocatedIn

Country-Capital

Page 107: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

107

Addition d’un élément à une relation

Town v ;

Country c ;

t = townHome.create("Lausanne");

c = countryHome.create("Switzerland");

t.setIsLocatedIn(c); // 1:1 side

t = townHome.create("Bern");

c.addHasTown(t); // 1:N side

Country (1) – Town (N)

Page 108: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

108

Déposer une relation et y accéder

Collection collection = aCountry.getHasTown();

Iterator it = collection.iterator();

while (it.hasNext()) { // Java 1.4

System.out.println(

( (Town) it.next() ) .getName() );}

Page 109: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

109

Déposer une relation et y accéder

Collection collection = aCountry.getHasTown();

for (Object o: collection) { // Java 1.6

System.out.println(

( (Town) o ) .getName() );}

Page 110: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

110

addHasTown est introduit par WebLang

void addHasTown(t) {

getHasTown().add(t);

}// standard add et remove de Collections// ajouté automatiquement par WebLang

removeHasTown(t) {

getHasTown().remove(t);

}

Les collections doivent être manipulées à l’intérieur de transactions

Page 111: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

111

Résumé des relations et de leurs méthodesindication

in Xxxx

Other end

in Yyyy

methods available

in Xxxx

<elemY 1:1 elemX> Yyyy no relation<elemX 1:1 target elemY> Xxxx

<collX 1:N elemY> Xxxx

Yyyy y = getElemX() setElemX(yyyy)

<elemY 1:1 target elX> Yyyy no relation<elX 1:1 elemY> Xxxx

Yyyy y = getElemY()setElemY(yyyy)

<collY 1:N elemY> Yyyy no relation<elemX N:1 collY> Xxxx

Collection y = getCollY()setCollY(collection)addCollY(yyyy), removeCollY(yyyy)

<collY N:M collX> Yyyy no relation<collX N:M collY> Xxxx

Collection y = getCollY()setCollY(collection)addCollY(yyyy), removeCollY(yyyy)

Page 112: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

112

Comparaisons entre objets

CB h1 = cBHome.create("5");

CB h2 = cBHome.findH("5");

if (h1 == h2) ; // pas valable !

if (h1.getPrimaryKey().equals(h2.getPrimaryKey()) System.out.println("2 x the same bean");

if ( ((Long)h1.getPrimaryKey()).intValue() ==

((Long)h2.getPrimaryKey()).intValue())

System.out.println("2 x the same bean");

Page 113: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

113

Finders

http://ltiwww.epfl.ch/~petitpie/ProgrammationInternet/ejb-2_1-fr-spec.pdf

(voir exemple du paragraphe 11.2.6.8)

Page 114: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

114

Finder retournant un objet( WebLang )

Course findCourse (java.lang.String name) {

query = "SELECT OBJECT(o)

FROM Course o

WHERE o.courseName=?1"

}

Page 115: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

115

Source d’un finder/** * Pays CMP Entity Bean * * @ejb.bean * name = "Pays" * display-name = "CMP Entity Bean" * description = "Description of the CMP Entity Bean" * view-type = "both" * type = "CMP" * primkey-field = "pk" * jndi-name = "geo_PaysRemote" * local-jndi-name = "geo_PaysLocal" * @ejb.pk * class ="java.lang.Long" * @ejb.finder * signature = "java.util.Collection findByVilleAvecM (java.lang.String s)" * query = "SELECT OBJECT (p) FROM Pays p, IN (p.contient) v WHERE v.nom LIKE CONCAT(?1, '%')" * @generated */public abstract class PaysBean implements EntityBean {

Page 116: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

116

Build/classes/META-INF/ejb-jar.xml . . .

<query>

<query-method>

<method-name>findVille</method-name>

<method-params>

<method-param>java.lang.String</method-param>

</method-params>

</query-method>

<ejb-ql><![CDATA[SELECT OBJECT(v) FROM Ville v

WHERE v.nom=?1]]>

</ejb-ql>

</query> . . .

Page 117: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

117

Tester si un objet existe en WebLang

Country c = null;

try {

c = countryHome.findByName("Switzerland");

} catch (javax.ejb.FinderException fe) {

c = countryHome.create("Switzerland");

}

Page 118: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

118

Finder retournant une collection

java.util.Collection findCourses () {

query = "SELECT OBJECT(o)

FROM Course o"

}

Note: les collections retournées par les finders peuvent être manipulées dans servlets.

(ici la table entière)

Page 119: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

119

Références cascadées 1:1

Option findOptionByProf (java.lang.String profName) {

query = "SELECT OBJECT(s)

FROM Option o

WHERE o.course.profName=?1"

}

// le finder doit être inclus dans le CMP bean

// qui définit l’objet retourné

Page 120: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

120

Relation 1:1 retournant une collectionde membres appartenant à la relation

public java.util.Collection findCountryByCapital

(java.lang.String capital) {

query = "SELECT c.capital

FROM Country c

WHERE c.capital.name LIKE

CONCAT('_', CONCAT(?1, '%‘)) "

}// On utilise une collection, parce qu’on suppose que // plusieurs beans peuvent correspondre au même critère

Page 121: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

121

Relation 1:N Country <contains 1:N isIn> Town

public java.util.Collection

findCountryByTownName (java.lang.String name) {

query = Country

"SELECT OBJECT(c)

FROM Country c, IN (c.contains) t

WHERE t.name=?1"

}

Page 122: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

122

Relations 1:N cascadées Country : contains Town : hasNb Number

public java.util.Collection findCountryByNumber

(int number, java.lang.String name) { 

query = "SELECT OBJECT(n)

FROM Country c,

IN (c.contains) t,

IN (t.hasNb) n

WHERE c.name = CONCAT("%", ?2)

AND n.value < ?1"

}

Page 123: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

123

Relations cascadées

A   1:1  B   1:1   C   1:1   D  -  dd

public A findAByX (java.lang.String name) {

query = "SELECT OBJECT (o)

FROM A o

WHERE o.b.c.d.dd=?1" 

}

Page 124: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

124

Relations cascadées

An  1:N  Bn   1:N   Cn   1:N Dn  -  dd

public java.util.Collection findA(java.lang.String name) {

query = "SELECT OBJECT (o)

FROM An o, IN(o.bnN) bx, IN(bx.cnN) cx, IN(cx.dnN) dx

WHERE dx.dd=?1"

}

Page 125: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

125

Relations en cascade

An  1:1  Bn   1:N   Cn   1:1 Dn  -  dd

public java.util.Collection findAn (java.lang.String name) { query = "SELECT OBJECT (o) FROM An o, IN(o.bn.cnN) cx WHERE cx.dn.dd=?1" }

// à introduire dans un bean An

(la query retourne un An)

Page 126: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

126

Relations en cascade

An  1:1  Bn   1:N   Cn   1:1 Dn  -  dd

public java.util.Collection findBn (java.lang.String s) { query = "SELECT o.bn FROM An o, IN(o.bn.cnN) cx WHERE o.aa=?1"}

// à introduire dans un bean Bn car il retourne une // collection de Bn

(la query retourne un Bn)

Page 127: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

127

Transactions

Page 128: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

128

Transactions dans les session beans

transaction Bean;

La transaction n’est pas gérée automatiquement,

le développeur doit insérer le code qui la gère.

Page 129: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

129

Relation N:M manipulée depuis une session bean

Cours EtudiantsN M

Expérience:

• Enregistrer un étudiant dans un cours

• Voir si l’étudiant est visible depuis le cours

Page 130: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

130

beanContext.getUserTransaction().begin();

s1.addCourse(c1); // s1, s2 are students and

s1.addCourse(c2); // c1,c2 courses

s1.addCourse(c3);

s2.addCourse(c3);

System.out.println("Additions terminées");

Thread.sleep(10000); // suspendue pendant 10 sec pour voir

// dans la base de données

for (Students s : c3.getStudentsN()) {

System.out.println("c3.collection"+s.getName());

}

beanContext.getUserTransaction().commit();

Page 131: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

131

CMP Bean A

CMP Bean B

Transaction présente avant d’entrer B

Transaction crée par le conteneur pour B

Transactions

Page 132: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

132

Dans le CMP bean (WebLang)

transaction RequiresNew;

Dans la méthode du CMP bean

beanContext.setRollbackOnly();

Page 133: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

133

Type de transaction

Transaction avant

l’exécution

Réaction

du conteneur

Required présente

aucune

est gardée

une nouvelle

RequiresNew présente

aucune

une nouvelle

une nouvelle

Mandatory présente

aucune

est gardée

erreur

Types de transaction

Page 134: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

134

Appels locaux/distants

• Les programmes situés sur des ordinateurs autres que le serveur peuvent accéder à une session beans ou une CMP entity beans de la même manière que les servlets ( mais par le biais de XxxRemoteHomeProxy )

• Il ne peuvent pas manipuler les relations des CMP beans(pour plusieurs raisons)

Page 135: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

135

Classes / jclients de WebLang• WebLang gèrent les home interfaces, les

entités CMP et les noms des classes des session beans de même que les input/output channels dans la plupart des modules

• En particulier dans les jclients et dans les classes.

Note: les classes doivent contenir l’indication access Remote; si elles ne sont pas dans le serveur.

Page 136: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

136

class or jclient Modulejclient Ouf {

package clientPack;

inputchannel varName (topic, "TopicName") { … }

void method1 (String s) {

Person aPers;

Course aCourse;

aPers = personHome.createPerson(s+"pers"); // CMP bean

aCourse = courseHome.createCourse(s+"course");

}

void method2 () {

List aList;

String str = "Text = "+listHome.create().text(); // session bean

System.out.println(str);

} }

Page 137: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

137

Struts

Page 138: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

138

Servlet ServletJSP JSP

PersonManagement SportManagement

person sport

personName

personForm

sportNamelocation

Basic structure of struts

sportForm

• The forms are saved in the HTTP session

• Under the name derived from the class !

Servlet Servlet

Page 139: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

139

Output of data (same for input)

Struts

sportForm.setLocation("xxx")

JSP

<bean:write name="sportForm" property="location"/>

<html:text name="location"/>

sportForm location

No direct connection !

Page 140: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

140

Servlet ServletJSP JSP

PersonManagement SportManagement

person sport

personName

personForm

sportNamelocation

2

1

3

Basic structure of struts

sportForm

• The forms are saved in the client session

• Under the name derived from the class !

Servlet Servlet

Page 141: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

141

/**

* @struts.form name="personForm"

*/

public final class PersonForm extends ActionForm {

private String name;

public String getName() {

return (this.name);

}

public void setName(String name) {

this.name = name;

}

} // ActionForm has code to fill in the form from the URL

1 Librairies Struts: Action Form ( = java bean )

Page 142: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

142

JSP: input.jsp

<h3>personForm.sportForm</h3>

<html:form action="/personManagement">

sportName <html:text property="name"/>

<html:submit/>

</html:form> // Plusieurs paramètres de l’action sont définis dans struts-config.xml

// en particulier une form est attribuée à cette action et name est le nom d’un

// champ de cette form

2 Librairie JSP pour Struts: HTML Form

Page 143: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

143

public final class PersonManagement extends Action {

PersonForm f;

public ActionForward execute (ActionMapping mapping, ActionForm form,

HttpServletRequest request, HttpServletResponse response) {

try {

f = (PersonForm) form;

f.getName();

return (mapping.findForward("sport"));

}

catch(Exception e) { // trap exceptions that may occur in your servlet

e.printStackTrace(); // you will get better error messages !

return (mapping.findForward("error"));

} } }

// L’action form passèe comme argument est automatiquement

// remplie à partir des arguments de l’URL

3 Struts: Action Servlet

Page 144: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

144

<action-mappings>

<action path="/personManagement" type="management.PersonManagement"  // servlet class name="personForm" // name in HTTP session scope="session" input="/pages/Error.jsp" unknown="false" validate="true" > <forward name="sport" // name that can be used as next page path="/pages/sport.jsp" redirect="false" /> </action><action-mappings>

(généré par xDoclet)Fichier auxiliaire: struts-config.xml

Page 145: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

145

Action Forms CMP Beans

PersonForm

Main

personForm[]

Person

Course

Person[]

finder ou getCollection

Recrée une collection et copie ses éléments dans l’autre collection

// code prochaine page

Action forms

CMP beans

Page 146: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

146

Action Forms CMP Beans

PersonForm

Main

personForm[] per

Person

Course

Person[] per

Pseudo-code

course.setPer( new ArrayList() )

for (each main.per[]) {

x = personHome.create(per[].attributes)

course.addPer(x)

}

PersonForm Person

Page 147: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

147

- Action forms,- arrays of action forms,- trees of action forms

Page 148: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

148

Action Action

In/out

Input

In/out

PersonManagement SportManagement

job

person

sport

personName

personName

personForm

jobNamelocation

sportForm[ ]

jobForm[ ]

jobForm[]

jobNamelocation

jobNamelocation

sportForm

Java beans composés

jobNamelocation

jobNamelocation

sportNamelocation

Pas supportéjobNamelocation

jobNamelocation

jobNamelocation

sportNamelocation

// Toutes les Action Form envoyées à // une action doivent avoir le même type

Page 149: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

149

/**

* @struts.form name="personForm"

*/

public final class PersonForm extends ActionForm {

. . .

private SportForm sportForm; // sub-form

public SportForm getSportForm () {

return (this.sportForm);

}

public void setSportForm (SportForm sportForm) {

this.sportForm = sportForm;

}

}

Tree of action forms

Page 150: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

150

( x[ ] or Collection or Set )

/**

* @struts.form name="personForm"

*/

public final class PersonForm extends ActionForm {

. . .

private Collection sportForms;

public Collection getSportForms () {

return (this.sportForms);

}

public void setSportForms (Collection sportForms) {

this.sportForms = sportForms;

}

}

Array of sub-action forms

Page 151: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

151

In the action servlet

f.getName();

In the JSP

<html:text property="name"/>

the form in which name is looked for is linked to the JSP by a definition introduced in struts-config.xml

Reference to an attribute of an Action Form

Page 152: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

152

In the action servlet

f.getSportForm().getName();

In the JSP

<html:text property="sportForm.name"/>

the form is linked to the JSP within struts-config.xml

Reference to an attribute of a Sub-Action Form

Page 153: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

153

In the action servlet (first element ! )

o = ((ArrayList) f.getSportForms();

name = ((SportForm) o.get(0)).getName();

// f is linked to the JSP in struts-config.xml

In the JSP

<html:text property="sportFormN[0].name"/>

// The element passed to the property can be // an ArrayList or an array such as String[]

Reference to an array of Sub-Action Forms

Page 154: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

154

Tags in the JSP and the Struts

<jsp:useBean id="managementForm"  scope="session" class="man.ManagementForm"/>

<bean:write name="managementForm" property="warning" filter="false"/> // prints the value of the property on the page

http://localhost:8080/struts-documentation

http://ltiwww.epfl.ch/WebLang/references.html

Page 155: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

155

HTML form in a JSP

<h3>PetForm</h3>

<html:form action="/Supplier_State_0_Action" >

<html:hidden name="petForm"property="<%= page_prop_token %>" value="<%= pageId %>" />

<table border=0><tr><tr><td> &nbsp; &nbsp; &nbsp; name &nbsp; &nbsp;

<td><html:text property="name"/><tr><td colspan=2 align=center><html:submit property="submit">submit</html:submit>

</table>

</html:form>

Page 156: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

156

Array in an HTML form

<html:form action="/Supplier_State_0_Action" ><html:hidden name="petForm"

property="<%= page_prop_token %>" value="<%= pageId %>" />

<table border="0" cellspacing="1"><tr><td> <table border="0" width="100%"><td>subName</table><td> <table border="0" width="100%"><td>number</table><td> <table border="0" width="100%"><td>check</table><tr><td> <table border="0" cellspacing="1"></table>

<!-- tableau transparent suivant

<tr><td colspan=10 align=center> <html:submit property="submit">submit</html:submit> </table></html:form>

Page 157: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

157

Iteration on the array (or collection)

<logic:iterate name="petForm"property="thingN"id="item1"indexId="index1">

<tr><td><table border="0" width="100%"<%=color[index1.intValue()%2]%>>

<td> &nbsp;<bean:write name="item1" property="subName"/></table>

<td><table border="0" width="100%"<%=color[index1.intValue()%2]%>>

<td><bean:write name="item1" property="number"/></table>

<td><table border="0" width="100%" <%=color[index1.intValue()%2]%>>

<td><html:checkbox property='<%="thingN["+index1.intValue()+"].check"%>'/></table>

</logic:iterate> cette valeur est retournée dans l’URL

Page 158: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

158

Internationalization (a.k.a. i18n)

• Properties defined in resources/application.properties resources/application_fr.properties

• Introduced in the JSPs by <bean:message key=“struts.page.form.text"/> (see the file for details)

• If the browser is set to French application_fr.properties is used

Page 159: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

159

Translation of the properties

Copy

resources/application.properties

to

resources/application_fr.properties

and edit the content of the new file

Page 160: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

160

Struts in WebLang

Architecture pour:

Machine à états finie

Gestion des pages

Page 161: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

161

Assurer une confirmation!

• L’utilisateur clique le bouton Confirm

• L’ordre est exécuté par le serveur

• L’utilisateur clique le bouton BACK du browser

• Il reclique Confirm erreur: double entrée

• Comment le serveur évite-t-il le doublon ?

Page 162: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

162

Eviter le doublon

• Chaque page contient un hidden field avec un numéro unique

• Avant de lire les paramètres de la page, on vérifie que le numéro est celui de la dernière page envoyée

• Cela implique un code homogène

Page 163: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

163

State Machine

• Login Register

• Fill a cart

• Confirm the cart

• Show the bill

• Confirm the order (only once)

Page 164: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

164

state == 1transition from state 1state = 2

JSP JSP

personName sportNamelocation

WebLang use of the JSPs and servlets

state == 2transition from state 2state = 1

State_2State_1

Page 165: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

165

FSM bean FSM beanJSP JSP

personName

sportNamelocation

Same bean,but different states

WebLang use of the JSPs and servlets

Where to start ? In the bean!

Page 166: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

166

Finite State Machine in a Struts

Struts

0

1

showBasket

notconfir-med

2

confirmed

OK

page_0

page_1

page_2

Page 167: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

167

struts PersonManagement {

package management;

stateMachine

state State_0 > person;

state State_1 > job;

. . . FSM . . .

page person {

personForm;

personForm.sportForm[ ];

personForm ("Comment", submitName) ;

}

}

WebLang Module : states and pages

Page 168: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

168

// Pure Java code

WebLang Module : Finite State Machine

stateMachine { state State_0 > supply; state State_1 > supplyConfirmation; switch (sessionState) { case State_S: sessionState = State_0; break; case State_0: Pet pet = petHome.create( petForm.getName() ); sessionState = State_1; break; case State_1: if (supplyConfirmation.getConfirmation()) sessionState = State_0; }}

Page 169: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

169

form SportForm { package fmPack; String sportName; int location);}form PersonForm { // sub-form package fmPack; String name ; JobForm jobForm; SportForm sportFormN [ ] ;} form JobForm { String jobName; int location;}

WebLang Module : Forms (Java beans)

Page 170: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

170

Different display formats

page SomePage {

petForm; // displays all the fields

petForm.thingN[ ];

petForm.bbb (MySubmit); // displays a MySubmit button

petForm.ccc (Cancel); // display a button

petForm.aaa (); // displays no button

}

Page 171: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

171

Struts JSP

struts Supplier { . . . page supply { petForm; petForm.thingN[ ]; } }form PetForm { package fp; String name; Thing thingN[];}form Thing { package fp; String subName, int number, boolean check;}

Page 172: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

172

Selection of the visible fields

page SomePage {

petForm () { readwrite nom; hidden age; }

petForm.thingN[ ];

petForm.bbb (MySubmit); }

Page 173: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

173

Selection of the visible fields

page SomePage {

petForm () ;

petForm2<PetForm> ()

petForm.thingN[ ];

petForm3<PetForm>.bbb (MySubmit); }

Page 174: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

174

Characteristics of the fields

hiddenmessagereadonlyreadwriteradio (aaa,bbb)combo (aaa,bbb) password

readonly radio (aaa,bbb) | readwrite | combo (aaa,bbb)

| password

// last lines: one of each group, e.g. readwrite radio

Page 175: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

175

Struts

browseForm.petForm[ ] (form)

basket.petFrom[ ] (form)

PetOrder status = ordered OrderItems* (CMP+CMR)

0

1

showBasket

notconfir-med

browser (JSP)

order-registered

(JSP)

showBasket (JSP)

2

confirmed

OK

Struts in WebLang

JSPs Action Servlet

Action Forms

CMP bean

Page 176: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

176

Administrator

Struts

Three tiers (overview)

browseForm.petForm[ ] (form)

basket.petFrom[ ] (form)

PetOrder status = ordered OrderItems* (CMP+CMR)

PetOrder status = awaitInvoice OrderItems* (CMP+CMR)

PetOrder status = toBeChecked OrderItems* (CMP+CMR)

file

OrderForm.petForm[ ]not accept

(form)

Buying

Struts

0

1

showBasket

notconfir-med

browser (JSP)

order-registered

(JSP)

showBasket (JSP)

2

SendSupplierPO

MDBean

0

select

login

confirmed

1confirmed

OK

areYouThe-Administrator

(JSP)

checkOrders (JSP)

Display Business Layer Database

+ Dataflow

DisplayBusiness Layer

Queue

Page 177: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

177

Struts

out print println

0

JSP

Prints in WebLang

print

In the Struts, WebLang automatically defines a stream named out, which contains methods

out.print(“xxx”); and out.println(“yyy”);

the text produced is automatically printed on the next JSP

1

Page 178: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

178

Sub-FSMs

02

1

displayapplicationenter

start

enter

display_francs

next

ignore

ignore

display_euros

previous

timeoutdisplayapplication

display

enter

start

ignore

timeout

Page 179: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

179

Sub-FSM

Struts A Struts B

State_0

State_S(start)

State_S(start)

State 0State_R(redirect)

1st return

1st call

subsequent calls

State_1

Goto B

Continue

State_1State_3

Goto B

Continue

State_3

Return

Continue

2nd return

State_R(redirect)

Page 180: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

180

Page_0

Introduirepersonnes/groupes

Lister/formergroupes

Nom groupe

Personnes

Page_2

nomP NomG v

Quitter

Entrer

Groupe

Personnes

Page_1

Quitter

EntrerGroupe

EntrerPersonne

EntrerGroupe

EntrerPersonne

Quitter

EntrerGroupe

EntrerPersonne

Page 181: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

181

JMS: Java Message Services

• Channels (queues, topics, durable topics)

• Message driven beans

• Architecture

Page 182: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

182

Server

queuetopic

Sender

Listener

SynReceiver

queue/topic

Message Driven Beanqueue, topic

MDBeanClients

Page 183: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

183

Types de canaux

QueuesEach message is rec-eived by a single client

TopicsEach client receives all messages

Durable Topics

Each client receives all messages, even if it is temporarily discon-nected

Requires (only in input)

subscription name

username, passwd

Page 184: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

184

Création de queues et topics

• Queolques queues et topics sont créés quand le serveur

JBoss est démarré: A, B, C, D, testTopic (lire les

informations imprimées quand JBoss démarre)

• La queue ou le topic d’un MDBean est créé à la création

du MDBean.

• On peut créer d’autres queues et topics en modifiant les

fichiers qui définissent l’environment de JBoss selon

http://ltiwww.epfl.ch/WebLang/JBossQueues.html

Page 185: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

185

Canaux disponibles dans WebLang:

• MDBeans (1 input / 0-n outputs)

• Servlets, (0-n outputs)JSPs, Struts

• CMP beans (0-n outputs)

• jclient, class (0-n inputs / 0-n outputs)

Page 186: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

186

Listener de queue / topic

queuetopicListener

Client

inputchannel ch {

}

Serveur

Object

operation1()operation2()

Needs C:\jboss-4.0.0\client\jbossall-client.jar

Page 187: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

187

Client

outputchannel ch {

}

Envoyer des messante à une queue ou un topic

queuetopicproxy

Server

Object

ch.send(message)

Page 188: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

188

jclient MyClient { // or class

package myPackage;

inputchannel inputName (topic, "MDBTopic") { String s = ((TextMessage)msg).getText());

varName.publish(msg);

}

outputchannel varName (topic, "testTopic");

public void method(String s) { . . . }

}

Module client ou classe en WebLang

Page 189: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

189

Listener généré par WebLang

public class alarmChListener implements javax.jms.MessageListener {

public void onMessage(javax.jms.Message msg) {

try {

System.out.print ((javax.jms.TextMessage)msg).getText();

} catch (Exception t) {

t.printStackTrace();

} } } Text specifié dans l’inputchannelText specifié dans l’inputchannel

Page 190: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

190

Lecture synchrone

// Lire la queue en mode synchrone

// (attente de 5 secondes au plus)

tmpQueue = (javax.jms.Queue) queueCtx.lookup("queue/C");

queueObj = queueSession.createReceiver(tmpQueue);

for (;;) {

Message msg = (Message) queueObj.receive(5000);

if (msg == null)

System.out.println("Timed out");

else

System.out.println(msg.getText());

}

Page 191: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

191

Message driven bean

Page 192: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

192

// executed when a message arrives

Module MDBean en WebLang

Pas de nom (à la diférence des autres)mdbean MyMDB {

package myPackage;

inputchannel (queue, "MDBQueue") {

String s = ((TextMessage) msg).getText());

varName.send(msg); }

outputchannel varName (queue, "B");

}

Page 193: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

193

servlet MyClient {

package myPackage;

// pas d’inputchannel possible !

outputchannel varName (queue, "A");

public void method(String s) {

TextMessage tm =

queueSession.createTextMessage(s);

varName.send(tm); } }

Module servlet en WebLang

Page 194: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

194

Proxy d’un topic

public void newTopicEnv(String name, String passwd)

throws Exception {

Object tmp = initCtx.lookup("UIL2ConnectionFactory");

TopicConnectionFactory tcf = (TopicConnectionFactory) tmp;

topicConn = tcf.createTopicConnection(name, passwd);

topicSession = topicConn.createTopicSession(

false, javax.jms.TopicSession.AUTO_ACKNOWLEDGE

);

topicConn.start(); }

(généré by WebLang, similaire pour les queues)

Page 195: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

195

Connexion à un topic

tmpTopic = (javax.jms.Topic) initCtx.lookup("topic/testTopic");

fromTopic = topicSession.createSubscriber(tmpTopic);

fromTopic.setMessageListener(new fromTopicListener());

(généré by WebLang)

Page 196: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

196

Exemples d’architecture

Page 197: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

197

Server

CMP beans(nom de partie)

Java client

Java client

Java client

topic

ServletBrowserInitialise le jeu game

Exemple d’environnement pour un jeu dans lequel un dé tourne parmis les joueurs (une fois qu’ils se sont enregistrés)

Page 198: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

198

GUI Listeners

actionPerformed() {

}

Business layer

FSM () {

}

Message Listener

onMessage () {

}

GUI

setUsername ()getUsername ()setPosition ()setError ()

topic

Java client

invokeLater

Page 199: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

199

Classes in WebLang

class Business {

package ppp;

outputchannel ch (topic, “testTopic”);

access Remote;

public Business(LoterieGUI gui) {

this();

this.gui = gui;

}

}

Page 200: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

200

La machine d’état est exécutéesur le thread du GUI et le sur le thread qui gère le topic

java.awt.EventQueue.invokeLater( new Runnable() { public void run() { // access to the GUI } });

Page 201: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

201

public void transition(String source) { try { switch (state) { case 0: if (source != "username") return; game = gameHome().findByName(gui.getGameName()); . . . state = 1; break; case 1: if (source != "nextmove") return; state = 2; break; case 2: if (source != "done") return; game.moveTerminated(); state = 1; } } catch (Exception e) { } }

Machine à états finie

Page 202: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

202

Web Services

• SOAPSimple Object Access Protocol ou Service Oriented Architecture ProtocolHTTP remote call

• SOAService oriented architecture

• WSDLWeb Services Description Language

• UDDIUniversal Description Discovery and Integration ( tombe dans l’oubli )

Page 203: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

203

Schéma d’un web service

Application(standalone)

stub

Application(sur serveur)

stub

Serveur

remote object== Java bean

Page 204: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

204

Documentation sur la création des Web Services

Help > Help Contents >

Documentation

Page 205: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

205Bottom Up: Java bean service

package web;public class Test {

public Person grow(Person p){p.setSize(p.getSize()+1);return p;

}}

. . .<wsdl:types> <schema elementFormDefault="qualified" <element name="grow"> <complexType> <sequence> <element name="p" type="impl:Person"/> </sequence> </complexType> </element> . . .

WSDL

Page 206: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

206

Web Services Description Language (WSDL)

<?xml version="1.0" encoding="UTF-8"?><wsdl:definitions targetNamespace="http://web" /" xmlns:wsdlsoap="http://schemas.xmlsoap.org/wsdl/soap/" <!--WSDL created by Apache Axis version: 1.3Built on Oct 05, 2005 (05:23:37 EDT)--> <wsdl:types> <schema elementFormDefault="qualified" <element name="grow"> <complexType> <sequence> <element name="p" type="impl:Person"/> </sequence> </complexType> </element> . . . <wsdl:port binding="impl:TestSoapBinding" name="Test"> <wsdlsoap:address location="http://

</wsdl:port> </wsdl:service></wsdl:definitions>

Page 207: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

207

Creation d’un Web Service

L’accès à une application est

fait au moyen de servlettes

développées dans le projet Axis

et qui appellent l’objet désigné

par l’utilisateur

Page 208: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

208

Test du service (après avoir compilé la classe)

• Service ExplorerWebContent/wsdl/Xxx.wsdl > right click > Web Services > Test with Web Services Explorer

• JSP de testclasse.java > right click > Web Services > Generate Sample JSPs

Page 209: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

209

Top Down: Java bean service

• WSDL file (par exemple sur une page WEB qui décrit le service)

• On obtient un squelette à compléter

Page 210: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

210

Web service en WebLang(seuls les types simples supportés)

webservice Simple {package xxx;public int add (int i, int j) {

return i+j;}

}

Page 211: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

211

Transfer of data

From an action form to a CMP bean

and vice-versa

Page 212: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

212

Action Forms CMP Beans

PersonForm

Main

resultFormN

Person

Course

personN

finder or getCollection

Recreates a collection and copies one into the other member by member

// code next page

Action forms

CMP beans

Page 213: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

213

Action Forms CMP Beans

String courseName = result.getCourseForm().getName(); // reads an action formjava.util.Collection<Person> coll = personHome.findPersonInCourse(courseName);

java.util.Collection<PersonForm> c = new ArrayList<PersonForm> ();

for (Person aPerson: coll) { // scan the collection of CMP beans PersonForm personF = new PersonForm(); personF.setFirstName(aPerson.getFirstName()); personF.setLastName(aPerson.getLastName()); c.add(personF); // creates the collection of action forms}result.setPersonFormN( c );

Page 214: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

214

Checking which submit has been clicked

If (submit.equals(“OK”)) { . . . }

page supply {          petForm.thingN [ ] (OK, Cancel)           readwrite name;      }  }

Page 215: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

215

Generated automatically WebLang

modules

• Lottery application implemented with Struts• Draw first a diagram with the html forms, the

action forms, the state machine and the database

CMP bean: Customer

namestruts: Lottery

- register(String) - login() - displayResults()

CMP bean: Token

number

Exercise

html: lottery

Start struts

Page 216: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

216

EJB - Hibernate 3

• Hibernate 3 allows the beans to be either attached to or detached from the database

• The beans can thus be used as action forms too, which avoids the tedious transfers from the beans to the action forms

• The version we will use is based on the @annotations introduced in Java 1.5

See the page WebLang about Hibernate

Page 217: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

217

Annotations (replace xDoclets)

/** * @struts.form name="jeton" */@Entitypublic class Jeton implements java.io.Serializable { . . .@Id(generate = GeneratorType.AUTO)public long getId() { return id;} . . . @ManyToOne public loterie.Client getClient() { return (client);}

Note: En WebLang, tous les ejb3 doivent se trouver

dans le même package

Page 218: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

218

WebLang module(same as cmpbean, but no finders, no creators: they are made in the user’s space)

ejb3 MyCountry { package myPackage; relations (Town=1:N); String name; int number; public Country(String name) throws Exception { this.name = name; } public String toString() { String str = "Country id=" + getId() + " name=" + getName(); java.util.Collection<Town> tlist = getTownN(); for (Town town: tlist) { str = str + "\n Town=" + town; } return (str); }}

Page 219: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

219

Configuration parameters

config {

deploypath = "C:/jboss-4.0.0/server/standard/deploy/";

hibernate_driver = "org.hsqldb.jdbcDriver";

hibernate_url = "jdbc:hsqldb:hsql://localhost:1701";

// for the JBoss database as prepared here

hibernate_username = "sa";

hibernate_password = "";

hibernate_dialect = "org.hibernate.dialect.HSQLDialect";

hibernate_dbauto = "create-drop"; // if present,

// recreates the tables at each restart

}

Page 220: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

220

Use of a Hibernate bean

javax.persistence.EntityManager em;

javax.persistence.EntityTransaction tx;

em = hibernate_utility.Manager.open();

tx = em.getTransaction();

tx.begin();

Country c = new Country("Switzerland");

em.persist(c);

c.setNumber(1291); // DB updated at commit

tx.commit(); // tx.commit() or tx.rollback();

hibernate_utility.Manager.close();

Page 221: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

221

Finding objects with Hibernate

javax.persistence.Query qt;

qt = em.createQuery( "select t from Town t where t.name=?");qt.setParameter(1, name);try {      town = (Town)qt.getSingleResult();} catch (javax.persistence.EntityNotFoundException enf) { town = new Town(name);       em.persist(town);}

Page 222: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

222

Finding lists of objects with Hibernate

javax.persistence.Query qt;

qt = em.createQuery("select t from Town t");

try {

townN = (Collection)qt.getResultList();

} catch (Exception e) {

// some error

}

Page 223: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

223

Using Hibernate objects (size() not written - lazy evaluation)

tx.begin();

. . .

proprietaire = qt.getSingleResult();

Collection c = proprietaire.getVoitureN(); // The elements of the

. . . // collection are retrieved only when needed

tx.commit();

for (Voiture v: proprietaire.getVoitureN()) {

out.println(v.getName()); // accessed outside the transaction}

09:22:28,774 INFO [STDOUT] org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: package.Proprietaire.voitureN, no session or session was closed

Page 224: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

224

Using the objects of a Hibernate relationship outside the transaction

tx.begin();

. . .

owner = qt.getSingleResult();

owner.getCarN().size();

. . .

tx.commit(); required to force the computation

(other functions may also be used)

for (Car c: owner.getCarN()) { otherwise not available

out.println(v.getName()); }

Owner Car

1 N

Page 225: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

225

Both Action form and Hibernate bean

ejb3 MyCountry

extends strutsStateMachine.StateForm {

package myPackage;

relations (Town=1:N);

String name;

int number;

}

Page 226: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

226

Create and Persist an Action Form

// town is assumed to be a form filled in by the user

      town.setId(0); // be sure it has not been left // attached by some previous action javax.persistence.EntityManager em; javax.persistence.EntityTransaction tx; em = hibernate_utility.Manager.open(); tx = em.getTransaction(); tx.begin();

      em.persist(town); tx.commit(); hibernate_utility.Manager.close();

}

Page 227: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

227

Transaction

store into the DB

Transaction

Transactions and display

get from the DB

display,let the user modify the

data

No transaction

Java bean

(ActionForm/EJB)

Must reconnect the bean to a transaction

Page 228: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

228

Reconnect an EJB3 to the DB

tx.begin(); // a first call to a servlet

em.persist(x);

tx.commit();

…Displaying…

tx.begin(); // a subsequent call

y = em.merge(x); // copy x to a new y

y.setName(“new value”); // and persists y

tx.commit();

Page 229: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

229

Handling a relationship

tx.begin();

em.persist(owner);

for (Car c: cars) {

em.persist(c)

owner.add(c);

c.setCar(owner); // indispensable to introduce it into the DB

} // because the reference is defined in table car

tx.commit();

Owner Car

1 N

Page 230: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

230

Merging a relationship(could be done by using cascade)

tx.begin(); x = em.merge(owner);

for (Car c: owner.getCarN()) { x.add(em.merge(c)); // reintroduce the merged } // objects into the new object owner = x; // optional: remettre l’objet dans son pointeur request.getSession().setAttribute(“owner”, owner); // et

tx.commit(); // dans la servlet-session

Owner Car

1 N

x : Owner c : Car

1 N

Page 231: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

231

SQL beans

• SQL beans have been devised at the EPFL: they present the same structure as Hibernate 3 (particularly within WebLang), but they only use JDBC and the standard SQL

• Much simpler to debug, as all statements may be traced within the debugger

• No home, the object must be created to hold the finder (instantiation by new)

Page 232: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

232

SQL Bean Example

sqlbean Town extends strutsStateMachine.StateForm { package appliT; relations ( Country = N:1, <isCapitalOf 1:1 hasCapital> Country); String name; public long findPK_OfTown() throws Exception {

query = "SELECT * FROM Town WHERE name=$name;" }}TownN { public void findN_TownList(String s) throws Exception {

query = "SELECT * FROM Town WHERE name>$s"}

Page 233: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

233

Use of an SQL bean

// we assume that country has been created // and filled by the Struts mechanism

case State_1:

long pkC = country.findPK_OfCountry();

if (pkC!=0) { country.reloadAll(pkC); } else { country.store(); } country.addTownN(town); // town.setCountry(country); // either this line or the line // above; the second one is

// called automatically

Page 234: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

234

FindersTownN tn = new TownN();

try { tn.findTownList(“N”);} catch (weblangUtils.SQLException we) { System.out.println(“Not found”);}

for (Town t: tn) { System.out.println(“t.getName());}

……………………………………………………………..

TownN { String name; public void findTownList (String s) throws Exception { query = "SELECT * FROM Town WHERE name>$s" }}

Page 235: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

235

Detached object

Attached object

pk!=0

Attached + linked + connected object

pk!=0 rel!=0

Linked object

pk==0

o.delete()

o.findXx()

o.store() o.set(null)o.remove(o1)

o.set(o1)o.add(o1)

o.set(null)o.remove(o1)

o.set(o1)o.add(o1)

o.reload(0)

o.reloadAll() o.storeAll()

o.deleteAll()

o.reload()o.reloadAll()o.update()o.updateAll()

o.delete()

o.store()

o.delete()

o = new Xxx()

FSM of the SQL beans

o.reload(pk)

pk=o.findPKXx()

Page 236: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

236

States of the SQL objects

Detached: The object has been instantiated

Attached: The object has a corresponding set of data in the database

Linked: The object is embedded in a structure, but it has no primary key

Attached, linked The object is available in the database, and connected: as well as in memory, within some

relationship

Page 237: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

237

Operations of the SQL beans

store Copies the data of the object into the database, new primary key inserted in the object

findXxx Query method returning a DB row, the objectmust be instantiated before the method is called

findPKXxx Returns the value of the primary key (or 0),method may also throw an exception

reload(pk) Method copies the data of the object into a DB row with primary key pk

update Dual of the reload, updates the database row that has the PK found in memory

Page 238: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

238

More Operations

delete Removes the data in the database, not the memory, resets the object’s primary key

set, add Establishes connections between

remove the objects, the two directions of the relationship are handled

storeAll Call all the objects bound by

deleteAll a relationship (not recursively)

reloadAll

updateAll

Page 239: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

239

RMI Application

ClientServer

Xxxx(stub)

RemoteXxxx

interfaceXxxx

Xxxx(skeleton)

interfaceXxxx

Page 240: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

240

RMI: inverse communication (by transmitting the stub)

Client Server

MyRemote(skeleton)

MyRemote(stub)

rmiregistry

Transfer(stub)

1

2

3

Transfer(skeleton)

myRemStub

Page 241: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

241

RMI Modulermi Test { package rmis; public void print (String s) { System.out.println("X "+s); }}

jclient Client { package rmis; Test x; // as Test corresponds to an rmi interface,

// x is automatically initialized RemoteTest y; // y is not automatically initialized, the client // must call new RemoteConnection(true) public void print (String s) { try { x.print(s); } catch (Exception e) { e.printStackTrace(); } }}

Page 242: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

242

Software Engineering

Page 243: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

243

Application / implementation

Craig: (http://www.codegeneration.net/tiki-read_article.php?articleId=27)

Specifying software means components, interfaces, archit-ectures, or what is sometimes referred to as the "How".

Specifying applications means features, capabilities, options, or what is sometimes referred to as the "What".

So, it seems odd to me (i.e., Craig ) to use UML (a "how" language) as a universal specification language.

Page 244: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

244

My View

Library

(Librarian, book shelves, quiet room)

Soft Library (simulator)

(terminals, server, software)

Each time a book is borrowed in the real library, the librarianborrows a book here

Software application

(terminals, server, software)

=

Borrow a book

Look for a user

A book has been lost

Check differences

Sort books

Reserve a book

Actually, you want to describe the software, the how. The customer can often not read any schema and will require a fast prototype, which is indeed the software.

Page 245: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

245

Administrator

Struts

Three tiers (overview)

browseForm.petForm[ ] (form)

basket.petFrom[ ] (form)

PetOrder status = ordered OrderItems* (CMP+CMR)

PetOrder status = awaitInvoice OrderItems* (CMP+CMR)

PetOrder status = toBeChecked OrderItems* (CMP+CMR)

file

OrderForm.petForm[ ]not accept

(form)

Buying

Struts

0

1

showBasket

notconfir-med

browser (JSP)

order-registered

(JSP)

showBasket (JSP)

2

SendSupplierPO

MDBean

0

select

login

confirmed

1confirmed

OK

areYouThe-Administrator

(JSP)

checkOrders (JSP)

Display Business Layer Database

+ Dataflow

DisplayBusiness Layer

Queue

Page 246: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

246

Exercise of Software Engineering (8)

• Creation of a stock exchange application.Customers are connected to the bank. The bank keeps a portfolio for each client, transmits the customer orders to the stock exchange. The stock exchange keeps an “order book” that contains the stocks that customers want to buy or sell, with the prices (or price range) they are willing to pay or get.

• Create a diagram that specifies a customer, a bank and a stock exchange, with CMP beans, queues, session beans…

• Create a diagram of the software system that will run the application, not of the application itself.

Page 247: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

247

Exercice:

• Compléter la loterie pour que le client voie une annonce quand le manager a sélectionné les jetons

• Créer les fonctions qui permettent d’entrer des jetons depuis le client Java (rich client)

Page 248: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

248

Client Serveur

cmpbean: Client

String nom

cmpbean: Jeton

int numero

attenteint etat gagnant

perdant

sbean: AccesJetons

- addJeton(Client, Jeton)

- listeResultats(Client)

1

N

html: display_Enregistrement

- enregistre(String)

- login(String)

html: display_Manager

- tireJetons(int)

servlet: Manager

- tireJetons(int)

- afficheJetons()

servlet: GestionJeton

- remplitJeton(int)

- afficheResultats()

servlet: Enregistrement

- enregistre(String)

- login(String)

html généré

Loterie

Java bean: LotteryData

- constantes générales

- client

html: display_GestionJeton

- remplitJeton(int)

- afficheResultats()

Page 249: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

249

Loterie

Browser

Serveur

cmpbean: Client

String nom

cmpbean: Jeton

int numero

attenteint etat gagnant

perdant

1

N

html: display_Manager

- tireJetons(int) servlet: Manager

- tireJetons(int)

- afficheJetons()

Java bean: LotteryData

- constantes générales

- client

Client

topic: testTopic

listener:class: LoterieGUI

(created with Visual Editor)

Page 250: 1 Documents   > J2SE APIs > J2EE APIsJ2SE APIsJ2EE APIs

250

Loterie

Browser

Serveur

cmpbean: Client

String nom

cmpbean: Jeton

int numero

attenteint etat gagnant

perdant

1

N

html: display_Manager

- tireJetons(int) servlet: Manager

- tireJetons(int)

- afficheJetons()

Java bean: LotteryData

- constantes générales

- client

Client

topic: testTopic

listener:

class: LoterieGUI

- display: TextArea

- login: TextField

- tireJeton: TextField

display(String)

class: Business

- login(String)

- tireJeton(int)

invokeLatersbean: ClientBean

- login(String)

- tireJeton(int)