Building Web Applications with Java - PowerPoint PPT Presentation

1 / 178
About This Presentation
Title:

Building Web Applications with Java

Description:

Building Web Applications with Java EPFL - Ecole Polytechnique F d rale de Lausanne (Swiss Federal Institute of Technology) Claude Petitpierre, Olivier Buchwalder ... – PowerPoint PPT presentation

Number of Views:802
Avg rating:3.0/5.0
Slides: 179
Provided by: Petitp5
Category:

less

Transcript and Presenter's Notes

Title: Building Web Applications with Java


1
Building Web Applications with Java
EPFL - Ecole Polytechnique Fédérale de
Lausanne (Swiss Federal Institute of
Technology) Claude Petitpierre, Olivier
Buchwalder, Paul-Louis Meylan
2
Web Applications
3
J2EE
php
Websphere Weblogic
CVS
Visual Age
.net
ant
RMI
Eclipse
JDO
Hybernate
Java
MySQL
Javascript
HTML
Entity Bean
Servlet
Cookie
JSP
JBoss
MDBean
Tomcat
taglib
XML
Struts
4
Web server (J2EE, JBoss)
  • Servlets, Struts
  • objects to access databases
  • Development environment
  • wizards
  • diagrams
  • WebLang (language developed at the EPFL)
  • Software engineering
  • geography (collaboration diagrams)
  • behavior (use cases, finite state machine)
  • data (class diagrams)

5
Precision
  • This course is about the application
    architecture, not the formatting of the pages,
    for which there are many specialized editors!

6
Content
Servlets 7 Javascript 118 JSP 23 Struts CMP beans
36 structure (MVC) 124 Relationships
Java beans 130 DB object views 54 JSP
(in-out) 138 operations 67
FSM 146 Finders 77 Data transfers 151 Transact
ions 90 Hibernate 3 155 Java client 98 SQL
beans 160 JMS 99 RMI modules 168 Architecture 110
Software Engineering 171
7
Calling an HTML Page
Tomcat, Apache (server)
Browser (client)
  • HTML Test.html

ltA HREF"URL"gtlinklt/agt
Internet
8
Servlet handle data entered in such fields
Submit button
9
Calling a Servlet
JBoss Server
Browser
servlet Test.java
HTML page ltA HREF"URL"gtlinklt/agt ltFORM
ACTION"URL"gt ltINPUT TYPE text
NAME"field"gt lt/FORMgt
Internet
HTML page
10
Structure of a Servlet
public class Test extends HttpServlet public
void doGet ( HttpServletRequest
request, HttpServletResponse response
) throws ServletException, IOException
response.setContentType("text/html") out.p
rintln ("lthtmlgtltbodygt") out.println
("lth1gtTitlelt/h1gtlt/bodygt")
Produces the html page automatically when the
method returns.
11
Retrieval of the parameter value within the
servlet(see J2EE Javadoc)
ltINPUT type text name "txtInp"gt in the
browser . . .
yyy
http//www.epfl.ch/servletName?txtInpyyy
String valueParam
in the servlet valueParam
request.getParameter("txtInp")
12
Loading a Servlet into Tomcat-JBoss
WEB-INF/jboss-web.xml WEB-INF/web.xml WEB-INF/clas
ses/packageName/MyServlet.class jar cf
Test-WEB.war WEB-INF In order to load the
servlet in the server, one must transfer the
Test-WEB.war into the deploy folder of Tomcat or
JBoss
13
Content of web.xml
ltservletgt ltservlet-namegtMyServletServletlt/se
rvlet-namegt ltdisplay-namegtMyServletlt/display
-namegt ltdescriptiongtlt!CDATAA simple
Servletgtlt/descriptiongt ltservlet-classgtserv
.MyServletlt/servlet-classgt lt/servletgt ltservlet-ma
ppinggt ltservlet-namegtMyServletServletlt/servl
et-namegt lturl-patterngt/MyServletlt/url-patter
ngt lt/servlet-mappinggt
14
Read by xDoclets to create web.xml
import javax.rmi.PortableRemoteObject
. . . / _at_web.servlet name
"MyServletServlet" display-name
"TestServlet" description "A simple
Servlet" _at_web.servlet-mapping
url-pattern "/MyServlet" / public class
TestServlet extends HttpServlet public void
doGet (HttpServletRequest request,
. . .
15
How to create all that stuff ?
  • WebSphere, JBossIDE, WebLogic, JBuilder based
    on wizards
  • Optimal-J, Arc Styler based on diagrams (MDA)
  • WebLang our simple programming language

16
What should a generator produce ?Here is our
choice
html InputForms ltFORM action "test"gt a b
m1 c b m2
servlet Test.java doGet() . .
. m1(int a, String b) ...
m2(String c, long d) ...
17
With more details
html InputForms ltFORM action "test"gt
ltINPUT ... name"a"gt ltINPUT ... name"b"gt
ltSUBMIT name"m1"gt lt/FORMgt ltFORM
action "test"gt ltINPUT ... name"c"gt
ltINPUT ... name"b"gt ltSUBMIT
name"m2"gt lt/FORMgt
servlet Test.java doGet() a
getParameters(a) m1(a, b) or
m2(c, d) m1(int a, String b) ...
m2(String c, long d) ...
18
Servlet Module in WebLang
servlet TestServlet package
packageName int attribute // delicate
public void add ( PrintWriter out, int
number) attribute number
out.println(attribute)
public void sub (int number)
attribute ? number
19
Output of the WebLang Compiler
Test.la
  • MyServlet.java (with the xdoclets
    (_at_web...)
  • xdoclet-build.xml
  • packaging-build.xml
  • README/MyServlet.html

20
(No Transcript)
21
Exercise 1
  • Create a servlet that returns the current date
    Client Server

servlet showDate show()
html showDate
Specify in a WebLang module
Automatically created by WebLang
22
Session Objectsin servlets
Client 2
Client 2
Serveur
action form 1
Client 1 (cookie)
action form 1
Servlet y session.getAttribute("xx")
action form 3
action form 4 xx
action form 1
Client 2 (cookie)
action form 1
action form 3
action form 4 xx
23
Session
public public void doGet (
HttpServletRequest request,
HttpServletResponse response) HttpSession
session request.getSession() MyForm myForm
new MyForm() session.setAttribute("myForm",
myForm ) session.getAttribute("someName") .
. .
24
JSP Java Server Page
(WebLang generates JSP on their own and as Struts
companion)
25
Use of a JSP
JSP compiler
Java compiler
Execution
JSP code html
Servlet Java code
Servlet Java source
server
browser
http//www.ch/xxxx.jsp
26
Example of a JSP page(details follow)
lthtmlgt ltheadgtlttitlegtFilelt/titlegtlt/headgt ltbodygt lth1
gtExamplelt/h1gt lt! declarations gt lt code
Java gt Nouvelle valeur de l'attribut lt
attribute gt ltpgt ltform action"http//localhost8
080/Exercice3-WEB/File.jsp"gt ltinput
type"text" name"attribute"/gt ltinput
type"submit"/gt lt/formgt lt/bodygt lt/htmlgt
27
Page JSP
lt! declarations gt lt--! Methods,
attributes Attention, a single servlet
object is shared by all clients --gt
28
Page JSP
Value of the attribute lt attribute gt lt
myClass.text() gt lt // Java code
out.println( "Text ltpgt" ) gt
29
URL of a JSP
ltform action"http//localhost8080/
Exercice3-WEB/File.jsp"gt ltinput
type"text" name"attribute"/gt ltinput
type"submit"/gt lt/formgt
30
Exercise 2
  • Create a JSP that display the date and has a link
    pointing to the same JSP Client
    Server

jsp jspDate lth1gtDatelt/h1gt lta href"This
JSP"gt Show date lt/agt
html jspDate See this link !
Specify in a JSP WebLang module
Automatically created by WebLang
31
JSP statement
lt_at_ pageimport"packName." gt
32
Applet
ltjspplugin type"applet"
code"package.HorlogeApplet"
width"370" height"50"gt lt/jspplugingt
33
Importing a tag
definition lt_at_ taglib uri "pack/myTag.tld"
prefix
"tag"gt use lttagmyTag/gt
34
Corresponding class tag
package pack import java.io.IOException /
_at_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 1
35
Description of a tag MyTag.tld
Created by the xDoclets
?xml version"1.0" encoding"UTF-8"?gt lt!DOCTYPE
taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP
Tag Library 1.2//EN" "http//java.sun.com/dtd/web
-jsptaglibrary_1_2.dtd"gt lttaglibgt
lttlib-versiongt1.0lt/tlib-versiongt
ltjsp-versiongt1.2lt/jsp-versiongt
ltshort-namegtxdoclet-buildlt/short-namegt
lttaggt ltnamegtmyTaglt/namegt
lttag-classgtpack.myTaglt/tag-classgt
ltdescriptiongtlt!CDATAA test class for
tagsgtlt/descriptiongt lt/taggt lt/taglibgt
36
Where is the compiled JSP file ?
C\jboss-4.0.0\server\standard\work
37
Database access with the helpof persistent
objects
EJB Enterprise Java Beans
38
Client-server Application (J2EE)
Server
JBoss
Container
Container
Client
Session EJB
Entity EJB
Client
proxies
DB
Container
Network
Entity EJB
39
Web Application (J2EE)
JBoss
Server
Container
Container
Entity EJB
Session EJB
DB
Client
Tomcat
Browser
Servlet
proxies
Container
Entity EJB
x.html
Network
40
CMP entity beans
(Container Managed Persistency) BMP, Bean
Managed Persistency will not be studied as there
are better alternatives
41
Files generatedby WebLang and by the xDoclets
src /control/ejb Game.java GameCMP.java /control/p
roxy GameLocalHomeProxy.java GameLocalObjectProxy.
java GameRemoteHomeProxy.java GameRemoteObjectProx
y.java
sources of the beans interfaces of the
proxies
42
Parts of a CMP entity bean
EJBContainer
servlet other EJB
XxxxLocalHomeProxy create
findByPrimaryKey
XxxxEntityBean
Xxxx ejbCreate ejbPostCreate
ejbFindByPrimaryKey ejbLoad
ejbStore userMethods
XxxxLocalObjectProxy userMethods
43
Instantiation of a persistent object
InitialContext lookup
XxxxHomeProxy create
findByPrimaryKey
client servlet bean
44
Lookup to get a home proxy
TownLocalHomeProxy townLocalHomeProxy
null Context context new InitialContext() Obj
ect ref context.lookup("store_PersonLocal") to
wnLocalHomeProxy (TownLocalHomeProxy)
PortableRemoteObject.narrow ( ref,
TownLocalHomeProxy.class ) // narrow cast
from object to TownLocalHomeProxy
45
CMP entity bean Attributes
/ A pair of getter / setter for each
attribute _at_ejb.persistent-field
_at_ejb.interface-method view-type "both
/ public abstract String getAtt() /
_at_ejb.interface-method view-type "both
/ public abstract void setAtt(String att)
46
CMP entity bean (beginning)
. . . / Attribute Pk is
used as primary key by default.
_at_ejb.persistent-field / public abstract
java.lang.Long getPk() public abstract void
setPk(java.lang.Long pk) / Default
remove method _at_throws RemoveException
_at_ejb.remove-method / public void ejbRemove()
throws RemoveException
47
Control files generated by the xDoclets
META-INF ejb-jar.xml jboss.xml jbosscmp-jdbc.xml
48
Class specifying a CMP entity bean(continuation)
package store.ejb import javax.ejb.EntityBean im
port javax.rmi.PortableRemoteObject /
_at_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"
_at_ejb.pk class "java.lang.Long"
/ public abstract class Customer implements
EntityBean EntityContext entityContext
. . .
49
Specification of CMP entity beans in WebLang
CMP bean attributes methods finders /
creators relations
50
Definition of an object in WebLang
cmpbean Town package geo String name
// DB attributes int numero public void myMet
(String s) System.out.println(s) //
creators - finders
51
CMP Bean method create
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.
52
CMP Bean finder method
Person findPerson () query
"SELECT OBJECT(o) FROM Course o WHERE
o.name?1" // more details later
53
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" )
54
Servlet using a bean
servlet myservlet package servlets
public void newPerson ( PrintWriter out,
String
firstName,
String lastName, int age)
throws Exception
Person aPers aPers
personHome.createPerson
(firstName, lastName, age) //
it is a simple means to test CMP beans, an html
// file that calls this servlet is created
automatically
55
Java Client (remote)
jclient Ouf package clientPack
public void method1 (String s1, String s1)
Person aPers Course aCourse
aPers personHome.createPerson("a",
s1) aCourse courseHome.createCourse
("prof", s2) // WebLang generates
automatically a remote access
56
Reading the HSQLDB database
http//localhost8080/jmx-console Select
serviceHypersonic (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 gt Select )
57
Exercise 3
  • Create a servlet that gets a town and a country,
    introduces each component in its table(the check
    to determine if an object already exists in the
    database will be performed in a subsequent
    exercise)

Generated automatically
html TownInCtr town country
WebLang modules
CMP bean Town name
servlet TownInCountry addTownCountry(
String t, String c )
submit
CMP bean Country name
58
Relations between CMP beans
59
An example of relation
Books title borrower (1) Borrower
name books (N)
60
Object / Database view
books local-PK title
borrower-PK
Borrowers local-PK name
1
N
3 Hans
4 Peter
7 Uli
12 Islands 7
15 Countries 4
11 Mountains 4
61
Person ? book
Hans
3
12 Islands 7
15 Countries 4
11 Mountains 4
Peter
4
Uli
7
Books of borrower ("Peter") SELECT Books. FROM
Books, Borrowers WHERE books.borrower_pk
borrowers.local_pk AND borrowers.namePeter
62
Book ? person
Hans
3
12 Islands 7
15 Countries 4
11 Mountains 4
Peter
4
Uli
7
Borrower of book("Countries") SELECT
Borrowers.name FROM Borrowers, Books
WHERE borrowers.local_pk books.borrower_pk
AND books.title countries returns the
borrower
63
1N Relation
Y
4
23
X
N
23
8
23
1
5
WebLang cmpbean X relations (Y 1N)
23
64
11 Relation (bidirectional)
Y
X
23
4
23
WebLang cmpbean X relations (Y 11
target) cmpbean Y relations (X
11)
65
NM Relation
23
4
27
X
8
Y
24
5
23
5
8
23
8
27
4
24
66
NM Relation (bidirectional)
WebLang cmpbean X relations (Y NM)
attributes cmpbean Y relations (X
NM) attributes
67
Object View
Books local-PK title
borrower-PK
EJB Books abstract getPk() abstract
setPk(pk) abstract getTitle() abstract
setTitle(title) abstract getBorrower()
// relation 11 abstract
setBorrower(borrower)
68
Object View
Borrowers local-PK name
EJB Borrowers abstract getPk() abstract
setPk(pk) abstract getName() abstract
setName(name) abstract getBooksN()
// 1N relation abstract
setBooksN(booksN) abstract add(book)
// added by WebLang abstract remove(book)
69
xdocletsof the relationships
/ Implementation of the relationship
getCollection _at_ejb.interface-method
view-type "local"  _at_ejb.relation
name"Courses-Students-NM"
role-name"Courses-N-role"
target-ejb"Students"
target-role-name"Students-M-role"
target-multiple"yes" _at_jboss.relation-mapping
style"relation-table"
_at_jboss.relation-table table-name"Courses
XStudents" _at_jboss.relation
related-pk-field "pk"
fk-column"students_pk" fk-constraints
"false" _at_jboss.target-relation
related-pk-field "pk" fk-column
"courses_pk" fk-constraints "false"
/ public abstract java.util.Collection
getStudentsN()
70
Operations concerning the relationships between
beans
(WebLang)
71
Relationships used in the following pages
cmpbean Country relations (Capital11,
Town1N) cmpbean Capital relations
(Country11) cmpbean Town relations
(Country11)
72
Handling of a 11 bidirectional reference
Country-Capital
Capital t capitalHome.create("Bern") Country
c countryHome.create("Switzerland") t.setCountr
y(p) System.out.println( c.getCapital().getName()
)
// setCountry is automatically defined when one
specifies (Country11)
73
Addition of an element to a relationship
Country (1) Town (N)
Town v Country p t townHome.create("Lausanne
") c countryHome.create("Switzerland") t.setCo
untry(c) // 11 side t
townHome.create("Bern") c.addTown(t)
// 1N side
74
Storing a relationship and accessing it
Collection collection aCountry.getTownN() Itera
tor it collection.iterator() while
(it.hasNext()) // Java 1.4
System.out.println( ( (Town)
it.next() ) .getName() )
75
addTown is introduced by WebLang
void addTown(v) getTownN().add(p)
// standard add and remove of Collection//
added automatically by WebLang removeTown(t)
getTownN().remove(t) // the collections
must be handled within a transaction
76
Summary of the relationships and their methods
indication in Xxxx Other end in Yyyy methods available in Xxxx
Yyyy 11 no relationXxxx 11Xxxx 11 targetXxxx 1N Yyyy y getYyyy() setYyyy(yyyy)
Yyyy 11 target no relationXxxx 11Xxxx 11 target Yyyy y getYyyy() setYyyy(yyyy)
Yyyy 1N no relationXxxx 11 java.util.Collection y getYyyyN()setYyyyN(collection)addYyyy(yyyy), removeYyyy(yyyy)
Yyyy NM no relationXxxx NM java.util.Collection y getYyyyN()setYyyyN(collection)addYyyy(yyyy), removeYyyy(yyyy)
77
Comparisons between objects
CB h1 cBHome.create("5") CB h2
cBHome.findH("5") if (h1.isIdentical(h2))
System.out.println("2 x the same bean") if (h1
h2) // does not work ! 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")
78
Advices
Before starting JBoss, clear the database, by
deleting c\jboss-4.0.0\server\standard\dat
a c\jboss-4.0.0\server\standard\tmp
c\jboss-4.0.0\server\standard\work As well as
the files .ear in c\jboss-4.0.0\server\sta
ndard\deploy
79
Exercise 4
  • Create a servlet that gets a town and a country,
    introduces each component in its table (no
    checks)and establish a relationship between them

WebLang modules
CMP bean Town name
servlet TownInCountry addTownCountry(
String t, String c )
N
1
CMP bean Country name
80
Finders
http//ltiwww.epfl.ch/petitp/ProgrammationInterne
t/Lecon_CMP/ejb-2_1-fr-spec.pdf (voir example
du paragraphe 11.2.6.8)
81
Finder returning an object( WebLang )
Course findCourse (java.lang.String name)
query "SELECT OBJECT(o)
FROM Course o
WHERE o.courseName?1"
82
Checking if an object exists in WebLang
Country c null try c countryHome.findByNam
e("Switzerland") catch (javax.ejb.FinderExcepti
on fe) c countryHome.create(" Switzerland
")
83
Finder returning a collection
(here the whole table)
java.util.Collection findCourses ()
query "SELECT OBJECT(o)
FROM Course o" Note the collections must
be handled either in the CMP entity beans, or in
the sessions beans, not directly in the servlets.
84
Cascaded 11 references
Option findOptionByProf (java.lang.String
profName) query "SELECT OBJECT(s)
FROM Option o
WHERE o.course.profName?1"
// the finder must be located in the CMP bean
// that defines the returned object
85
11 relation returning a collectionof members
belonging to a relation
public java.util.Collection findRoomByCourseName

(java.lang.String CourseName) query
"SELECT c.room FROM
CourseDescriptions c WHERE
c.course_name ?1
AND c.room.number LIKE '5' "
// If several beans may correspond to the same
criteria
86
1N Relation
public java.util.Collection
findStudentByCourseName (java.lang.String name)
query "SELECT OBJECT(s)
FROM Students s, IN (s.courseDescriptionsN) ca
WHERE ca.course_name?1"
!
87
Cascaded 1N relations
public java.util.Collection findGradeByCourseGrade
(int
courseGrade, java.lang.String name)  
query "SELECT OBJECT(g)
FROM Students s, IN
(s.courseDescriptionsN) a,
IN (a.gradesN) g WHERE
a.course_name ?2 AND g.grade lt ?1"
88
Cascaded Relations
A   11  B   11   C   11   D
 -  dd public A findAByX (java.lang.String
name) query "SELECT OBJECT (o)
FROM A o WHERE
o.b.c.d.dd?1" 
89
Cascaded Relations
An  1N  Bn   1N   Cn   1N 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"
90
Cascaded Relations
(the query returns an An)
An  11  Bn   1N   Cn   11 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" // to be stored in bean An
91
Cascade Relations
(the query returns an Bn)
An  11  Bn   1N   Cn   11 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" // to
be stored in bean Bn as it returns a collection
of Bn
92
Exercise 5
  • Same as before, but check that the country does
    not already exist
  • and print the list of towns within a given
    country
  • (both checks use a finder)

WebLang modules
CMP bean Town name
servlet TownInCountry addTownCountry(
String t, String c )
N
1
CMP bean Country name
93
Transactions
94
Transactions in the session beans
transaction Bean The transaction is not handled
automatically. It can be used to handle the
collections.
95
NM Relation handled in a session bean
Courses
Students
N
M
  • Experience
  • Register a student in a course
  • See if the student is known from the course

96
beanContext.getUserTransaction().begin() s1.getCo
ursesN().add(c1)
// s1, s2 are students and s1.getCoursesN().ad
d(c2)
// c1,c2 courses s1.getCoursesN().add(c3)
s2.getCoursesN().add(c3) System.out.println("Add
itions terminées") Thread.sleep(10000)
// sleep for 10 seconds to allow
peering
//
into the database Iterator it
c3.getStudentsN().iterator() while
(it.hasNext()) Students s (Students)
it.next() System.out.println("c3.colle
ction"s.getName()) beanContext.getUserTransact
ion().commit()
97
Transactions
CMP Bean A
Transaction available before entering B
CMP Bean B
Transaction created by the container for B
98
In the CMP bean (WebLang) transaction
RequiresNew In the methods of the CMP bean
beanContext.setRollbackOnly()
99
Transaction types
Transaction type Transaction available before the execution Reaction of the container
Required available none keeps it starts a new one
RequiresNew available none starts a new one starts a new one
Mandatory available none keeps it error
100
Java Clients
  • External programs can access the session beans in
    the same way as the servlets
  • They can access the CMP beans, but not manage
    their relationships (the collections must be
    handled within transactions)

101
jclient Module
jclient Ouf package clientPack void method1
(String s) Person aPers Course aCourse
aPers personHome.createPerson(s"pers") aC
ourse courseHome.createCourse(s"course")
void method2 () List aList String str
"Text "listHome.create().text() // session
bean System.out.println(str)
102
JMS Java Message Services
  • Channels (queues, topics, durable topics)
  • Message driven beans
  • Architecture

103
Message Driven Beanqueue, topic
Server
Clients
Sender
queue/topic
MDBean
Receiver
queue topic
SynReceiver
If the MDBean reads a topic, it must write to a
topic. Similarly for the queues (?).
104
Types of channels
Queues Each message by a single client
Topics Each client receives all messages
Durable Topics Each client receives all messages, even if it is temporarily disconnected Only in input, requires subscription name username, passwd
105
Creation of queues and topics
  • A few queues and topics are created when the
    JBoss serv er is started A, B, C, D, testTopic
    (read the information printed when JBoss starts)
  • The queue or the topic of an MDBean is created at
    the creation of theMDBean.
  • One may create other queues and topics by
    modifying the files controlling the environment
    of JBoss according to http//ltiwww.epfl.ch/WebLan
    g/JBossQueues.html
  • One can also create them dynamically according to
    http//ltiwww.epfl.ch/olivier/jmx.html

106
Channels available in WebLang
  • MDBeans (1 input / 0-n outputs)
    no other entry call possible
  • Servlets, (0-n outputs)JSPs, Struts
  • CMP beans (0-n outputs)
  • clients (0-n inputs / 0-n outputs)

107
Module MDBean in WebLang
No name (unlike the other ones)
mdbean MyMDB package myPackage
inputchannel (queue, "MDBQueue")
String s ((TextMessage) msg).getText())
varName.send(msg) outputchannel
varName (queue, "B")
108
Module client en WebLang
jclient MyClient package myPackage
inputchannel inputName (topic, "MDBTopic")
String s ((TextMessage)msg).getText())
varName.publish(msg)
outputchannel varName (topic, "testTopic")
public void method(String s) . . .
109
Synchronous reading
// Read the queue in a synchronous manner //
(at most 5 seconds waiting) for ()
Message msg (Message)
inputName.receive(5000) if (msg null)
System.out.println("Timed out")
else System.out.println(msg.getText())

110
Module servlet en WebLang
servlet MyClient package myPackage
// pas dinputchannel ! outputchannel
varName (queue, "A") public void
method(String s) TextMessage tm
queueSession.createTextM
essage(s) varName.send(tm)

111
Connection to a topic
(generated by WebLang)
public void newTopicEnv(String name, String
passwd)
throws Exception
Object tmp initCtx.lookup("UIL2ConnectionFactor
y") TopicConnectionFactory tcf
(TopicConnectionFactory) tmp topicConn
tcf.createTopicConnection(name,
passwd) topicSession topicConn.createTopicSess
ion( false, javax.jms.TopicSession.AUTO_ACKNOWLE
DGE ) topicConn.start()
112
Connection to a topic
(generated by WebLang)
tmpTopic (javax.jms.Topic) initCtx.lookup("topi
c/testTopic") fromTopic topicSession.createSub
scriber(tmpTopic) fromTopic.setMessageListener(n
ew fromTopicListener())
113
Architecture Example
114
Example
paper scissors - stone
topic
Player 1
Player 2
  • One uses a topic, so that the two players do not
    need to address different queues (same source)
  • One receives thus the choice of the other and
    ones own choice

115
Distinction between the two returned choices
  • If one receives a message different from ones
    own choice, it is the others message
  • If one receives a message equal to ones own
    choice, it may be ones own choice or the others
    choice, but it is then not necessary to know
    which one it is !

116
Java client
GUI setUsername () getUsername () setPosition
() setError ()
topic
GUI Listeners actionPerformed()
Message Listener onMessage ()
Business layer FSM ()
117
Finite State Machine
public synchronized 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)

118
The FSM is shared
  • synchronized java.awt.EventQueue.invokeLater(
    new Runnable() public void run()
    // handling of the GUI
    ) // the direct access to the GUI is delicate

119
Automaton of the example
0 0
My choice has been sent
His choice received
Message received (his/my choice)
My choice sent
x y
Message received (his/my choice)
My choice received
The messages I have received I have sent my
choice
See following slides!
120
Exercise 6
  • Create a game environment in which a die runs
    among all players (once they have registered
    themselves in the match)


Server
Browser
Servlet
CMP beans (match name)
Java client
Java client
topic
Java client
121
Javascript
  • Similar, but different from Java
  • Interpreted in the browser (not a servlet)
  • Image animation
  • Checking data input
  • Allows each element to become a submit

122
Use of an event
  • ltBODY onLoad"someFunction()"gt
  • ltINPUT TYPE button
    onClick'alert("HELP,HELP !")'
  • gt
  • quotes and apostrophes
  • (could be swapped)

123
Conditional Submit
ltFORM NAME "record" ACTION
"http//ltisun.epfl.ch8080/xxx" onSubmit
"return confirm ('Really submit?')"gt
Open dialog box
Important
124
Every element may call a submit
ltSCRIPTgt var i0 function
key(j) forms0.submit() // values passed
within // text or
hidden fields lt/SCRIPTgt ltIMG SRC "im2.jpg"
width 50px onClick
"key(2)"gt
125
Hidden fields
  • ltINPUT TYPE "hidden"
  • NAME "myValue" 
  • VALUE "notSeen"
  • gt
  • document.forms0.myValue.value "coucou"
  • // value returned to the servlet, if placed
    within an HTML form

126
Events
onClick the user clicks on form element or
link onChange the user changes value of text,
text area, or select element onFocus the user
gives form element input focus onBlur the user
removes input focus from form element onMouseOver
the user moves mouse pointer over a link or
anchor onMouseOut the user moves mouse pointer
off of link or anchor onSelect the user selects
form element's input field onSubmit the user
submits a form onResize the user resizes the
browser window onLoad the user loads the page in
the Navigator (must be placed in
the BODY command) onUnload the user exits the
page (must be placed in the BODY command)
127
Struts
128
Basic structure of struts
PersonManagement
SportManagement
Servlet
Servlet
JSP
JSP
sport
person
3
2
personName
sportName location
1
sportForm
personForm
129
1 Action Form PersonForm.java ( java bean )
/ _at_struts.form name"personForm" / public
final class PersonForm extends ActionForm
private String personName public String
getPersonName() return
(this.personName) public void
setPersonName(String personName)
this.personName personName
130
HTML Form, calling an action-servlet
2 JSP input.jsp lth3gtpersonForm.sportFormlt/h3gt
lthtmlform action"/personManagement"gt
sportName lthtmltext
property"name"/gt lthtmlsubmit/gt
lt/htmlformgt
131
3 Action Servlet
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"))
132
Auxiliary file struts-config.xml
(generated by xDoclet)
ltaction-mappingsgt ltaction
path"/personManagement" type"management.Pe
rsonManagement" name"personForm"
scope"session" input"/pages/Error.jsp"
unknown"false" validate"true" gt
ltforward name"sport"
path"/pages/sport.jsp" redirect"false"
/gt lt/actiongt ltaction-mappingsgt
133
- Action forms,- arrays of action forms,- trees
of action forms
134
Complex Java beans
person
SportManagement
In/out
PersonManagement
Action
Action
In/out
In/out
sport
job
jobName location
jobName location
personName
sportName location
jobName location
jobName location
personName
jobName location
sportForm
jobName location
personForm
jobFormN
jobForm
sportName location
sportForm
135
WebLang Module Forms (Java beans)
form SportForm package fmPack fields
(String sportName, int location) form
PersonForm // sub-form package
fmPack fields ( String
personName ) forms ( jobForm, sportFormN
) form JobForm // arrays
add N and package fmPack fields
(String jobName, int location)
136
Tree of action forms
/ _at_struts.form name"personForm" / public
final class PersonForm extends ActionForm .
. . private SportForm sportForm public
SportForm getSportForm () return
(this.sportForm) public void
setSportForm (SportForm sportForm)
this.sportForm sportForm
137
Array of sub-action forms
(
x or Collection or Set ) / _at_struts.form
name"personForm" / public final class
PersonForm extends ActionForm . . .
private Collection sportFormN public
Collection getSportFormN () return
(this.sportFormN) public void
setSportFormN (Collection sportFormN)
this.sportFormN sportFormN
138
Reference to an Action Form
Dans laction servlet f.getName() Dans la
JSP lthtmltext property"name"/gt f est liée à
la JSP dans struts-config.xml
139
Reference to a Sub-Action Form
Dans laction servlet f.getSportForm().getName()
Dans la JSP lthtmltext property"sportForm.name
"/gt f est liée à la JSP dans struts-config.xml
140
Reference to an array of Sub-Action Forms
In the action servlet (first element ! ) o
((ArrayList) f.getSportForm() name
((SportForm) o.get(0)).getName() In the
JSP lthtmltext property"sportForm0.name"/gt
f is linked to a JSP in struts-config.xml
141
Automatic Creation of JSPs
142
WebLang use of the JSPs and servlets
sportName location
FSM bean
FSM bean
JSP
JSP
personName
Where to start ? Same bean,but different
states
143
Other Tags in the JSP and the Struts
ltjspuseBean id"managementForm" 
scope"session"
class"man.ManagementForm"/gt ltbeanwrite
name"managementForm"
property"warning" filter"false"/gt
http//localhost8080/struts-documentation http
//ltiwww.epfl.ch/WebLang/references.html
144
HTML form in the preceding JSP
lth3gtPetFormlt/h3gt lthtmlform action"/Supplier_Stat
e_0_Action" gt lthtmlhidden name"petForm"
property"lt page_prop_token gt"
value"lt pageId gt" /gt lttable
border0gtlttrgt lttrgtlttdgt nbsp nbsp nbsp
name nbsp nbsp
lttdgtlthtmltext property"name"/gt lttrgtlttd
colspan2 aligncentergt lthtmlsubmit
property"submit"gtsubmitlt/htmlsubmitgt lt/tablegt lt
/htmlformgt
145
Array in the HTML form
lthtmlform action"/Supplier_State_0_Action"
gt lthtmlhidden name"petForm" property"lt
page_prop_token gt" value"lt pageId
gt" /gt lttable border"0" cellspacing"1"gt lt
trgtlttdgt lttable border"0" width"100"gtlttdgtsubName
lt/tablegt lttdgt lttable border"0"
width"100"gtlttdgtnumberlt/tablegt lttdgt lttable
border"0" width"100"gtlttdgtchecklt/tablegt lttrgtltt
dgt lttable border"0" cellspacing"1"gtlt/tablegt
lt!-- tableau ?
transparent suivant lttrgtlttd colspan10
aligncentergt lthtmlsubmit
property"submit"gtsubmitlt/htmlsubmitgt
lt/tablegt lt/htmlformgt
146
Iteration on the array (or collection)
ltlogiciterate name"petForm" property"thingN
" id"item1" indexId"index1"gt lttrgtlttdgt lt
table border"0" width"100"ltcolorindex1.intVa
lue()2gtgt lttdgt nbspltbeanwrite name"item1"
property"subName"/gt lt/tablegt lttdgt lttable
border"0" width"100"ltcolorindex1.intValue()
2gtgt lttdgtltbeanwrite name"item1"
property"number"/gt lt/tablegt lttdgt lttable
border"0" width"100" ltcolorindex1.intValue()
2gtgt lttdgtlthtmlcheckbox property'lt"thingN"
index1.intValue()".check"gt'/gt lt/tablegt lt/logi
citerategt
pour que la valeur soit
retournée dans lURL
147
Struts JSP
struts Supplier . . . page
supply forms (petForm, petForm.thingN
) form PetForm package fp
fields (String name) forms
(thingN) form Thing package fp
fields ( String subName, int
number, boolean check)
148
Different display formats
page SomePage forms ( petForm,
petForm.thingN , petForm.bbb
(MySubmit), // displays a MySubmit
button petForm.ccc ( "An indication",
Cancel) // display a comment and a
button petForm.aaa (),
// displays no button )
149
Finite State Machine in a Struts


Struts
0
not confir- med
showBasket
1
confirmed
2
OK
150
Struts in WebLang
browseForm.petForm (form)


Struts
Action Forms
browser (JSP)
0
not confir- med
basket.petFrom (form)
showBasket
1
showBasket (JSP)
confirmed
order- registered (JSP)
2
PetOrder status ordered OrderItems
(CMPCMR)
CMP bean
OK
JSPs
Action Servlet
151
WebLang Module states and pages
struts PersonManagement package
management stateMachine statedef
State_0 (person) statedef State_1
(job) . . . FSM . . . page
person forms ( personForm,
personForm.sportForm ,
personForm ("Comment", submitName) )
152
WebLang Module Finite State Machine
stateMachine statedef State_0 (supply)
statedef 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
// Pure Java code
153
Three tiers (overview)
browseForm.petForm (form)
Buying
Struts
browser (JSP)
Administrator Struts

0
areYouThe- Administrator (JSP)
PetOrder status toBeChecked OrderItems
(CMPCMR)
0
not confir- med
basket.petFrom (form)
showBasket
login
1
showBasket (JSP)
checkOrders (JSP)
OrderForm.petForm not ? accept (form)
select
1
confirmed
order- registered (JSP)
2
confirmed
PetOrder status ordered OrderItems
(CMPCMR)
OK
SendSupplierPO MDBean
Queue
file
PetOrder status awaitInvoice OrderItems
(CMPCMR)
Database Dataflow
Display
Business Layer
Display
Business Layer
154
Transfer of data
  • From an action form to a CMP bean
  • and vice-versa

155
Action Forms ??CMP Beans
Action forms
finder or getCollection
Recreates a collection and copies one into the
other member by member
CMP beans
// code next page
156
Action Forms ??CMP Beans
String courseName result.getCourseForm().getName
()
// reads an
action form java.util.CollectionltPersongt
coll personHome.findPersonInCourse(courseName
) java.util.CollectionltPersonFormgt c new
ArrayListltPersonFormgt () for (Person aPerson
coll) // scan the collection of
CMP beans PersonForm personF new
PersonForm() personF.setFirstName(aPe
rson.getFirstName())
personF.setLastName(aPerson.getLastName())
c.add(personF) // creates
the collection of action forms result.setPersonF
ormN( c )
157
Exercise 7
  • Transform the exercise about towns and countries
    and implement it with Struts
  • Draw first a diagram with the html forms, the
    action forms, the state machine and the database

WebLang modules
CMP bean Town name
Generated automatically
struts TownInCountry - get a town - get a
country - insert and connect
html TownInCtr Start struts
CMP bean Country name
158
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

159
WebLang module
ejb3 MyCountry package myPackage
relations (Town1N) 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.CollectionltTowngt tlist
getTownN() for (Town town tlist)
str str "\n Town" town
return (str)
160
Use of the 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) country.setNumber(1291)
tx.commit() // or tx.rollback() hibernate_u
tility.Manager.close()
161
Finders of Hibernate
javax.persistence.Query qt qt
em.createQuery("select t from Town t where
t.name?")qt.setParameter(1, town.getName())tr
y       town (Town)qt.getSingleResult()
catch (javax.persistence.EntityNotFoundException
enf)       town.setId(0)            
em.persist(town)
162
Action form Hibernate bean
ejb3 MyCountry extends strutsStateMachine.StateFo
rm package myPackage relations
(Town1N) String name int number
163
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)

164
SQL Bean Example
sqlbean Town extends strutsStateMachine.StateForm
package appliT relations ( Country
N1, ltisCapitalOf 11
hasCapitalgt Country) String name public
long findPK_OfTown() throws Exception query
"SELECT FROM Town WHERE namename"
TownN public void findN_TownList(String
s) throws Exception query "SELECT FROM
Town WHERE namegts"
165
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
166
Finders
TownN tn new TownN() try
tn.findTownList(N) catch (weblangUtils.SQLExc
eption 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 namegts"
167
FSM of the SQL beans
Detached object
o new Xxx()
o.set(o1) o.add(o1)
o.set(null) o.remove(o1)
o.store()
o.findPKXx()
o.findXx()
o.store()
o.delete()
Attached object pk!0
o.delete()
Linked object pk0
o.reload(pk)
o.delete()
o.set(null) o.remove(o1)
o.set(o1) o.add(o1)
o.reloadAll()
o.storeAll()
Attached linked connected object pk!0 rel!0
o.deleteAll()
o.reload() o.reloadAll() o.update() o.updateAll()
168
States of the SQL objects
Detached The object has been instantiated Attache
d 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
169
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 object must 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
170
More Operations
  • delete Removes the data in the database, not the
    memory, resets the objects 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

171
RMI Application
172
RMI inverse communication (by transmitting the
stub)
myRemStub
MyRemote (stub)
173
RMI Module
rmi 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()

174
Software Engineering
175
Application / implementation
Craig (http//www.codegeneration.net/tiki-read_ar
ticle.php?articleId27) 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.
176
My View
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.
Library (Librarian, book shelves, quiet
room)
Soft Library (simulator) (terminals,
server, software) Each time a book is borrowed
in the real library, the librarian borrows a
book here

Borrow a book Look for a user A book has been
lost Check differences Sort books Reserve a book
Software application (terminals, server,
software)
177
Three tiers (overview)
browseForm.petForm (form)
Buying
Struts
browser (JSP)
Administrator Struts

0
areYouThe- Administrator (JSP)
PetOrder status toBeChecked OrderItems
(CMPCMR)
0
not confir- med
basket.petFrom (form)
showBasket
login
1
showBasket (JSP)
checkOrders (JSP)
OrderForm.petForm not ? accept (form)
select
1
confirmed
order- registered (JSP)
2
confirmed
PetOrder status ordered OrderItems
(CMPCMR)
OK
SendSupplierPO MDBean
Queue
file
PetOrder status awaitInvoice OrderItems
(CMPCMR)
Database Dataflow
Display
Business Layer
Display
Business Layer
178
Exercise of Software Engineering (8)
  • Creation of a stock exchange application.Customer
    s 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.
Write a Comment
User Comments (0)
About PowerShow.com