Javier Ramos Rodríguez
J2EE Internet Store An Example of Building an Enterprise Web Application Bachelor’s Thesis Information Technology
May 2005
2
DESCRIPTION Date of the bachelor's thesis
May 17, 2005
Author(s)
Degree programme and option
Javier Ramos Rodríguez
Information Technology
Name of the bachelor's thesis
J2EE Internet Store: An example of building an enterprise web application. Abstract
It is obvious that software development has change considerably in the past years. The machines have considerably increased their speed and telecommunications have grown exponentially in the last 15 years. Also, customer’s requirements have increase in the past years and more complex and reliable software is required. The software development has to adapt to the new infrastructures; many tools and software patterns have appear to help developers to build software that adapts to both, technology and customers requirements. Probably the development of enterprise applications is the most complex task in software engineering. It requires the domain of various technologies, such as databases, transactions handling, distributed applications and Client/Server applications among others. Developers have to face several problems due to the size of the enterprise applications. With this diploma work I attempt to show and explain how to build enterprise applications using the J2EE platform. The idea is to talk about the platform and its technologies, explaning also some design concepts like design patterns. I tried to explain all the concepts the simplest way using a practical approach following a usual example: An Internet Store. First, I introduce the J2EE platform and all its technologies trying to summarize all the concepts the best way. Also, I talk about the design patterns used in the development of enterprise applications. In the second part, I explain the application trying to show all the concepts that were introduce before. Subject headings, (keywords)
J2EE, Java, OOP, Struts, EJB, JDBC, XML, Design Patterns, Hibernate, Spring, Open Source, UML… Pages
Language
336
English
URN
Remarks, notes on appendices
Mikkeli Polytechnic Tutor
Supervisor: Reijo Vuohelainen
Employer of the bachelor's thesis
3
List of figures Chapter 2: FIGURE 1 .................................................................................................................................................... 33 FIGURE 2 .................................................................................................................................................... 34 FIGURE 3 .................................................................................................................................................... 35 FIGURE 4 .................................................................................................................................................... 38 FIGURE 5 .................................................................................................................................................... 39 FIGURE 6 .................................................................................................................................................... 43 FIGURE 7 .................................................................................................................................................... 49 FIGURE 8 .................................................................................................................................................... 57 FIGURE 9 .................................................................................................................................................... 57 FIGURE 10 .................................................................................................................................................. 66 FIGURE 11 .................................................................................................................................................. 88 FIGURE 12 .................................................................................................................................................. 92 FIGURE 13 .................................................................................................................................................. 95 FIGURE 14 .................................................................................................................................................. 96 FIGURE 15 .................................................................................................................................................. 97 FIGURE 16 ................................................................................................................................................ 102 FIGURE 17 ................................................................................................................................................ 104 FIGURE 18 ................................................................................................................................................ 105 FIGURE 19 ................................................................................................................................................ 106 FIGURE 20 ................................................................................................................................................ 107 FIGURE 21 ................................................................................................................................................ 109 FIGURE 22 ................................................................................................................................................ 114 FIGURE 23 ................................................................................................................................................ 116 FIGURE 24 ................................................................................................................................................ 128 FIGURE 25 ................................................................................................................................................ 129 FIGURE 26 ................................................................................................................................................ 132 FIGURE 27 ................................................................................................................................................ 133 FIGURE 28 ................................................................................................................................................ 134
Chapter 3: FIGURE 29 ................................................................................................................................................ 155 FIGURE 30 ................................................................................................................................................ 156
4 Chapter 4:
FIGURE 31 ................................................................................................................................................ 169 FIGURE 32 ................................................................................................................................................ 170 FIGURE 33 ................................................................................................................................................ 171 FIGURE 34 ................................................................................................................................................ 171 FIGURE 35 ................................................................................................................................................ 172 FIGURE 36 ................................................................................................................................................ 173 FIGURE 37 ................................................................................................................................................ 174 FIGURE 38 ................................................................................................................................................ 175 FIGURE 39 ................................................................................................................................................ 176 FIGURE 40 ................................................................................................................................................ 176 FIGURE 41 ................................................................................................................................................ 177 FIGURE 42 ................................................................................................................................................ 178 FIGURE 43 ................................................................................................................................................ 179 FIGURE 44 ................................................................................................................................................ 180 FIGURE 45 ................................................................................................................................................ 181 FIGURE 46 ................................................................................................................................................ 182 FIGURE 47 ................................................................................................................................................ 182 FIGURE 48 ................................................................................................................................................ 184 FIGURE 49 ................................................................................................................................................ 185 FIGURE 50 ................................................................................................................................................ 186 FIGURE 51 ................................................................................................................................................ 187 FIGURE 52 ................................................................................................................................................ 187 FIGURE 53 ................................................................................................................................................ 188 FIGURE 54 ................................................................................................................................................ 190 FIGURE 55 ................................................................................................................................................ 191 FIGURE 56 ................................................................................................................................................ 193 FIGURE 57 ................................................................................................................................................ 194 FIGURE 58 ................................................................................................................................................ 195 FIGURE 59 ................................................................................................................................................ 196 FIGURE 60 ................................................................................................................................................ 197 FIGURE 61 ................................................................................................................................................ 199 FIGURE 62 ................................................................................................................................................ 200 FIGURE 63 ................................................................................................................................................ 202 FIGURE 64 ................................................................................................................................................ 203 FIGURE 65 ................................................................................................................................................ 204 FIGURE 66 ................................................................................................................................................ 206 FIGURE 67 ................................................................................................................................................ 207 FIGURE 68 ................................................................................................................................................ 211 FIGURE 69 ................................................................................................................................................ 213 FIGURE 70 ................................................................................................................................................ 215 FIGURE 71 ................................................................................................................................................ 216 FIGURE 72 ................................................................................................................................................ 217 FIGURE 73 ................................................................................................................................................ 219 FIGURE 74 ................................................................................................................................................ 221 FIGURE 75 ................................................................................................................................................ 223 FIGURE 76 ................................................................................................................................................ 226 FIGURE 77 ................................................................................................................................................ 228
5 Chapter 5: FIGURE 78 ................................................................................................................................................ 242 FIGURE 79 ................................................................................................................................................ 243 FIGURE 80 ................................................................................................................................................ 244 FIGURE 81 ................................................................................................................................................ 245 FIGURE 82 ................................................................................................................................................ 246 FIGURE 83 ................................................................................................................................................ 247 FIGURE 84 ................................................................................................................................................ 249 FIGURE 85 ................................................................................................................................................ 250 FIGURE 86 ................................................................................................................................................ 251 FIGURE 87 ................................................................................................................................................ 252 FIGURE 88 ................................................................................................................................................ 254 FIGURE 89 ................................................................................................................................................ 256 FIGURE 90 ................................................................................................................................................ 258 FIGURE 91 ................................................................................................................................................ 259 FIGURE 92 ................................................................................................................................................ 260 FIGURE 93 ................................................................................................................................................ 261 FIGURE 94 ................................................................................................................................................ 262 FIGURE 95 ................................................................................................................................................ 264 FIGURE 96 ................................................................................................................................................ 265 FIGURE 97 ................................................................................................................................................ 266 FIGURE 98 ................................................................................................................................................ 267 FIGURE 99 ................................................................................................................................................ 268 FIGURE 100 .............................................................................................................................................. 269 FIGURE 101 .............................................................................................................................................. 271 FIGURE 102 .............................................................................................................................................. 272 FIGURE 103 .............................................................................................................................................. 273 FIGURE 104 .............................................................................................................................................. 275 FIGURE 105 .............................................................................................................................................. 276 FIGURE 106 .............................................................................................................................................. 277 FIGURE 107 .............................................................................................................................................. 278 FIGURE 108 .............................................................................................................................................. 280 FIGURE 109 .............................................................................................................................................. 281 FIGURE 110 .............................................................................................................................................. 282 FIGURE 111 .............................................................................................................................................. 283 FIGURE 112 .............................................................................................................................................. 286 FIGURE 113 .............................................................................................................................................. 287 FIGURE 114 .............................................................................................................................................. 288 FIGURE 115 .............................................................................................................................................. 289 FIGURE 116 .............................................................................................................................................. 291 FIGURE 117 .............................................................................................................................................. 292 FIGURE 118 .............................................................................................................................................. 293 FIGURE 119 .............................................................................................................................................. 294 FIGURE 120 .............................................................................................................................................. 295 FIGURE 121 .............................................................................................................................................. 296 FIGURE 122 .............................................................................................................................................. 297 FIGURE 123 .............................................................................................................................................. 299 FIGURE 124 .............................................................................................................................................. 300 FIGURE 125 .............................................................................................................................................. 301 FIGURE 126 .............................................................................................................................................. 302 FIGURE 127 .............................................................................................................................................. 303 FIGURE 128 .............................................................................................................................................. 304 FIGURE 129 .............................................................................................................................................. 305 FIGURE 130 .............................................................................................................................................. 307 FIGURE 131 .............................................................................................................................................. 308 FIGURE 132 .............................................................................................................................................. 309 FIGURE 133 .............................................................................................................................................. 310 FIGURE 134 .............................................................................................................................................. 311 FIGURE 135 .............................................................................................................................................. 312
6 FIGURE 136 .............................................................................................................................................. 313 FIGURE 137 .............................................................................................................................................. 315 FIGURE 138 .............................................................................................................................................. 316 FIGURE 139 .............................................................................................................................................. 317 FIGURE 140 .............................................................................................................................................. 319 FIGURE 141 .............................................................................................................................................. 320 FIGURE 142 .............................................................................................................................................. 322 FIGURE 143 .............................................................................................................................................. 323 FIGURE 144 .............................................................................................................................................. 324 FIGURE 145 .............................................................................................................................................. 325 FIGURE 146 .............................................................................................................................................. 327 FIGURE 147 .............................................................................................................................................. 328 FIGURE 148 .............................................................................................................................................. 329
7
Abbreviations − API: Application Programming Interface − ASP: Active Server Pages − BMP: Bean Managed Persistence − CGI: Common Gateway Interface script − CMP: Container Managed Persistence − COM: Component Object Model − CORBA: Common Object Request Broker Architecture − DAO: Data Access Object − DB: Data Base − LAMP: Linux+Apache+MySQL+PHP/Perl/Phyton − DBMS: DataBase Management System − DCE: Distributed Computing Environment − DCOM: Distributed COM − DNS: Domain Name System − DTD: Document Type Definition − EJB: Enterprise Java Bean − EL: Expression Language − EMF: Eclipse Modeling Framework − FTP: File Transfer Protocol − HTML: HyperText Markup Language − IDL: Interface Description Language − ISBN: International Standard Book Number − J2EE: Java 2 Enterprise Edition − J2ME: Java 2 Micro Edition − J2SE: Java 2 Standard Edition − JCA: Java Connector Architecture − JCP: Java Community Process − JDBC: Java DataBase Connectivity − JDK: Java Development Kit − JNDI: Java Naming and Directory Interface
8 − JMS: Java Message Service − JMX: Java Management Extensions − JRE: Java Runtime Environment − JSF: Java Server Faces − JSP: JavaServer Page − JSTL: JSP Standard Tag Library − JTS: Java Transaction Service − JVM: Java Virtual Machine − LDAP: Lightweight Directory Access Protocol − MVC: Model-View-Controller pattern − NIS: Network Information Service − ODBC: Open DataBase Connectivity − OLE: Object Linking and Embedding − OMG: Object Management Group − OODB: Object Oriented DataBase − OOP: Object Oriented Programming − ORB: Object Request Broker − ORPC: Object Remote Procedure Call − PHP: Hypertext Preprocessor − POJO: Plain Old Java Object − RMI: Remote Method Invocation − RPC: Remote Procedure Call − SB: Session Bean − SFSB: State Full Session Bean − SGML: Standard Generalized Markup Language − SLSB: State Less Session Bean − SMTP: Simple Mail Transfer Protocol − SOAP: Simple Object Access Protocol − SQL: Structured Query Language − SSI: Server-Side Include − SSL: Secure Sockets Layer − TCP: Transmission Control Protocol
9 − UDP: User Datagram Protocol − UI: User Interface − UML: Unified Modeling Language − UMTS: Universal Mobile Telecommunications System − URL: Uniform Resource Locator − VB: Visual Basic − VO: Value Object − WML: Wireless Markup Language − WSDL: Web Services Description Language − XML: EXtensible Markup Language
10
TABLE OF CONTENS Description.................................................................................................................................................. 2 List of figures.............................................................................................................................................. 3 Abbreviations ............................................................................................................................................. 7 PREFACE ................................................................................................................................................ 15 1.
2.
INTRODUCTION.......................................................................................................................... 18 1.1.
OPEN SOFTWARE SOLUTIONS...................................................................................... 19
1.2.
ENTERPRISE ARCHITECTURE AND THE PRESENT PANORAMA........................ 21
1.2.1.
LAMP ................................................................................................................................ 24
1.2.2.
CORBA.............................................................................................................................. 25
1.2.3.
.NET .................................................................................................................................. 26
1.2.4.
J2EE .................................................................................................................................. 28
JAVA 2 ENTERPRISE EDITION OVERVIEW ........................................................................ 30 2.1.
J2EE DEFINITION .............................................................................................................. 30
2.2.
MULTITIER ARCHITECTURE........................................................................................ 32
2.2.1.
2-tier approach .................................................................................................................. 33
2.2.2.
Multitier approach ............................................................................................................ 34
2.3.
MAIN ARCHITECTURAL PATTERNS USED IN ENTERPRISE APPLICATIONS . 36
2.4.
J2EE MODEL ....................................................................................................................... 39
2.5.
J2EE TECHNOLOGIES...................................................................................................... 42
2.5.1.
JDBC ................................................................................................................................. 42
2.5.1.1.
Types of JDBC technology drivers .......................................................................................44
2.5.1.2
Establishing a connection......................................................................................................45
2.5.1.3
Concurrence problems with the database ...........................................................................46
2.5.2
XML................................................................................................................................... 48
2.5.2.1
DTDs .......................................................................................................................................52
2.5.3
SERVLETS ....................................................................................................................... 53
2.5.4
JSP PAGES ....................................................................................................................... 61
2.5.4.1
JSP Pages Overview ..............................................................................................................62
2.5.4.2
JSP Use ...................................................................................................................................64
2.5.4.3
Language Syntax....................................................................................................................67
2.5.4.3.1
Directives...........................................................................................................................68
2.5.4.3.2
Script Elements................................................................................................................69
2.5.4.3.3
Comments .........................................................................................................................70
2.5.4.3.4
Actions...............................................................................................................................71
2.5.4.4
JavaBeans...............................................................................................................................72
2.5.4.5
JSP example ...........................................................................................................................74
2.5.4.6
JSP Architecture....................................................................................................................75
11 2.5.4.7
JSP vs. ASP ............................................................................................................................78
2.5.4.7.1
2.5.5
Examples ...........................................................................................................................81
JSP 2.0............................................................................................................................... 82
2.5.5.1
Expression Language (EL)....................................................................................................83
2.5.6
JAVA STANDARD TAG LIBRARY (JSTL).................................................................... 85
2.5.7
JAKARTA STRUTS .......................................................................................................... 87
2.5.7.1
MVC in web applications ......................................................................................................89
2.5.7.2
Servlet Front Controller pattern ..........................................................................................92
2.5.7.3
Model View Controller architecture using Struts...............................................................94
2.5.7.4
Struts Example.......................................................................................................................95
2.5.8
DISTRIBUTED APPLICATIONS ................................................................................. 100
2.5.8.1
Distributed Applications on Internet .................................................................................101
2.5.8.2
Intranet Applets...................................................................................................................101
2.5.8.3
Distributed Computation Environment (DCE).................................................................101
2.5.8.4
Distributed Component Object Model (DCOM)...............................................................103
2.5.8.5
Common Object Request Broker Architecture (CORBA)...............................................105
2.5.8.6
Java Remote Method Invocation (RMI) ............................................................................107
2.5.8.6.1
2.5.9
Java RMI as a technology for development enterprise applications ..........................112
JAVA NAMING AND DIRECTORY INTERFACE (JNDI) ........................................ 114
2.5.9.1
2.5.10
JNDI Architecture ...............................................................................................................116
ENTERPRISE JAVABEANS (EJB) ......................................................................... 118
2.5.10.1
EJB Architecture .................................................................................................................120
2.5.10.1.1
Distributed components .................................................................................................120
2.5.10.1.2
Implicit or Declarative Middleware..............................................................................121
2.5.10.1.3
Physical situation transparency ....................................................................................122
2.5.10.1.4
Local interfaces...............................................................................................................122
2.5.10.2
TYPES OF COMPONENTS ..............................................................................................123
2.5.10.2.1
Session Beans (SB)..........................................................................................................123
2.5.10.2.2
Entity Beans ....................................................................................................................125
2.5.10.2.3
Message-Driven Beans ...................................................................................................127
2.5.10.3
J2EE EJB Structure ............................................................................................................128
2.5.10.4
2.6
EJB Operation ................................................................................................................130
J2EE vs. .NET................................................................................................................. 139
2.6.2
Similarities between J2EE and .NET ......................................................................................139
2.6.3
Advantages of .Net over J2EE..................................................................................................140
2.6.4
Advantages of J2EE over .NET ...............................................................................................142
2.6.5
The Future.................................................................................................................................144
12 3.
NEW APPROACHES USING JAVA 2 PLATFORM .............................................................. 147 3.1 3.1.1
JavaServer Faces (JSF) .................................................................................................. 149
3.1.2
Spring .............................................................................................................................. 150
3.1.3
Struts vs. JSF vs. Spring ................................................................................................. 151
3.2
4.
5.
MVC FRAMEWORKS............................................................................................................ 149
HIBERNATE .......................................................................................................................... 153
3.2.1
Hibernate Structure ........................................................................................................ 155
3.2.2
Hibernate Overview......................................................................................................... 156
3.2.3
Hibernate Features ......................................................................................................... 157
3.2.4
Hibernate Example ......................................................................................................... 160
DESIGN PATTERNS .................................................................................................................. 168 4.1
USUAL OOP DESIGN PATTERNS ................................................................................. 169
4.2
ENTERPRISE APPLICATIONS DESIGN PATTERNS ................................................ 209
4.2.1
Session Facade................................................................................................................ 210
4.2.2
Business Delegate ........................................................................................................... 213
4.2.3
Service Locator................................................................................................................ 215
4.2.4
Value Object .................................................................................................................... 217
4.2.5
Value Object (EJB) ......................................................................................................... 220
4.2.6
Data Access Object.......................................................................................................... 223
4.2.7
Page-by-Page Iterator ..................................................................................................... 226
4.2.8
Fast-Lane Reader............................................................................................................ 228
CASE STUDY: J2EE INTERNET STORE............................................................................... 231 5.1
MAIN DESCRIPTION....................................................................................................... 232
5.1.1
Functional Requirements of the System......................................................................... 234
5.1.2
Non-Functional Requirements of the System ................................................................ 236
5.2 5.2.1 5.3
ARCHITECTURE.............................................................................................................. 237 Software Used.................................................................................................................. 239 USE CASE VIEW ............................................................................................................... 241
5.3.1
General Diagram............................................................................................................. 242
5.3.2
User Registration Diagram ............................................................................................. 243
5.3.3
User Authentication ........................................................................................................ 244
5.3.4
Product Visualization...................................................................................................... 245
5.3.5
Product Searches............................................................................................................. 246
5.3.6
Shopping Cart Administration........................................................................................ 247
13 5.4
LOGICAL VIEW................................................................................................................ 248
5.4.1
5.4.1.1
Item Facade..........................................................................................................................249
5.4.1.2
User Facade..........................................................................................................................250
5.4.1.3
Util Facade ...........................................................................................................................251
5.4.1.4
Shopping Facade..................................................................................................................252
5.4.2
5.5
GLOBAL ARCHITECTURE.......................................................................................... 248
PACKAGE DESCRIPTIONS ......................................................................................... 254
5.4.2.1
Package “fi.mamk.jramos.j2ee.j2eestore.model.category.dao” .......................................254
5.4.2.2
Package “fi.mamk.jramos.j2ee.j2eestore.model.category.vo” .........................................258
5.4.2.3
Package “fi.mamk.jramos.j2ee.j2eestore.model.country.dao” ........................................259
5.4.2.4
Package “fi.mamk.jramos.j2ee.j2eestore.model.country.vo”...........................................261
5.4.2.5
Package “fi.mamk.jramos.j2ee.j2eestore.model.idegenerator.ejb” .................................262
5.4.2.6
Package “fi.mamk.jramos.j2ee.j2eestore.model.item.dao” ..............................................264
5.4.2.7
Package “fi.mamk.jramos.j2ee.j2eestore.model.item.vo” ................................................266
5.4.2.8
Package “fi.mamk.jramos.j2ee.j2eestore.model.itemfacade.delegate” ...........................267
5.4.2.9
Package “fi.mamk.jramos.j2ee.j2eestore.model.itemfacade.ejb ......................................269
5.4.2.10
Package “fi.mamk.jramos.j2ee.j2eestore.model.order.ejb” .............................................272
5.4.2.11
Package “fi.mamk.jramos.j2ee.j2eestore.model.order.vo” ..............................................274
5.4.2.12
Package “fi.mamk.jramos.j2ee.j2eestore.model.shoppingcart.ejb” ................................277
5.4.2.13
Package “fi.mamk.jramos.j2ee.j2eestore.model.shoppingcart.vo”..................................279
5.4.2.14
Package “fi.mamk.jramos.j2ee.j2eestore.model.shoppingfacade.delegate”....................281
5.4.2.15
Package “fi.mamk.jramos.j2ee.j2eestore.model.shoppingfacade.ejb” ............................283
5.4.2.16
Package “fi.mamk.jramos.j2ee.j2eestore.model.shoppingfacade.ejb.actions” ...............287
5.4.2.17
Package “fi.mamk.jramos.j2ee.j2eestore.model.specificitem.dao”..................................289
5.4.2.18
Package “fi.mamk.jramos.j2ee.j2eestore.model.specificitem.vo”....................................292
5.4.2.19
Package “fi.mamk.jramos.j2ee.j2eestore.model.transport.dao”......................................293
5.4.2.20
Package “fi.mamk.jramos.j2ee.j2eestore.model.transport.vo”........................................295
5.4.2.21
Package “fi.mamk.jramos.j2ee.j2eestore.model.userfacade.delegate”............................296
5.4.2.22
Package “fi.mamk.jramos.j2ee.j2eestore.model.userfacade.ejb” ....................................298
5.4.2.23
Package “fi.mamk.jramos.j2ee.j2eestore.model.userfacade.ejb.actions” .......................301
5.4.2.24
Package “fi.mamk.jramos.j2ee.j2eestore.model.userfacade.exceptions” ........................303
5.4.2.25
Package “fi.mamk.jramos.j2ee.j2eestore.model.userfacade.util”....................................304
5.4.2.26
Package “fi.mamk.jramos.j2ee.j2eestore.model.userfacade.vo”......................................305
5.4.2.27
Package “fi.mamk.jramos.j2ee.j2eestore.model.userprofile.ejb” ....................................306
5.4.2.28
Package “fi.mamk.jramos.j2ee.j2eestore.model.userprofile.vo” .....................................309
5.4.2.29
Package “fi.mamk.jramos.j2ee.j2eestore.model.util” .......................................................310
5.4.2.30
Package “fi.mamk.jramos.j2ee.j2eestore.model.utilfacade.delegate” .............................312
5.4.2.31
Package “fi.mamk.jramos.j2ee.j2eestore.model.utilfacade.ejb”......................................314
5.4.2.32
Package “fi.mamk.jramos.j2ee.j2eestore.http.controller.actions” ..................................317
5.4.2.33
Package “fi.mamk.jramos.j2ee.j2eestore.http.controller.frontcontroller” .....................320
5.4.2.34
Package “fi.mamk.jramos.j2ee.j2eestore.http.controller.session”...................................323
5.4.2.35
Package “fi.mamk.jramos.j2ee.j2eestore.view.actionforms” ...........................................325
5.4.2.36
Package “fi.mamk.jramos.j2ee.j2eestore.view.applicationobjects”.................................328
5.4.2.37
Package “fi.mamk.jramos.j2ee.j2eestore.view.messages” ................................................330
PROJECT INFORMATION ............................................................................................. 331
14 6.
CONCLUSION............................................................................................................................. 332
7.
REFERENCES ............................................................................................................................. 335 7.1
INTERNET REFERENCES ...................................................................................................... 335
7.2
BOOKS REFERENCES............................................................................................................ 336
15
PREFACE The goal of this diploma work is to show the reader how to develop enterprise applications using the J2EE platform. Enterprise applications may be one of the most difficult fields in the Software engineering field. In this diploma work I try to explain all the architecture and its technologies in the simplest possible way. However, this diploma is focus on software engineering’s who are willing to learn this new platform. So, I assume the reader has some basic knowledge about this world. Next, I describe the requirements to follow this diploma work, which are the usual for a J2EE course:
Java Language Knowledge: The reader must know the basic Java concepts like what is a JVM, a Java thread, a static variable, a Java interface, garbage collector…
Object Oriented Programming (OOP): The reader must understand the basic ideas of the OOP, like what is an object, a class, hierarchy, an abstract class…
Database Knowledge: The reader must have enough knowledge to understand what is a transaction, an SQL query, a primary key…
Software Design Knowledge: The reader must know the basic idea of software design like the UML language or the design patterns.
16 Diploma work organization This diploma work is organizing in two parts: 1. On the first part I introduce the knowledge to be able to understand and follow the final web application. We begin with an introduction to the enterprise applications; talking about the origins of these types of applications and the present panorama, we also discuss about the open source solutions. Finally we introduce the most famous enterprise technologies. Then, we have the J2EE overview. First, we give a short introduction and we also explain some basic concepts to understand the architecture. After that, we explain the J2EE architecture and all its technologies which are necessary to understand the main application. After that, we introduce other new approaches based on the Java technology. Then, we discuss about the big topic on enterprise application: J2EE vs. .NET.
17 Finally, we go into the scary world of the design patterns. This is probably the most difficult part to understand but the knowledge of these patterns is necessary to build scalable applications. We, begin with a short review of the usual OOP patterns, on this section I don’t try to teach the patterns is just a short review to be use as a reference for someone who already study then, if the reader doesn’t have any knowledge about these main pattern he may have some difficulties following this diploma work. I recommend further reading about design patterns. After this review, we introduce the J2EE Core Patterns, which are the main patterns used in the J2EE platform, most of them related with the EJB technology. We take a close look to these patterns because they are use on the main application.
2. On the second part we describe the application. We will use case diagrams to describe the functionality and class diagram to show the structure of the application.
3. Finally, we have the conclusions.
18
1. INTRODUCTION Software development has change considerably in the past years. The machines have considerably increased their speed, and telecommunications have grown exponentially in the last 15 years. Also, customer’s requirements have increase in the past years and more complex and reliable software is required. The software development has to adapt to the new infrastructures; many tools and software patterns have appear to help developers to build software that adapts to both, technology and customers requirements. Probably the development of enterprise applications is the most complex task in software engineering. It requires the domain of various technologies, such as databases, transactions handling, distributed applications and Client/Server applications among others. Developers have to face several problems due to the size of the enterprise applications. They should have knowledge of the following:
• Software engineering: They must have the ability to analyze the customer requirement and be able to create a good representation of the application using languages like the UML. Also, they must know the general requirements in enterprise application development.
• Enterprise applications technology: Developers must know a wide range of different tools and technologies used in the development of enterprise applications.
• Design Patterns: They should know all the basics design pattern to help building more reliable applications. Also, the experience of the developers is crucial.
19
1.1.
OPEN SOFTWARE SOLUTIONS
The design of enterprise applications has always been one of the most fruitful fields for proprietary software. The companies have always been reticent to the installation of free software to manage their precious treasure which is their information. One of the causes of this situation is mainly the ignorance of the market, as much on the part of the companies suppliers of services like on the part of the companies who contract these services. Many consultancies use proprietary solutions simply because they do not know others, even when the margins of benefits that can obtain are smaller. On the other hand it is very common that the clients know only the solutions of the most important companies and follow the way that these companies mark. The consequence of all this is normally the acquisition of as expensive products as unnecessary, simultaneously that are generated high costs of formation, consultancy and sub hiring. Luckily, the panorama nowadays is changing. At the present time the number of enterprise solutions in form of free software is growing at a rate that seems unstoppable. No longer are only the classic Web servers or data bases the protagonists, but a great number of products like applications servers, mail solutions, Web services systems, etc., are arising considerably. It’s difficult to ignore the existence of such solutions, and the people in charge in the decision making are considering, more often, the world of free software like a valid solution.
20 This causes that at the present time is feasible to create an enterprise architecture with all the requirements of scalability, reliability, easy to maintain, flexibility, security that these systems need; and using only and exclusively free software.
21
1.2.
ENTERPRISE ARCHITECTURE AND THE PRESENT PANORAMA
A possible abstract definition of enterprise architecture would be: "the study of complex enterprise systems from the point of view of its structure". An enterprise architect has to be able to study a concrete problem and choose a series of components to model the most suitable architecture for the problem. These components can be application servers, Web containers, mail servers, etc. The architect, also, has to be able to settle down how these components work, the tools to use and the existing relations between the components. The most complicated work and with the greater responsibility for an enterprise architect is the election of the enterprise platform on which the architecture of a company will be laid the foundations. An erroneous election can have catastrophic results for the company and also for the person in charge of this election. An enterprise development platform has to offer a series of directed services to the architects and developers to facilitate the development of enterprise applications, and at the same time it must provide the greater possible amount of functionalities to the users. Usually an enterprise development platform has the following requirements: •
Scalability: The application has to offer as much horizontal scalability as vertical scalability so that if the load of the system increases we can be able to add servers or to extend the existing ones without making modifications.
•
Easy to maintain: It has to allow adding or modifying the existing components without modifying the system behavior.
•
Reliability
•
Database Access
22 •
Availability: We need to have support for fault tolerant architectures, redundant systems, etc., we need to assure that our system will be always available.
•
Easy to expand: The system has to support the addition of new components and capacities to the system without affecting the rest of the components.
•
Manageability: Our systems easily have to be manageable and easy to configure.
•
Security: We require good security systems at authentication, authorization, and transport level.
•
Performance: Our application needs to offer automatically clustering support, load balance, object pools, connection pools, caches, and in general, mechanisms that allow to increase the performance in a transparent way for the user.
•
Multitier Architecture Support: In an enterprise application, it has to be a separation between the user graphical interface and the business model. The user interface (UI) can be standalone (window mode) or Web based. The business model encapsulates the application logic. The model has to be reusable for the different user interfaces. To achieve this, a multitier architecture has to be implemented.
The importance of an enterprise platform is that all these components are offered to us automatically so that the developers are much more productive. The difference between using an enterprise development platform and not using it is that in the second case our developers will lose long time making systems at low level, not being able to center in the development of applications and therefore diminishing considerably the productivity.
23 To develop an enterprise architecture using unique and exclusively products based on free software is really complicated. Probably, when proposing the use of any product based on free software in our company we will be with the typical questions: "Who is going to give technical support?", "What telephone should I call if some error takes place?” Luckily it seems that something is changing in the enterprise panorama. Many architects and engineers are beginning to see a new requirement indispensable for any enterprise development platform: The availability of free solutions. A platform that has free solutions contributes very important benefits extra to the architects since they obtain a great number of solutions at low cost that can evaluate, and in addition they usually have an ample community of developers to be able to solve problems that may appear. Returning to the subject of the proprietary solutions, many of these, often do not have of some (or several) of these characteristics, reason why we have to be very careful when we acquire these products (often very expensive) and to make sure that what really offers to us is worth what we are paying. In case outside little, the proprietary solutions, often can represent problems for the companies since these will be bound to third organizations on which they will depend for the evolution of his structures of information. It is for that why at the present time most important platforms are those than have the support of great amount of companies, organizations or associations and that have standardization groups which they assure the same ones the future. At the present time the more important enterprise development platforms are three: LAMP CORBA .NET J2EE
24
1.2.1.
LAMP
Lamp is an open source web platform used to develop web applications. Basically, is a set of various tools, concretely: Linux + Apache + MySQL + Perl/PHP/Python. It uses Linux as operating systems, Apache as a web server, MySQL as Database server and Perl/PHP/Python as programming languages. All of the software it’s open source. The main characteristics of this approach are:
Uses Script programming languages Provides database access Supports XML The main advantage of this approach is that doesn’t require a lot of knowledge on Web technologies and developers can easily build web applications. The problem is that this approach doesn’t satisfy the requirements to build enterprise applications such scalability, reliability, multitier support or security. Mostly, because PHP is a script language and not a powerful Object Oriented (OO) language like Java. Although PHP supports the concept of Object, is not a OO Language. So, the software quality is very low and is only suitable for home users.
25
1.2.2.
CORBA
Without a doubt, the model followed by any enterprise platform. The advantages that CORBA offers are very important:
Support of multiple operating systems.
Support of multiple languages.
Great amount of services: mail, events, transactions, persistence, etc.
Controlled by a serious organism, OMG.
The advantages are very important, even so, CORBA drags problems that suppose a serious trouble: •
Complexity: CORBA is a very complex development platform, although abstraction layers exist to facilitate the development of applications, the true is that to develop a simple "Hello World” program it is not a trivial work.
•
Bureaucracy: The evolution of the CORBA specifications is subject to too many passages of bureaucracy, which causes an enormous delay in the development of new features in the platform.
•
Few free solutions: As a result of his complexity and from the slowness of his evolution causes that few free solutions exist. OpenORB is an example and some others exist but the amount is not elevated.
26
1.2.3.
.NET
The enterprise development platform of Microsoft offers to the developers some interesting advantages: •
Support of multiple systems languages: Although it doesn’t support all its characteristics, the true is that with .NET is possible to develop applications using simultaneously several programming languages.
•
Ideal for Microsoft environment: If in our company we have great amount of software and dependent hardware of Microsoft, probably the best option is to continue developing is this platform, since its integration with products of the company is perfect.
•
Visual Studio .NET: The platform .NET has this great tool that in addition to its power offers a homogenous environment for development.
•
A great department of marketing: .NET will be a platform that will widely be used at enterprise level thanks to Microsoft marketing department who has tremendous effectiveness.
•
It doesn’t require so much experienced developers: Under the development platform of Microsoft .NET is possible to use languages like VB that make the creation of enterprise applications very simple. This way it is possible to have an equipment of developers little experienced but been able to create applications easily.
27 Even so, if the list of advantages is quite great, the list of disadvantages does not have anything to envy: •
It does not support multiple operating systems: The world of NET tour around the operating system Windows and although is being tried to transfer important parts of the platform, like the CLR or C #, to other operating systems, the true is that these parts comprise very small of the totality of the platform of Microsoft.
•
An only owner: The platform NET is dominated only by Microsoft. This supposes a serious problem since it the only company that can add and remove characteristics from the platform. Also, this causes that the competition is null and the evolution of the platform is not stimulated.
•
It is an immature technology: Its immaturity causes that probably it must spend some time until is really productive.
•
Few free solutions: There is not an exact correspondence between the parts of the platform .NET and free solutions. We cannot created a complete architecture only using products based on free software.
28
1.2.4.
J2EE
J2EE is a platform created by SUN in the year 1997 and is one of the best development perspectives for companies that want to base its architecture on products based on free software. J2EE offers us among other the following advantages: •
Support of multiple operative systems: Because the platform is based on the language Java, is possible to develop architectures based in J2EE using any operating system where you can execute a virtual machine Java.
•
Control organism: The platform J2EE is controlled for the JCP, an organism formed for more than 500 companies. The most important companies of computer world are among the companies, this guarantees the evolution of the platform.
•
Competitiveness: Many companies believe solutions based in J2EE and that they offer characteristic as performance, price, etc. This way the client has a great amount of options to choose.
•
Maturity: Created in the year 1997 as answer to the technology MTS of Microsoft, J2EE already have many years of life and a great amount of important projects.
•
Free solutions: In the platform J2EE it is possible to create unique based complete architectures and exclusively in products that are free software.
29 Even this way, the J2EE platform also has disadvantages, some important ones: •
It depends on an only language: The platform J2EE depends exclusively on Java language. You can only use this language to develop applications, this can suppose a big problem if our team doesn't have the enough knowledge or has other preferences.
•
Complexity: Although it is not such a complex platform as CORBA, a VB .NET doesn't exist in Java. The creation of applications under J2EE usually requires more experienced developers that the necessary ones to develop under .NET or LAMP.
•
Heterogeneity: A great heterogeneity exists in the development solutions. It doesn't exist in J2EE a simile to Visual Studio .NET. The great quantity of available tools causes confusion inside the developers and it can create dependences inside the companies.
30
2. JAVA 2 ENTERPRISE EDITION OVERVIEW 2.1.
J2EE DEFINITION
J2EE is a group of Java APIs specifications for the development of enterprise applications. The main characteristics are:
Most of the abstractions of the APIs corresponds to interfaces and abstract classes
Exists multiple implementations from different companies, even some Open Source
A application built with J2EE doesn't depend on one particular implementation
Sun defines the J2EE platform like: “The Java 2 Platform, Enterprise Edition (J2EE) defines the standard for developing multitier enterprise applications. The J2EE platform simplifies enterprise applications by basing them on standardized, modular components, by providing a complete set of services to those components, and by handling many details of application behavior automatically, without complex programming. The J2EE platform takes advantage of many features of the Java 2 Platform, Standard Edition (J2SE), such as "Write Once, Run Anywhere" portability, JDBC API for database access, CORBA technology for interaction with existing enterprise resources, and a security model that protects data even in internet applications. Building on this base, the Java 2 Platform, Enterprise Edition adds full support for Enterprise JavaBeans components, Java Servlets API, JavaServer Pages and XML technology. The J2EE standard includes complete specifications and compliance tests to ensure portability of applications across the wide range of existing enterprise systems capable of supporting the J2EE platform. In addition, the J2EE specification now ensures Web services interoperability through support for the WS-I Basic Profile” The most important issue from the Sun definition is that the J2EE is a standard for development enterprise applications, is important to realize that the J2EE fully supports multitier architectures, essential in enterprise applications. Also is important to realize that the J2EE is based on the Java 2 Standard Edition (J2SE) but adds a wide range of enterprise systems such Enterprise Java Beans (EJB).
31 The most important features of the J2EE are: •
Open Source, it’s just a specification.
•
Is a Standard supported by several companies.
•
Is platform independent.
•
Used to build portable, reliable and scalable applications.
•
Supports multitier architectures.
Sun offers three different versions of the Java 2 platform: J2ME (Java 2 Platform, Micro Edition) For devices (e.g.: PDAs) J2SE (Java 2 Platform, Standard Edition) For applications and applets J2EE (Java 2 Platform, Enterprise Edition) Based on J2SE As time passed by, more APIs are been moving to the J2SE.
32
2.2.
MULTITIER ARCHITECTURE
In order to understand how to build enterprise applications we have to take a closer look to the multitier architecture. Usually in an enterprise application we have three components: 1. User Interface (UI) code: This is the presentation layer, it’s the code written to show the information to the user. In case of a Web based interface the code is written to generate dynamically web pages, in case of Java JSP pages are used. 2. Business logic: This is the model layer. This is the code that contents all the application logic. It processes the information fetched from the UI or the database code. 3. Database code: This is the data layer. This code is in charge to communicate with the database in order to get the information and create the objects use by the other layers. We will talk later about the layer architectural pattern, now we focus on the physical structure of an n-tier application. There are two basic architectures in which the database and programmer code are arranged:
client/server (or 2-tier)
multi-tier (or 3-tier or n-tier)
33
2.2.1.
2-tier approach
The Client/Server architecture looks like this:
Figure 1
In this approach the clients have all the code and they access to a database server which is in another computer. This architecture has an important problem, if the model layer or the database changes we have to recompile and reinstall the application in all computers, this is a big problem in enterprise application were the number of clients is very high.
34
2.2.2.
Multitier approach
The 3-tier architecture look life this:
Figure 2
With this approach we insert a server in the middle who has the business logic and the database logic. Using this architecture a change in the model or the database only affects the main server. We can use an n-tier approach by using more middle servers, like in the 4-tier where we separate the business logic and the database logic in to two different servers having a distributed environment.
35 A more complex example could be:
Figure 3
This is an example using the Java 2 Enterprise Edition platform. Here we have different clients that use different UI, some are standalone clients and other are web based clients, then we have the middle tier that takes care of the clients request and finally the database. We will explain later on the J2EE and its different technologies.
36
2.3.
MAIN ARCHITECTURAL PATTERNS USED IN ENTERPRISE APPLICATIONS
There are two main architectural patterns used in the development of enterprise applications: 1. Layers Pattern: This design pattern is essential in order to build scalable and reusable application. This pattern is related to the multitier architecture. The main idea is to logically divide the application in modules or layers, each of them having different function.
PRESENTATION
LOGIC
DATABASE
•
The presentation layer is the part of the application where all the code written for the UI resides. This layer represents the client tier in the 3-tier architecture, if the client is standalone this layer will represent all the classes used to create the interface. If the client is Web based this layer
37 represent the pages or classes use to create the web pages that the user sees in the Web browser. In the case of the J2EE, the JSP pages are commonly used to generate dynamic Web pages, and are the main component in the presentation layer. •
The logic layer represent the business model and is in charge of implement the main functions of the system. It fetch the information from the presentation layer and process the information, if its necessary it will ask the data layer to get some information. Here we will have the main classes of our application. This layer corresponds to the business tier in the 3-layer architecture; the middle server will have the code corresponding to this layer.
•
The data layer will have the code necessary to connect to the database and create the objects used in the second layer. It represents the database layer in the 3-tier architecture.
The main issue here is how the layers communicate with each other. The idea is that one layer only communicate with the lower layer sending request, no bidirectional communication takes place. The upper layer sends a request to the lower layer and gets a response, but the upper layer doesn’t know how this operation was done, it only knows the public interface. So, the communication takes place only from the upper layers to the lower layers, is not allowed to send a request from one lower layer to an upper layer. This approach provides a high level of abstraction and encapsulation allowing the developers to build scalable and reusable applications because we can change the data layer and the logic layer won’t be affected as long as the public interfaces are kept the same. This approach allows us to build reusable software been able to change different modules without affecting the others. For example, we can change the database and the logic layer will not be affected. The business logic layer has all the functionality of the systems and also treats the data independently of its internal representation. This pattern is related to the Facade design pattern that we will discuss later on.
38 2. Model-View-Controller (MVC): MVC was originated in the Smalltalk-80 system to promote a layered approach when developing graphical user interfaces. It emerged in the late 1970s and early 1980. This pattern tell us how the three layers communicate with each other: •
The model handles application and business logic.
•
The view handles presentation logic showing the data to the user.
•
The controller accepts and interprets keyboard and mouse input.
Figure 4
The main idea here is to separate the model (meaning nonGUI) code from its presentation. Later on, we will study Struts, the MVC implementation in the J2EE platform.
39
2.4.
J2EE MODEL
In this section we will analyze the general J2EE model and later on we will go through its different components.
Figure 5
As we can see in the graphic, Sun uses also the layer pattern to describe the J2EE platform. Sun separates the presentation in two parts: the part on the server which generates the web pages and the client part.
40 Now let’s take a general look to each layer: 1. Client-Side Presentation: In the client-side we have the user interface that can be: •
Desktop Client: A standalone client written using Java code.
•
Web based client: In this case the client use a browser to interact with the model. It can be a Java Applet which is a Java application that is downloaded in the client and executed in there. With this approach most of the system functionality is on the client side. Nowadays the tendency is to have clients with barely any functionality and servers with all the system functions, mostly for security and performance reasons. So, nowadays is usually that the client use a browser that receives HTML pages generated dynamically in the server.
•
Other: Other kinds of clients.
2. Server-Side Presentation: In this side we have the main server; this layer is in charge to provide de information to the client. So, here we use a Web server that is in charge of serving Web pages to the client. In the case of a Web based system, the server will use JSP pages or Servlets to generate the view by generating HTML pages dynamically. Later on, we will get more in deep with these two technologies. Communication between Client and Server can take place using various methods: •
HTTP Protocol: The most common way to communicate in a Client/Server web based environment. The server receives a request, processes it and then generates a Web page that is send using the HTTP protocol (TCP Port 80).
41 •
XML: This is a standard way to communicate using text files. Using XML we have a portable way to send information between Server and Client. XML files are easy to manage because they keep the information with a well defined structure and because are text files, all kinds of clients can read the files.
•
Java Remote Method Invocation (RMI): RMI is a technology used to invoke remote objects in a distributed system. Is a high-level solution better than using sockets directly. RMI is only supported by Java but it can be used over IIOP (CORBA).
3. Server-Side Business Logic: On this layer we have the EJB Container who is in charge of manage the EJB. An EJB (Enterprise JavaBean) it is a safe, transactional and maybe persistent object used to implement de business logic. They can be local or remote. We will talk more in detail later on about the EJB because they are the main component in the business logic on the J2EE platform. 4. Enterprise Information System: This is usually a database with the company information.
42
2.5. J2EE TECHNOLOGIES 2.5.1.
JDBC
JDBC technology is an API (included in both J2SE and J2EE releases) that provides cross-DBMS connectivity to a wide range of SQL databases and access to other tabular data sources, such as spreadsheets or flat files. Right now, JDBC current version is 2.0. It’s a technology used at the lower layer to access to the database. The JDBC API makes possible three things: 1. Establish a connection with a database or access any tabular data source. 2. Send SQL statements. 3. Process the results. The design is based in two well know APIs: ODBC (Open DataBase Connectivity). X/OPEN SQL CLI (Call Level Interface). The programmer always works with the java.sql and javax.sql packets. To be able to connect to the DB and to send queries, it is necessary to have an appropriate driver for it: − A driver is usually a .jar file that contains the implementation of all the interfaces of the JDBC API. − Our code never depends on the driver, since always works against the packages java.sql and javax.sql.
43 The package diagram looks like it follows:
Figure 6
44 2.5.1.1.
Types of JDBC technology drivers
JDBC technology drivers fit into one of four categories: 1. A JDBC-ODBC bridge provides JDBC API access via one or more ODBC drivers. Note that some ODBC native code and in many cases native database client code must be loaded on each client machine that uses this type of driver. Hence, this kind of driver is generally most appropriate when automatic installation and downloading of a Java technology application is not important. 2. A native-API partly Java technology-enabled driver converts JDBC calls into calls on the client API for Oracle, Sybase, Informix, DB2, or other DBMS. Note that, like the bridge driver, this style of driver requires that some binary code be loaded on each client machine. 3. A net-protocol fully Java technology-enabled driver translates JDBC API calls into a DBMS-independent net protocol which is then translated to a DBMS protocol by a server. This net server middleware is able to connect all of its Java technology-based clients to many different databases. The specific protocol used depends on the vendor. In general, this is the most flexible JDBC API alternative. It is likely that all vendors of this solution will provide products suitable for Intranet use. In order for these products to also support Internet access they must handle the additional requirements for security, access through firewalls, etc., that the Web imposes. Several vendors are adding JDBC technology-based drivers to their existing database middleware products. 4. A native-protocol fully Java technology-enabled driver converts JDBC technology calls into the network protocol used by DBMSs directly. This allows a direct call from the client machine to the DBMS server and is a practical solution for Intranet access. Since many of these protocols are proprietary the database vendors themselves will be the primary source for this style of driver. Several database vendors have these in progress.
45 2.5.1.2
Establishing a connection
Before a database can be accessed, a connection must be opened between our program (client) and the database (server). This involves two steps: 1. Load the vendor specific driver To ensure portability and code reuse, the API was designed to be as independent of the version or the vendor of a database as possible. Since different DBMS's have different behavior, we need to tell the driver manager which DBMS we wish to use, so that it can invoke the correct driver. An Oracle driver is loaded using the following code snippet: Class.forName("oracle.jdbc.driver.OracleDriver") 2. Make the connection Once the driver is loaded and ready for a connection to be made, you may create an instance of a Connection object using: Connection con = DriverManager.getConnection( "jdbc:oracle:thin:@dbaprod1:1521:SHR1_PRD", username, passwd); The first string is the URL for the database including the protocol (JDBC), the vendor (Oracle), the driver (thin), the server (dbaprod1), the port number (1521), and a server instance (SHR1_PRD). The username and password are your username and password.
46 JDBC is a “low level” technology that is used for other “high level” technologies like EJB. For enterprise applications is not recommendable to use direct SQL queries to the database because it creates a dependency between the database and the application. 2.5.1.3
Concurrence problems with the database
The transactions guarantee that there won’t be any problem if two or more transactions modify common data at the same time. However, depending on the blocking strategy we can have three kinds of problems: 1. Dirty reads: A transaction reads data updated by another transaction, but still not committed. 2. Non-repeatable reads: A transaction rereads data that has changed “magically” from the first reading because of another transaction that has change the value. 3. Phantom reads: A transaction sends again a query and obtains “magically” more lines the second time because another transaction has updated the table. The java.sql.Connection package provides the method setTransactionIsolation that allows to specify the level of wanted isolation:
TRANSACTION_NONE: Transactions not supported.
TRANSACTION_READ_UNCOMMITED: “Dirty Reads”, “non-repeatable reads” and “phantom reads” may occur.
TRANSACTION_READ_COMMITED: “Non-repeatable reads” and “phantom reads” may occur.
TRANSACTION_REPEATABLE_READ: “Phantom reads” may occur.
TRANSACTION_SERIALIZABLE: It eliminates all concurrence problems.
47 The bigger isolation level, the DB does more blocks and there is less concurrence. Not all the drivers/DBs have to support all the isolation levels. Usually supports TRANSACTION_READ_COMMITED and TRANSACTION_SERIALIZABLE. The default isolation level usually is TRANSACTION_READ_COMMITED. So depending, on the operation we have to modify the isolation level.
48
2.5.2 XML EXtensible Markup Language (XML) is an open standard for describing data from the W3C. XML was introduced in 1998 and is used for defining data elements on a Web page and business-to-business documents. XML uses a similar tag structure as HTML; however, whereas HTML defines how elements are displayed, XML defines what those elements contain. While HTML uses predefined tags, XML allows tags to be defined by the developer of the page. Thus, virtually any data items, such as "product," "sales rep" and "amount due," can be identified, allowing Web pages to function like database records. By providing a common method for identifying data, XML supports businessto-business transactions and has become "the" format for electronic data interchange and Web services. The human-readable XML tags provide a simple data format, but the intelligent defining of these tags and common adherence to their usage determines their value. Countless vocabularies have been developed for vertical applications; so many in fact that a universal language was developed to provide a standard for interoperability between them. An XML document is self defining if an XML schema is included in it. Schemas, such as W3C XML Schema, are written in XML and identify the tags and their relationships to each other in the document. Unlike HTML, which uses a rather loose coding style and which is tolerant of coding errors, XML pages have to be "well formed," which means they must comply with rigid rules. These rules allow building efficient parsers. Is important to remember that is a different between upper and lower case.
49 XML and HTML Tags Following are examples of XML and HTML tags. Note that the XML statements define data content, whereas the HTML lines deal with fonts and display (boldface). XML defines "what it is," and HTML defines "how it looks." XML
Maria Roberts 10-29-52 HTML
Maria Roberts October 29, 1952 In theory HTML is a subset of XML specialized in presentation of documents for the Web, while XML is a subset of SGML (Standard Generalized Markup Language) specialized in the administration of information for the Web. XML it contains HTML although not in their entirety. HTML is simply a language, while XML is a metalanguage, this is, a language to define languages.
Figure 7
50 Objectives The main objectives are: •
XML should be directly usable on Internet.
•
XML should support a wide variety of applications.
•
XML should be compatible with SGML.
•
It should be easy writing programs that process XML documents.
•
The number of optional characteristic in XML should be absolutely minimum, ideally zero.
•
The XML documents should be readable for human and reasonably clear.
•
The design of XML should be prepared quickly.
•
The design of XML should be formal and concise.
•
The documents XML should be create easily.
•
The conciseness in the marks has minimum importance.
XML Documents All documents should have a root element. Between the beginning tag and the end there can be other elements or text. Contrary to HTML, is not possible to mix the order of the nested tags. The first element that opens up should be the last one that closes. The following example would not be well formed: < tag-1 > < tag-2 > < /tag-1 > < /tag-2 > An element can have attributes:
The value of the attribute has to go quoted (better with “”)
For a given element, an attribute can only have a value
51 Here is an XML document example:
Some recipes used for the XML tutorial. Beef Parmesan with Garlic Angel Hair Pasta ... Preheat oven to 350 degrees F (175 degrees C). ... Make the meat ahead of time, and refrigerate over night, the acid in the tomato sauce will tenderize the meat even more. If you do this, save the mozzarella till the last minute. ...
52 2.5.2.1
DTDs
A DTD (Type Definition Dates) it allows to specify elements of an XML application: •
How they are nested
•
If they are empty or not
•
The attributes (and their type) of each element
A document is valid if it follows the rules of its DTD. All the parsers require that the documents are well formed, but not all require that they are valid. A more complex parser also verifies that the one document follows its associate DTD.
53
2.5.3 SERVLETS A servlet is a software application written in Java that is executed in the server. The Java Servlet API allows a software developer to add dynamic content to a web server using the Java platform. The generated content is commonly HTML, but may be other data such as XML. Servlets are the Java counterpart to dynamic web content technologies such as CGI or ASP. It has the ability to maintain state after many server transactions. This is done using HTTP Cookies, session variables or URL rewriting. The servlet process is carried out on the server and only the results are send to the client (usually in HTML format). When a browser sends a request to the server, it executes the servlet that processes the request and it generates the appropriate answer that is returned to the client. Servlets Features The servlets has a series of advantages in front of other technologies: •
Execution capacity: The servlets are able to be executed in the same space in the server, this offers certain advantages compare to other technologies like CGI that loads several times in memory to process several user’s requirements. The servlets only need to be loaded once when they are invoked.
•
Compiled: Because they are compiled inside Java, we have binary code as a result (bytecode) that allows the servlets to be executed much more quickly. Also offers advantages like the detection of errors. This makes Servlets more stable, easy to develop and to debug.
54 •
Security: The servlets presents a high degree of security against errors because they are written in Java and executed in a virtual machine (JVM). The Java virtual machine is in charge of checking that all the operations are carried out properly, not allowing invalid operations.
•
Platform Independent: This Java advantage, and because Servlets are written in Java they are also platform independent.
•
Durable: The servlets remains in memory until they are remove in an explicit way. This way, the servlets only needs to be invoked once to serve multiple client requests.
•
Dynamically Executed: The servlets can be loaded dynamically through the net. This assures that the Servlet will not consume the server resources; they are only loaded when they are needed. Although the server can also be a servlet in certain cases.
•
Multithread: Java was designed to be a multithread language. The servlets supports this characteristic, which allows the users to be treated in different threads inside one process. This method requires fewer resources and is executed more quickly than when creating new processes for each request.
•
Protocol Independent: This allows Servlets to support HTTP and also the possibility to use FTP, SMTP or POP3 commands, besides Telnet sessions and other protocols. The API offers a robust support for the usual HTTP functions without sacrificing the capacity to support other protocols.
55 •
Safe: The security of the servlets is based mainly on three facts: −
Because they are implemented in Java, the invalid accesses to memory are avoided; also, type errors are not possible.
−
The servlets uses a Server's security manager reinforcing the security politics.
−
The servlet has access to all the information contained in the client's request. These data used with security protocols like SSL, allows the verification of each client's identity.
•
Written in Java: This feature gives Servlets many advantages like support for the programming guided to objects, strong types confirmation, multithread support, platform independence, etc.
•
Capacity: In a servlet you can use without more difficulty anyone of the elements defined in the API of Java (JDBC, CORBA, JMS, JTS, JNDI, EJB...) and, in general, any class Java made by others.
•
Portability: The servlets are written in Java using a well defined API. A servlet you can execute practically without any change in the container that implements the API.
•
Integration: The Servlets is very integrated with the server. The Servlets can use of the server to obtain absolute path, to carry out loggings, confirmation of permits...
•
Expandable and Flexible: The API of the Servlets is designed so that starting from the basic classes; new classes can be created that carry out functions more or less specific.
•
Free: Practically all the current web servers support servlets
56 As we estate before, a servlet is a Java class that can receive requests (usually HTTP) and generate an output (usually HTML, WML or XML). The servlets that conform a web application are executed in a web container. Each servlet can associate to one or more URLs. The Servlet API defines the expected interactions of a web container and a servlet. A web container is essentially the component of a web server that interacts with the servlets. The web container is responsible for mapping a URL to a particular servlet and ensuring that the URL requester has the correct access rights. A servlet is an object that receives requests and generates a response based on the request. The API defines HTTP subclasses of the generic servlet requests and responses as well as an HTTP session object that tracks multiple requests and responses between the web server and a client. Servlets may be packaged as a Web application. The main packages are javax.servlet and javax.servlet.http.
57 The class diagram look like this:
Figure 8
Figure 9
58 The programmer in order to create a Servlet only needs to write a class which extends from HttpServlet and implement the method doGet or doPost. A simple example could be: import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class HelloWorld extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println(""); out.println("My first servlet"); out.println(""); } } This Servlet, when is called, it generates a dynamic Web page with the message “My first servlet”. In a Java virtual machine (JVM), there’s only one instance of each Servlet that is programmed, and in consequence it can receive only concurrent requests. doGet, doPost, etc. should be thread-safe. A servlet can be implemented like: javax.servlet.SingleThreadModel (marker interface) In this case, the container can create multiple instances.
59 The servlets allows interactions in both directions between client and server, among the possibilities that servlets provide we have:
Dynamic construction and return of a HTML file based on the client request.
Process user's inputs through a HTML form, returning an appropriate answer.
It gives user's certification and other security mechanisms.
Access to resources such server databases to return useful information to the client.
Allow the server to communicate with client's applets using a common protocol maintaining connection open during the whole conversation.
It adds elements automatically like headed or feet, to all the pages returned by the server.
60 Before the JSP pages appear, the main use of the Servlets was to generate the view of an application web: 1. Receive petition HTTP associated to a URL 2. Read parameters 3. Invoke operation on the business model 4. Generate HTML Nowadays, the JSP pages are use to generate the view (HTML) because as we’ll see later on Servlets have many limitations. JSP pages provide better mechanisms to generate dynamically Web content. But still, the Servlets are really important and are usually used as application controllers. So, the main approach right now in the J2EE platform is to use the MVC pattern as it follows: View: JSP Pages. Model: EJB Controller: Servlets.
As we will see later on, the Jakarta Struts MVC Java implementation provides a generic servlet that constitutes the main of the controller.
61
2.5.4 JSP PAGES The main problem with Servlets is that the text generate for the view is mix with Java code and this has some disadvantages: •
It is not possible to use tools for generation of HTML, WML, etc. directly.
•
The text generation needs to be written by a person with knowledge of Java, which is economically very expensive.
•
Changes in the aspect of the graphic interface require recompilation, creation of a new .war file and re-start the server. In an application web, especially in Internet, changes in the graphic interface are very common.
We want to be in a situation were there is a complete job separation: People that work on the graphic aspect like graphics designers or similar with knowledge of graphic design and tools for generation of HTML and WML. People that implement the controller and the model like computer engineering with design and implementation knowledge. Also it should be possible to use the tools directly to design Web pages. Another requirement is that the graphic interfaces updates should not cause the re-start of the server. JSP pages were created to overcome this Servlets limitation on the generation of the view. Servlets are still use as application controllers but JSP pages have substituted them in the view generation. Even, JSP can use Java code (scriptlets), a “tag” approach can be used using technologies like standard tags (JSTL), providing a total separation between the model and the presentation.
62
2.5.4.1
JSP Pages Overview
JavaServer Pages (JSP) it is a group of technologies that allow the dynamic generation of web pages using a mark-up language like HTML or XML, to generate the content of the web pages. It can also mix the mark-up language with Java code using scriptlets. Been part of the Java technology, with JSP we can develop platform independent applications. An important feature is that it allows separating the user interface from the generation of the dynamic content, providing quicker and more efficient development processes. JSP features The characteristics offered by JSP like alternative to the generation of dynamic content for the Web are summarized below: •
Performance improvements: Use of “thin” processes (Java threads) for handling request. The servlet container can be executed as part of the web server.
•
Support of reusable components: By means of the creation, use and modification of JavaBeans in the server, these can be used in JSP pages, servlets, applets or Java applications. A JavaBean is a reusable component (Java class) that encapsulates data in simple and safe way.
•
Separation between presentation code and implementation code: The changes in the HTML code relative to how the data are shown, they don't interfere in the programming logic and vice versa.
63 •
Labour Division: The Web pages designers can be centred in the HTML code and the programmers in the logic of the program. The developments can be made independently. The frequent modifications of a page are carried out this way more efficiently.
•
Important back of the solid Java technology.
At the moment, there are different technologies that compete with JavaServer Pages. But JSP have a series of advantages regarding to these technologies: •
Active Server Pages (ASP): ASP is a similar technology created by Microsoft. JSP has several advantages. First, the dynamic part is written in Java, not in Visual Basic Script, or another specific language of Microsoft, for that reason is much more powerful and easier to use. Second, it is portable to other operative systems and Web servers. We will discuss these issues more in detail later on.
•
Servlets: JSP doesn't provide us anything that we were not able to do with a servlet. But it is much more convenient to write (and to modify) normal HTML than to have to make a trillion sentences “println” to generate HTML. Also, separating the content format can put different people on different tasks: The experts in Web pages design can develop HTML pages, leaving space so that the servlets programmers insert the dynamic content.
•
Server-Side Includes (SSI): SSI is a broadly supported technology that includes externally defined pieces inside a static Web page. JSP is better because it allows us to use servlets instead of a separate program to generate the dynamic parts. Also, SSI, it is really designed for simple tasks; not for real programs that use data forms, make connections to databases, etc.
64 •
JavaScript. JavaScript can generate dynamically HTML on the client side. This is a useful capacity, but it only manages situations where the dynamic information is based on the client's environment. With the exception of the cookies, HTTP and sending forms are not available with JavaScript. And, because it is executed in the client, JavaScript cannot access to the resources in the server side, as databases, catalogs, etc.
2.5.4.2
JSP Use
To be able to use this technology it is necessary a web server that support HTML pages, and code that implements a JSP container where we can execute the JSP labels. Most of web servers are written in traditional programming languages, compiled in native code because of efficiency reasons. For these servers it is necessary to add supplementary code that implements the JSP container. Server API’s have been provided to extend servers functionality. The Apache server has modules. In the old versions it was necessary recompile the server code to support a new module, nowadays they are loaded dynamically being based on configuration files. Once the JSP container has been installed and configured, the .jsp files are treated the same as the .html files, locating them in any place of the directory hierarchy. Although the JSP specification doesn't presuppose anything on the implementation of this technology, most of the available implementations are based on Servlets, this mean Java language. It’s important to realize that the JSP specification doesn’t require that JSP are implemented using Servlets (Java language). There are several JSP containers in the market, Tomcat is a well know free JSP container widely use on the market and is part of the Jakarta project.
65 The first component of the implementations based on servlets, is a special servlet denominated page compiler. This servlet with their associated Java classes, it is known as JSP container. The container is configured to call to the page compiler for all the .jsp pages requests. His mission is to compiling each .jsp page in a servlet whose purpose is generating the dynamic content specified by the original .jsp document. To compile a page, the page compiler scans the document searching for JSP labels, generating the corresponding Java code for each of them. The static HTML labels are converted to Java strings. The labels that make reference to JavaBeans are translated in the corresponding objects and methods calls. Once the code of the servlet has been created (its service() method has been coded), the page compiler calls to the Java compiler to compile the source code and add the file of the resulting bytecodes to the appropriate directory on the JSP container. Once the servlet corresponding to the .jsp page has been generated, the page compiler invokes the new servlet to generate the answer for the client. While the code of the page .jsp doesn't lose temper, all the references to the page will execute the same servlet. This supposes a certain delay in the first reference to the page, although mechanisms exist in JSP for precompile the .jsp page before the first petition has taken place.
66 The main packages are javax.servlet.jsp y javax.servlet.jsp.tagext.
Figure 10
67
2.5.4.3
Language Syntax
The source code of a JSP page includes: 1) Directives: Group of labels that contain instructions for the JSP container with information about the page in which they are. They don't produce any visible output, but they affect to the global properties of the .jsp page that have influence in the generation of the corresponding servlet. 2) Script Elements: They are used to encapsulate Java code that will be inserted in the corresponding servlet of the .jsp page. 3) Comments: They are used to add comments to the .jsp page. JSP supports multiple styles of comments, including those that comments in the HTML page generated as answer to the client's request. 4) Actions: They support different behaviours. They can transfer the control among pages, applets and interact with JavaBeans on the server side. JSP labels can be personalized to extend the functionalities of the language.
68 2.5.4.3.1
Directives
1) Page: Information for the page. Multiple directives can be include in a .jsp page. It’s not possible to repeat the use of an attribute in the same directive neither in others of the same page except for import. The attributes that are not recognized will generate an error during the execution (the name of the attributes is sensitive to uppercase and minuscule). <% @ page attribute1=”value1” attribute2=... %> 2) Include: It allows to include the content of another .html or .jsp page. It can be used to include the common head and foot of pages. <% @ include file=”localURL”% > 3) Taglib: This directive is used to notify to the JSP container that the page will use one or more libraries of personalized labels. A labels library is a collection of personalized labels that can be used to extend the basic functionality of JSP. <% @ taglib uri=”tagLibraryURI” prefix=”tagPrefix”% >
69 2.5.4.3.2
Script Elements
1) Declarations: They are used to define variables and specific methods for a .jsp page. The variables and the declared methods are accessible for any other script element of the page, although they are coded before the own declaration. The syntax is: <%! declaration (fi)% > 2) Expressions: They are bound to the contents generation. They can be used to print values of variables or results of the execution of some method. All result of an expression is converted to a String before being added to the page. The expressions doesn’t finish with “;”. <% = (hours < 12)? “AM”: “PM”% > 3) Scriptlets: They can contain any type of Java sentences, being able to leave open one or more blocks of sentences that will be closed in labels of later scritplets. Sentences like if-else, while and do/while can be included. <% scriptlet% >
70 2.5.4.3.3
Comments
1) Content comments: This type of comments will be included in the output of the .jsp page, and therefore they will be visible in the source code that arrives to the client. It is the standard type of comment for HTML and XML. You can include dynamic content in the comment (JSP expressions), and the value of the expression will appear like part of the comment in the client. 2) Comments: They are independent of the content type of the page and the script language used; these comments can only be seen examining the original .jsp page. <%--comment--% > 3) Script language comments: They can be introduced inside the scriptlets or the JSP expressions, using the native comments of the syntax of the script language. These comments won't be visible for the client, but they will appear in the servlet of the corresponding .jsp page. <% / * comment * /% >
71 2.5.4.3.4
Actions
1) Forward: It is used to transfer the control of a .jsp page to another localization. Any code generated until the moment is discarded, and the request process begins in a new page. The client browser continues showing the URL of the initial .jsp page. The value of the parameter page, it can be a static document, a CGI, a servlet or another JSP page. To add flexibility to this parameter, you can build their value like concatenation of values of different variables. It can be useful to pass pairs (parameter/value) to the destination of the label, for this we use < jsp:param... / >. < jsp:forward page=”localURL” / > 2) Include: It provides a simple form of including content generated by another local document in the output of the current page. In opposition with the label forward, include transfers the control temporarily. The value of the attribute flush, determines if the buffer of the current page should be emptied before including the generated content by the included program. As in the previous case, you can complete this label with the use of < jsp:param > to provide additional information to the called program. < jsp:include page=”localURL” flush=”true” / > 3) Plug-in: The purpose of this label is to generate specific HTML code for the client's browser when applets are invoked that use the Sun Plug-in. 4) Beans: It provides three different actions to use with JavaBeans on the server side: < jsp:useBean >, < jsp:setProperty > and < jsp:getProperty >.
72 2.5.4.4
JavaBeans
Javabeans are reusable components, usually Java classes, whose attributes represent the information of a data type (the attributes of a concrete entity of the database) and it has methods setAttribute and getAttribute to assign or to obtain the data of the attributes since they will be private in order to hide data, so they won’t be modified. The characteristics of a Bean are the following: 1. They need to have a constructor without parameters (by default). 2. The attributes should be private. 3. The access methods to the attributes should begin with set or get. 4. They should be serializable, since they are objects that will send among .jsp pages or from a Servlet to a .jsp page. The JavaBeans and the .jsp pages are related since JSP has labels for the creation and access to the beans. The JavaBeans can be in four different environments: •
Page: o Bean only visible in this page (it is destroyed at the end of each execution). o Bean hooked as attribute in javax.servlet.jsp.PageContext.
•
Request: o Bean hooked as attribute in javax.servlet.ServletRequest.
•
Session: o Bean hooked as attribute in javax.servlet.http.HttpSession.
73 •
Application: o Visible to the whole application web. o Bean hooked as attribute in javax.servlet.ServletContext.
javax.servlet.jsp.PageContext, javax.servlet.ServletRequest, javax.servlet.http.HttpSession and javax.servlet.ServletContext are environment variables that the JSP Container controls. Note that the javax packet is the implementation of the JSP specification and is provided by the JSP container, for example, Tomcat.
74 2.5.4.5
JSP example
This is the “Hello world” JSP example:
JSP page <%@ page language="java" %> <% out.println("Hello World"); %> As we can see in the example, with JSP we can mix HTML code with Java code. Although, like we state before, this is not a good approach and is only valid for small applications. The first line is a directive telling the container that the language use in the scriptlet is Java and the second line is Java code that prints the “hello world” message.
75 2.5.4.6
JSP Architecture
Before Struts and EJB appear the model used was: Servlets (or JSP pages) as controllers. JSP pages for the view JavaBeans for data access. DB
CAPA 2 Controller
REQ
CLIENT BROWSER RES
H T T P
CAPA 3 Data Model
SERVLET
create CAPA 1 View
JavaBean
JSP
DB
The usual steps were: 1. Client sends a request via HTTP protocol. 2. The request is taken by the controller, usually a servlet. 3. The controller will take care of the request and will create a JavaBean with the info for the response taken from the database. 4. The controller will call the JSP page that will generate the HTML page with the JavaBean information. 5. The HTML page is send back to the client with the response.
76 A usual architecture was:
CLIENT BROWSER
HTTP
APACHE SERVER
HTML PAGES VIEW
JAVASCRIPT
JSP PAGES
TOMCAT
USE
SERVLETS (LOGIC)
CREATE
JavaBeans DATA
JDBC
DB
The web server (like Apache) was in charge of serve the HTML pages to the client. Tomcat (JSP container) was in charge to create the servlets corresponding to the JSP pages in charge of the view. The Servlets had the application logic and were in charge of creating the JavaBeans that were use for the JSP pages to show the information to the client. As we can see, with this approach the layers pattern was implemented not letting the JSP pages (View) create the JavaBeans, the Servlets (Model) were in charge to do that using the information stored in the database. The Servlets will access using the JDBC technology.
77 So, the programmer was in charge to manually implement the MVC pattern. There were two main problems with this approach: 1. The elimination of Java code from the view code was really hard to achieve and at the end there was always some Java code in the .jsp pages, usually to show an array of JavaBeans or other operations that required some logic in the view. 2. In big applications like enterprise application they were many troubles to implement persistence with the JavaBeans and also the Servlets were too much overloaded causing many troubles for the programmer and ended with a low quality product. Struts were created to solve the first problem giving a good implementation of the MVC pattern having Servlets as controllers and JSP pages for the view; giving also labels to avoid Java code on the view. Also, the Java Standard Tag Library (JSTL) and the JSP 2.0 were created for the same reason. Enterprise Java Beans appear to solve the second problem and take care of the model on enterprise applications. We will discuss these technologies later on. So this approach is only good for small application and the Struts-EJB approach should be use for bigger and more scalable applications.
78 2.5.4.7
JSP vs. ASP
Few years ago it was easy to choose a server-side language as CGI used to be only the only scripting language available. But in due course of time, the developers found out that CGI scripts were inefficient and it was very difficult to write server extensions as we saw before. At that time, Microsoft came up with Active Server Pages (ASP), which allows developers to use simple scripting to access the server and its extensions. But ASP had some disadvantages. It limits you to work on Microsoft platforms, and the simplest of mistakes in the script can cause the server to crash or hang, effectively bringing down your website. In response to ASP, Sun Microsystems gave the world Java Server Pages (JSP) technology, which is entirely based on Java programming language. Internally, JSP pages are dynamically converted into Servlets, which are simply Java classes. This means JSP enjoys all the capabilities that Java programming supports. JSP is a great deal more efficient than many other scripting languages, such as CGI and ASP. Tags can be defined in tag libraries and then used within any JSP page. This makes for a better separation of page content from its code, which leads to less scattered code and hence, the site is easier to maintain. Global changes need to be made only to the tags defined in these tag libraries, making time-consuming, page-by-page fixes things of the past. JSP and ASP can be use, more or less, to develop the same type of web applications. However, they have many differences. Platform and server independence JSP follows the philosophy of the JAVA architecture of “write once and execute where you want." The installation of ASP is limited for architectures based on Microsoft technology.
79 This way, with JSP you can execute you web application in any operating system or in most popular web servers, as for example Apache, Netscape or Microsoft IIS. While ASP only has native support for IIS and Personal Web Server that are the two web servers for Microsoft systems, the first one with technology NT and the second for Windows 98 systems and similar. Open Source The JSP API benefits of the extended JAVA community, on the other hand the ASP technology is specific of Microsoft that develops its processes internally. Tags While both, JSP as ASP use tags and scripts to create dynamic web pages, the JSP technology allows developers to create new tags. The developers can create this way, new tags and not to depend so much on the scripts and avoid mixing view code with logic code allowing the separation between presentation and model layers. Reusability The JSP components are reusable in different platforms (UNIX, Windows). The advantage of Java The JSP technology uses Java as Script language while ASP uses VBScript or Jscript. Java is a language more powerful and scalable than Script languages. The JSP pages are compiled in Servlets that can use all the Java libraries available. Java makes the work of the easiest developer and helps to protect the system against the errors while the ASP applications has more than enough with the NT systems cause they are more susceptible of errors.
80 Maintenance The applications that JSP uses have an easier maintenance that those that ASP uses. •
The Script languages are well for small applications, but they don't fit well for big applications. Java is a structured language and big applications are easier to develop and maintain.
•
The JSP technology makes bigger emphasis in the components that in the Scripts, this makes JSP easier to revise the content without it affects the logic or to revise the logic without changing the content.
Conclusion The advantages on using the Java JSP technology instead of Microsoft (ASP) are diverse and interesting. However, ASP has also some advantages:
Support to various programming languages. JSP is based only on Java technology.
Easy to learn. There are other technologies available in the market but are not suitable for developing enterprise applications:
CGI: This technology now is obsolete. It was the first technology used to generate HTML pages dynamically. But it has many disadvantages; the main one is that it creates a new process on each request needing too much server resources.
PHP: This technology is widely use on internet and is part of the LAMP platform. As we state before this technology is not suitable for enterprise applications because, among other problems, it’s based only on script language.
81
2.5.4.7.1
Examples
We can see now the differences on the code of both technologies. ASP (using JScript): <%@ LANGUAGE = JScript %>
Simple Scripting Tricks Anyone can count like this:
<% for (i = 1; i < 6; i++) { Response.Write(i + "
"); } i = 1000000; %> It would take a long time, however, to count to <%= i %>.
JSP: <%@ page language="java" %>
Simple Scripting Tricks Anyone can count like this:
<% for (int i = 1; i < 6; i++) { out.println(i + "
"); } i = 1000000; %> It would take a long time, however, to count to <%= i %>.
82
2.5.5 JSP 2.0 JSP 2.0 is an upgrade to JSP 1.2 with several new and interesting features that make the life of web application developers and designers easier. The objective of JSP 2.0 is to make JSP easier to use than ever, and more importantly to be used without having to learn the Java programming language itself, thank to the new expression language no more Java code is needed in the JSP. JSP were incorporate in the J2EE 1.4. The JSP 2.0 specification has the next features: •
The Expression Language first introduced by the JSTL 1.0 (Java Standard Tag Library) specification is now incorporated in the JSP specification, making it available for use with all standard and custom components, as well as in template text.
•
The EL has been extended with a function call mechanism that JSTL 1.1 takes advantage of to make a set of commonly needed functions readily available.
•
JSP error pages now have access to more information about the error, through new variables that are better aligned with the error-handling mechanism defined by the servlet specification.
•
The requirements for how containers report JSP syntax errors have been made stricter to make it easier to find out what's wrong.
•
All J2EE 1.4 specifications, including JSP 2.0 and Servlet 2.4, use XML schema for declaration of the deployment descriptor rules. One benefit of this is that you can now list the declarations in the web.xml file in any order. JSP 2.0 also adds a number of new configuration options to the deployment descriptor, to allow for global configuration instead of per-page configuration.
•
Writing JSP pages as XML documents is now much easier, thanks to more flexible rules and new standard action elements.
83
• Custom tag libraries can now be developed as a set of tag files (text files with JSP elements), and tag handlers implemented as Java classes can use a new, simplified tag handler API. At the same time, a number of new features, such as support for a dynamic attribute list and executable fragment attributes, have been added. Compatibility with JSP 1.x : •
A JSP 2.0 container has to be able to execute applications with JSP 1.x syntax.
•
Is possible to migrate a JSP 1.x application to JSP 2.0 syntax page to page. 2.5.5.1
Expression Language (EL)
In JSP 1.x if you want to set a value to an attribute of a tag, is necessary to use an expression <% =... %>. Example: < jsp:useBean goes = " shoppingCart " scope = " session " class = " org.acme.ShoppingCart " / > < xxx:if test =" <% = shoppingCart.getNumberOfProducts () > 0% >" > ... < /xxx:if > JSP 2.0 provide with the EL facilitate their construction. Example: < xxx:if test =" ${sessionScope.shoppingCart.numberOfProducts > 0}" > ... < /xxx:if > The expressions have to be surrounded for ${}. Any value that doesn't begin with ${, it is considered a literal. Here are some examples of access to attributes of Java objects:
84 ${user.firstName} = user.getFirstName() ${user.address.city} = user.getAddress().getCity() ${user.preferencesMap["shipping"]} = user.getPreferencesMap().get("shipping") ${user.preferencesList[0]} = user.getPreferencesList().get(0) This example show how to access to a JavaBean using the JSP 2.0 EL. The object is user, and instead of have to write scriptlets using Java code like on the right we can use the Expression Language provided by JSP 2.0.
85
2.5.6 JAVA STANDARD TAG LIBRARY (JSTL) JSTL got born with the intention of compile in one standard the most used Tag libraries that were circulating on the net. Basically they were for: − Iterate over collections. − Print values of JavaBeans properties in a safe way. − Internationalization of messages, numbers, dates, etc. − URLs generation applying URL rewriting. − Access to XML documents. − Etc The JSTL specification was development under the auspice of the JCP (Java Community Process). The JCP is a process supervised by SUN but open to companies, and particular individuals that guides the development and approval of the standards for the Java language. At the present time the JCP has 700 participants. The JSTL 1.0 specification was finished the 11th of July 2002. Some days later the first implementation created by members of the Taglibs project of the Apache foundation appeared. The last JSTL version nowadays is it is 1.1, implemented by the Taglibs project. JSTL is optional in J2EE 1.4.
86 JSTL provides:
Five libraries of JSP labels: o Common functions for iteration over data, conditional operations, and import of other pages (Core Tags). o Internationalization and text format (I18n Tags). o String manipulation functions. o XML process (XML Tags). o Access to databases (the use if this tag is only recommended for small applications or prototypes).
An expression language to index objects and their properties without necessity of Java code.
Tag Library Validators (TLVs)
JSTL requires a JSP 2.0 container.
87
2.5.7 JAKARTA STRUTS Struts is a tool for the development of applications Web under the MVC patron using the J2EE platform. Struts is developed like part of the Jakarta project of the Apache Software Foundation. The original author was Craig R. McClanahan. Struts allows to reduce the development time, been free software and its compatibility with all the platforms where J2EE is available, it transforms it into a highly available tool. It is a framework that implements the MVC architecture pattern in Java. It works on any application server that implements the APIs servlets and JSP A framework is the extension of a language by means of one or more classes hierarchies that implement a functionality and (optionally) they can be extended. The framework can involve TagLibraries. As we mention before, the MVC architecture pattern (Model-View-Controller) is a pattern that defines the independent organization of the Model (Objects of Business), the View (interface with the user or another system) and the Controller (controller of the workflow of the application).
88 The MVC pattern architecture look like it follows:
Figure 11
89 2.5.7.1
MVC in web applications
The browser generates a request that is handled by the Controller (a specialized Servlet). The Servlet is in charge of analyzing the request, follow the configuration that has been programmed in the XML and call the corresponding Action (A java class that is used to access to the model) passing the corresponding parameters. The Action will instance or use the business objects (EJB) and they will do the task. Depending on the result of Action, the Controller will redirect to one or more JSP pages, which will be able to access the objects of the Model in order to carry out its task.
STRUTS
1. Request
CONTROLLER
2. Action
(Servlet) 3. Results WEB BROWSER
MODEL
4. Redirect
6. Result
(EJBs)
5. Uses VIEW (JSP/TagLibs)
So, Struts is basically the implementation of the View and Controller from the MVC pattern. It also implements the gateway between the controller and the model using the classes Action.
90 So, as we mentioned before, Struts is a framework that gives support to implement the View and Controllers layer of a Web application; it also provides: •
A Servlet Front Controller and related classes.
•
Template system.
•
Parameters validation.
•
JSP Tag Library.
The Servlet Front Controller pattern is the key of Struts implementation providing the basic structure of the MVC pattern. It is important to remember that Struts also provides a Tag library that can be used instead of the JSTL to generate the view; but it is also possible to use both at the same time. Struts Tag library provides the following type of Tags: •
Bean: − Print the value of the JavaBeans properties in a safe way. − Support for internationalization of messages.
•
Logic: − Flow control.
•
HTML: − Basic HTML generation: o Form inputs. o URL rewriting.
91 •
Tiles: − Implementation of the Composite View pattern. o Template systems for JSP pages. − It replaces Template. o Template systems was used with Struts 1.0
It is recommendable not to use the Bean and Logic Tags because JSTL provides the same type and it is a standard. In the other hand, Tiles is a powerful tool and it can be use along with JSTL. So, to generate the view we can use Struts+JSTL Tags.
92 2.5.7.2
Servlet Front Controller pattern
The Servlet Front Controller pattern that Struts implements is show bellow:
Figure 12
93 Let’s take a look to each class of the Struts MVC implementation: •
ActionServlet. o It’s the Servlet Front Controller. o In web.xml file is specified that all the URLs that imply process (GET or POST) are redirect to this servlet.
•
E.g.: URLs that finishes in .do
ActionForm Classes. o If the programmer wants it, can access to the request parameters through a JavaBean that extends from ActionForm.
•
Specially useful in forms.
Action Classes (method execute). o It access to the request parameters, directly or via the corresponding ActionForm. It carries out the operation invoking a method from the model. Usually the Session Facade of the model. The Session Facade is a design pattern that will discuss later on. o It leaves the result returned by the method in the request or in the session. o It returns an ActionForward object that represents the URL that is necessary to visualize next (sendRedirect or forward).
94 2.5.7.3
Model View Controller architecture using Struts
Model: o Independent classes from the view and the controller. Controller: o Group of Action classes. o Interact with the model and select the next view (leaving the data in one of the four possible environments, usually request or session) View: o Group of ActionForm classes. o Group of JSP pages. o They don’t contain Java code. o They only visualize data. o They use JSP actions to recover the values to show and to format.
95 2.5.7.4
Struts Example
On this section we will show an example using Struts to help to understand this framework and to see how easy is to create a MVC pattern architecture. This example helps to understand the most tedious part which are the configuration files. First, after install the JSP container, for example Tomcat, we download from http://jakarta.apache.org the Struts implementation. Then, inside the WebApp directory we create the web.xml file with the main configuration.
Figure 13
96 A standard configuration could be:
index.jsp index.html index.htm After this, we need to modify the server.xml file to include the WebApp:
Figure 14
97 We create a basic HTML page as main page (index.html) and we have our Web Application. Now we can begin to add the components of Struts. We decompress the file and we should copy struts.jar file inside Tomcat library.
Figure 15
We should also create a file struts-config.xml and to modify the file web.xml to add the struts tag-libs:
/WEB-INF/struts-bean.tld /WEB-INF/struts-bean.tld /WEB-INF/struts-html.tld /WEB-INF/struts-html.tld /WEB-INF/struts-logic.tld /WEB-INF/struts-logic.tld
98
/WEB-INF/struts-template.tld /WEB-INF/struts-template.tld And to configure the Front Controller Servlet (ActionServlet):
action org.apache.struts.action.ActionServlet application ApplicationResources config /WEB-INF/struts-config.xml debug 2 detail 2 validate true 2 action *.do
99 Now we can start writing our actions. We can create the following class with the first action: import java.io.*; import java.util.*; import javax.servlet.*; import javax.servlet.http.*; import org.apache.struts.action.*; import org.apache.struts.util.*; public final class accionBasica extends Action { public ActionForward perform(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { request.setAttribute("user","example"); // Forward control to the specified success URI return (mapping.findForward("home")); } } Then we tell the system how to map the request to this action using the struts-config.xml file:
Finally, we create the JSP page the way we want. To execute we have to start Tomcat and then go to next URL: http://localhost:8080/struts-blank/Exaction.do
100
2.5.8 DISTRIBUTED APPLICATIONS A distributed application is an application whose procedure is distributed by multiple computers on a net. The distributed applications are at the same time capable to serve multiple users and, depending on their design, to make a more appropriate use of the resources. The organization of a distributed system is shown in the following figure:
USER INTERFACE LEVEL
INFORMATION PROCESS LEVEL
DATA STORAGE LEVEL
The natural progress of the software development consists on creating applications that are distributed on the net. The future distributed applications will be made up of many objects that will be distributed in several computers. There are several approaches and standards at the moment that give support to the development of distributed applications, establishing the communication outline and distribution of the different components in the net. Many enterprise applications works on a distributed system having different modules working on different machines; understanding distributed applications are crucial to develop enterprise applications. Next, the different solutions for the design and implementation of distributed applications are detailed.
101 2.5.8.1
Distributed Applications on Internet
The popularity of Internet has made grow the distributed applications that are executed on a structure. These first generation applications admit communication based on specific application protocols like HTTP, FTP... 2.5.8.2
Intranet Applets
In an intranet environment, the corporate information systems admit services that adapt to the organizational necessities of the company. These intranet services can be implemented by Client/Server services, as a company Internal Web. The Java applet paradigm offers the possibility to execute the client interface layer and part of the information process layer. 2.5.8.3
Distributed Computation Environment (DCE)
The Distributed Computation Environment (DCE) constitutes another focus for the construction of distributed applications. It was developed by the Open Software Foundation that now is call you Open Group (http://www.opengroup.org). DCE integrates a series of services and fundamental technologies to build distributed applications. The distributed systems are organized in cells that are groups of resources, services and user process that admit common functions and they share a group common DCE services. The DCE provides intermediate support, since it is not an autonomous product, is a services package that is integrated in an operating system.
102 The services and technologies that DCE uses in a cell are the following: − Directory Services (CDS and GDS): They store the names of the resources that are available inside the distributed environment. − Distributed Files Service (DFS): It provides a file system that operates in all the computers in a cell. − Distributed Time Service (DTS): It is used to synchronize the hour in all the computers in a cell. − Remote Procedure Call (RPC): They replace the TCP sockets like basic mechanism for the communication. − DCE Threads: They are thin processes that simplify the design of Client/Server applications.
Figure 16
103 2.5.8.4
Distributed Component Object Model (DCOM)
The Pattern of Distributed Component Object Model (DCOM) it is the Microsoft solution for the development of distributed systems. The DCOM is based on COM that constitutes the nucleus of Microsoft object oriented development strategy. COM is the result of the Microsoft Object Linking and Embedding (OLE) technology that allowed to admit compound documents, documents that could manage multiple applications. The COM objects are instances of classes and they are organized in interfaces (simple collections of methods). The COM objects can only be accessed thru his methods, and each object it is implemented inside a server. A server can be a .dll file, an independent process or an operative service. COM avoids the details of the implementation and it presents an unique and uniform interface for all the objects, independently how each one is implemented. The interface language definition that is used to define the interfaces and methods of COM comes from DCE. DCOM is in essence the COM distributed on multiple computers. The communication among machines is carried out through RPC of objects, or ORPC, The ORPC is based on the Microsoft RPC that is in essence, the RPC of the DCE. The ORPC can be configured to use a series of transport protocols, but it works better with UDP.
104 Although DCOM is a Microsoft product, it constitutes an open standard that has been transported to other operative systems like UNIX. Microsoft tries that the DCOM becomes a solution of crossed platform for the development of distributed applications, although at the moment has not been very successful. The Java development kit of Microsoft includes a JVM and an API that provides an interface to the COM and DCOM. Here is an example of the DCOM architecture:
Figure 17
105 2.5.8.5
Common Object Request Broker Architecture (CORBA)
The Common Object Request Broker Architecture (CORBA) offers another approach to the construction of distributed systems. CORBA, like the DCOM but contrary to the DCE, it is object oriented. It allows the objects of a computer invoke the methods of objects of other computers. CORBA, contrary to DCOM, is an open solution and it is not linked to any operating system. CORBA uses the objects that are accessible through the Object Request Broker (ORB). The client interface to the ORB is an adapting fragment that is written in Interface Definition Language (IDL). The adapting fragment it is seen as a local proxy of the remote object, providing a mechanism of independent language programming to describe the methods of an object.
Figure 18
106 CORBA instead of depending on clients and monolithic servers (like browsers and Web servers), the applications can be distributed on several hosts. The advantages that CORBA has are the following:
It provides a true OO focus for the development of distributed applications.
It is independent of the language. You can use CORBA to connect objects develop in any programming language.
It is recognized as an international standard and is admitted by almost all the main companies.
Figure 19
107
2.5.8.6
Java Remote Method Invocation (RMI)
The distributed object model that Java uses allows objects executed in a JVM, invoke methods of objects that are executed in another JVM. The object that makes the invocation is denominated client object or local object, while the object whose method is invoked is denominated server object or remote object. A client object never makes direct reference to a remote object; it uses a remote interface that the remote object implements (adapter fragment). This allows compiling the client objects using the remote interface, eliminating the necessity that the files with the classes of the server are present locally during the compilation process. Besides from the remote interfaces, the model uses classes belonging to the adapting fragment and to the skeleton. The client interface invokes the methods of the fragment local adapter object. The local adapting fragment communicates these methods invocations to the remote skeleton, while this last one invokes to the methods of the server object.
Figure 20
108 The transport layer uses TCP sockets by default to communicate with the skeleton of the server, although other protocols can be used like SSL and UDP. To access to a server object, this should register by remote registration. The remote registration is a process that is executed in the server and it is created executing the program rmiregistry (JDK tool). To be able to carry out this operation it should be active the Java RMI System of Activation Demon in the remote system (tool rmid of the JDK). So when an client object passes an argument as part of the method remote invocation, the argument type will be serializable (all the Java primitive types are serializable, and also all the classes and interfaces that implement the Serializable interface of the package java.io). A class is serializable when it can be converted to a series of bytes, so it can be transmitted, for example, over a network. When a local object is passed like argument to a remote method invocation, the local object will be copied from the local JVM to the remote JVM. The variables will only be copied if they are not static or transitory (declared without the static or transient modifier). The characteristics that should complete a distributed application that is implemented using RMI are the following:
The class of the remote object should implement an interface that extends Remote interface. This interface should define the methods that the object will allow to be invoked. These methods should throw the RemoteException.
The class of the remote object should extend the class RemoteServer. This is usually made extending the subclass UnicastRemoteObject of RemoteServer
The adapting fragment and skeleton classes of the remote object should to be created by using the compiler rmic. The adapting fragment should be distributed to the client's host.
109
The class, interface and the skeleton of the remote object, should be in the CLASSPATH variable of the remote host.
The daemon of remote activation and the remote register should be activated.
An instance of the remote objects should be created, and it should be registered in the remote registration. The methods bind() and rebind() of the class Naming are use to register an object with their associate name. The remote object should install a security administrator to allow the load of the RMI classes.
Figure 21
110 Now let’s take a look of an example of a distributed client/server calculator using RMI: 1. First, we create the interface that extends from the Remote interface with the public methods that we want to make public available. import java.rmi.*; public interface ServOper extends Remote { int sum(int x, int y) throws RemoteException; int minus(int x, int y) throws RemoteException; int multiply(int x, int y) throws RemoteException; int divide(int x, int y) throws RemoteException; } 2. Then, we create the class which implement the interface. This class extends from UnicastRemoteObject import java.rmi.*; import java.rmi.server.*; import java.rmi.registry.*; public class ServOperImpl extends UnicastRemoteObject implements ServOper { static String hostName="localhost"; public ServOperImpl() throws RemoteException { super(); } public int sum(int x, int y) throws RemoteException { return x + y; } public int minus(int x, int y) throws RemoteException { return x - y; }
public int multiply(int x, int y) throws RemoteException { return x * y;
111 } public int divide(int x, int y) throws RemoteException { return x / y; } public static void main(String args[]) { System.setSecurityManager(new RMISecurityManager()); try { LocateRegistry.createRegistry(1099); // Default RMI port ServOperImpl serv = new ServOperImpl(); Naming.rebind("//" + hostName + "/ServOp", serv); System.out.println("Correct!!"); } catch (Exception ex) { System.out.println(ex); } } } 3. Finally, we write the client class. import java.rmi.*; public class ClientOper { static String hostName="localhost"; public static void main(String args[]) { try { ServOper serv = (ServOper) Naming.lookup("//" + hostName + "/ServOpe"); System.out.println("Executing 3 + 5 -> result: " + serv.sum(3, 5)); System.out.println("Executing 3 - 5 -> result: " + serv.minus(3, 5)); System.out.println("Executing 3 * 5 -> result: " + serv.multiply(3, 5)); System.out.println("Executing 3 / 5 -> result: " + serv.divide(3, 5)); } catch (Exception ex) { System.out.println(ex); } } }
112 2.5.8.6.1
Java RMI as a technology for development enterprise applications
We will discuss now the positive and negative aspects of using Java RMI to develop enterprise applications. Positive aspects: •
It allows separating the view and the controller physically from the model in a simple way. o Advantages of the 3 layers architectures.
•
It can work over IIOP o A client CORBA can access to a Java RMI object.
Negative aspects: •
Scalability o We would like to have a solution that allows to reply the model layer in several machines, transparently to the developer.
•
Security o We would like to have a solution that allows to specify what roles can invoke certain methods of an remote object.
•
Transactions o We would like to have a solution that hides the transactions API. o We would like to have a solution that allows distributed transactions.
113 •
Persistence o We would like to have a solution that automates the persistence of the objects in the persistent domain. It would not be necessary to program DAOs[1] (Data Access Object).
It decreases the development time.
It maximizes the portability (the software doesn't depend on the database type).
To help developers to overcome these difficulties the Enterprise JavaBeans were introduce.
[1] DAO (Access Object Dates): Is a design pattern used to access to the Objects Valued (VO) with the intention of uncouple the business logic from the data logic.
114
2.5.9 JAVA NAMING AND DIRECTORY INTERFACE (JNDI) JNDI is a Java technology used in distributed environment base on Java applications. Naming and directory services play a vital role in intranets and the Internet by providing network-wide sharing of a variety of information about users, machines, networks, services, and applications.
Figure 22
A naming service maintains a set of bindings. Bindings relate names to objects. All objects in a naming system are named in the same way. Clients use the naming service to locate objects by name. There are a number of existing naming services, we will describe the most useful ones: 1. COS (Common Object Services) Naming: The naming service for CORBA applications; allows applications to store and access references to CORBA objects. 2. DNS (Domain Name System): The Internet's naming service; maps peoplefriendly names (such as www.etcee.com) into computer-friendly IP (Internet Protocol) addresses in dotted-quad notation (207.69.175.36). Interestingly, DNS is a distributed naming service, meaning that the service and its underlying database is spread across many hosts on the Internet.
115 3. LDAP (Lightweight Directory Access Protocol): Developed by the University of Michigan; as its name implies, it is a lightweight version of DAP (Directory Access Protocol), which in turn is part of X.500, a standard for network directory services. Currently, over 40 companies endorse LDAP.
4. NIS (Network Information System) and NIS+: Network naming services developed by Sun Microsystems. Both allow users to access files and applications on any host with a single ID and password. JNDI is a Java API that provides naming and directory functionality to applications written in the Java programming language. It is designed especially for the Java platform using Java's object model. Using JNDI, applications based on Java technology can store and retrieve named Java objects of any type. In addition, JNDI provides methods for performing standard directory operations, such as associating attributes with objects and searching for objects using their attributes. Also, JNDI defined independent of any specific naming or directory service implementation. It enables applications to access different, possibly multiple, naming and directory services using a common API. Different naming and directory service providers can be plugged in seamlessly behind this common API. This enables Java technology-based applications to take advantage of information in a variety of existing naming and directory services, such as LDAP, NDS, DNS, and NIS(YP), as well as enabling the applications to coexist with legacy software and systems.
116 2.5.9.1
JNDI Architecture
The JNDI architecture consists of an API and a service provider interface (SPI). Java applications use the JNDI API to access a variety of naming and directory services. The SPI enables a variety of naming and directory services to be plugged in transparently, allowing the Java application using the JNDI API to access their services.
Figure 23
JNDI is divided into five packages:
javax.naming: contains classes and interfaces for accessing naming services.
javax.naming.directory: extends the javax.naming package to provide functionality for accessing directory services in addition to naming services. This package allows applications to retrieve attributes associated with objects stored in the directory and to search for objects using specified attributes.
117
javax.naming.event: contains classes and interfaces for supporting event notification in naming and directory services.
javax.naming.ldap: contains classes and interfaces for using features that are specific to the LDAP v3 that are not already covered by the more generic javax.naming.directory package
javax.naming.spi: provides the means by which developers of different naming/directory service providers can develop and hook up their implementations so that the corresponding services are accessible from applications that use the JNDI. We will use the javax.naming package to localize our data sources in a distributed environment.
118
2.5.10 ENTERPRISE JAVABEANS (EJB)
Enterprise Java Beans is an architecture that defines the way of building distributed components on the server side. This technology guarantees that the programmed components are scalable, effective and safe in spite of the simplicity of its development, but without a doubt, they have a great amount of concepts that we need to clarify before continuing. These are the main characteristics of the EJB: •
The EJB is distributed component, this means that we can speak of components that are executed in different servers, possibly using different databases (it is a decision of the analyst-developer).
•
The EJB is executed inside an application server; these servers should follow the standard fixed by SUN Microsystem INC. They are in charge of negotiating resources like net, the connection pools, or the administration of the security. The developer builds the EJB and the application servers negotiate them.
•
The EJB helps the modulate programming; the idea of the programming based on components is the dream of many and the EJB make it possible in a simple way. You can program your component or you can buy it from others, but it will always exist a division and independence among the different components in a system. Inside a system it becomes possible to add or to remove a component without the rest notices the difference.
119 •
The specification that the EJB defines is public and in several companies work on it. Anyone can download from Internet the standard and program their own application server. If that server implements the public interfaces correctly, and it completes the specification it will be able to execute an EJB correctly. There are several implementations right now on the market, many of them open source like JBoss. Some of them are more efficiently than others depending in how they implement the standard.
•
EJB is Java. To program reusable components a clear separation it is needed between interfaces and their implementation, and Java supports it. Java is stable, safe and multi-thread, rarely it gets block and has one of the richest APIs. Java is platform independent, this allows that our components to be reutilize in different projects independently of the platform that they will be executed.
•
EJB solves daily life problems, they can communicate between each other and solve the business logic, they can access to any database that has implemented a JDBC driver, or to access to other systems through an SOAP interface or a web service.
120
2.5.10.1
EJB Architecture
2.5.10.1.1 Distributed components The EJB is a software component that is executed in the server part of an application and they can be executed in a distributed multi-layer environment. Although we could define component as piece of accessible software through a public interface, in the case of the EJB, the software and this interface (in fact two) should follow the standard and mandatory implement certain methods that this specification defines, this way the EJB containers can negotiate the life cycle in an uniform way being independent of the container that carries out the task. The EJB are components that can be physically far from the client, for it, it’s said that their public interface is remote, Remote Interface. The EJB specification makes use of RMI/IIOP to offer this characteristic. In RMI/IIOP all remote object has an accessible interface for the clients, the client can make use of this interface through the stub that is a proxy sent to the client. When the client invokes the stub, this communicates with the skeleton that is the proxy located in the server side. Once the skeleton received the message he is in charge of communicating it to the distributed object, which will solve the operation (business logic) and he will return the answer to the client through the first skeleton and the stub later. As much the stub as the skeleton are transparent for the client and they always has the sensation of being invoking to the distributed object directly. The problem is that in this type of operations the load is quite heavy: requires to open sockets, transfer objects through the net and transform these objects in binary data according to the protocol (in this case IIOP).
121 2.5.10.1.2 Implicit or Declarative Middleware The key of the modern distributed components is that its middleware is implicit, this means, that the code of our software doesn't call directly to the software integrated in the server, but rather it defines in the describer of each component, how we want the context where the code it’s executed. For example, an EJB doesn't have the necessity to call in an explicit way, in the code, the transactions API to begin a transaction (atomic operation on the database) but rather we can define in a different file, how we want the EJB to behave. For that, apart from this file where is defined the EJB behaviour, another file is needed tot capture the call to the distributed components and configure the way in that these components will work. In the case of EJB is the EJB Object. The EJB Object is generated by the own container and it is in charge of interact with the container to offer its services. Among other services, it offers the administration of distributed transactions, security, administration of the life cycle, persistence, etc. The advantages are simpler components; the code is centred in solving the logic and not in the way of solving it. You can also change the behaviour of the EJB without modifying their code, only modifying the file that specifies how they should work which is the describer.
122 2.5.10.1.3 Physical situation transparency The specification says that it can vary the place where the EJB is, but in some way it is needed to know how we can access to them, this it is the Home Object work. The Home Object is in charge of create and to destroy the EJB Object. It is an object generated by the container, of type Factory that implements the second of the public interfaces of an EJB, the Home Interface. This way the container knows which the EJB type is, which parameters should pass the EJB Object to create a new component or what type of searches the user has defined to obtain the reference to several components. It is important to point out that it exists only one EJBHome implementing their corresponding Home Interface for each type of EJB in each container. This makes possible to search the reference in some cases. 2.5.10.1.4 Local interfaces In the EJB specification 1.1 this concept didn't exist but many application servers began to implement improvements for calls inside one Java Virtual Machine (JVM), this way the necessity of translating the data to RMI to make a non remote call was eliminated. People in charge of the specification realized about this necessity and they created the local interfaces in the version 2.0; that only allow receiving clients' calls of the same JVM. These calls are much quicker and the parameters are also passed by reference and not by value, which decreases the memory consume.
123 2.5.10.2
TYPES OF COMPONENTS
At the moment the standard EJB defines three types of EJB: 2.5.10.2.1 Session Beans (SB) The session EJB is in charge of solving the business logic of the application. We can say that each method contained in a SB solves a use case (function) of the application, for example: User Control, Prices Agent or Processes Control. In the EJB specification we can find two types of Sessions Beans, State Less (SLSB) and State Full (SFSB). •
State Less Session Beans
The SLSB is component without state, this means, they don't keep any relationship between different calls from a client. Even more, between two calls to the same type of SLSB is possible that the container addresses the client to different instances of the component. Another fact of how they behave this type of components it is their relationship with the number of users. For N users there are M instances being M < N in most of the cases. The maximum value and minimum of M is configurable in most of the servers. With these two values is defined the size of the object pool. The objects pool has been used from the beginning of Java. This is, define a space in memory for several objects, in such a way that instead of having to instance an object every time, we can reuse the existent instances in the pool. This causes memory consumption but offers faster speed. It also makes the garbage collector work less, with this, the improvement of results is quite remarkable. That is the objective of the EJB pools that use the containers, reuse the EJB instances in memory.
124 The container guarantees that to an EJB instance only one thread can access, with that we will never have a concurrence problem inside an EJB, the container solves it for us. •
State Full Session Beans
The SFSB is the opposite of the SLSB, they maintain the state, this means, they have a conversation one to one with each client that invokes them. To maintain this conversation it is necessary to make use of the Handle object. The Handle object is a serializable reference to an EJB object. Keeping this reference you can access later on to the EJB with which the client had established a relationship. With the SFSB each client has associate an object EJB during a conversation. In case this reference gets lost, it can recover thanks to the Handle object. For that reason is the client who has to take care of preserving the instance of these objects if he wants call to their SFSB again. For many people, this type of EJB is consider as true heavy scheme and its use is dissuaded in most of the cases. Others maintain their utility for the possibility of maintaining a session distributed among several servers. In any of the cases hibernation should be avoided. The hibernation is the serialization process to disk of those less recently used instances (although it is possible to specify another hibernation policies depending on the application server) when the number of instances required by the clients is bigger than those that can support the SFSB pool. This process can take place, because the server runs out of memory or because it has reached the limit of maximum instances configured on the describer. The opposite process is called activation, and takes place when a client calls to a method of his associate SFSB and this is hibernated.
125 2.5.10.2.2 Entity Beans The entity EJB is directly related with the application data, are objects that maintain in memory the data that the application manages like News, Forums, Users. The Entity Beans usually map the relational database tables, although it is also possible that they maintain the data persistence in files, for example a XML, or in LDAP. In any of the cases the objective of an Entity Bean is to search the data in memory from a persistent source and to maintain a total synchronization between the state of the data in memory and the source of the data. For this reason it is said that the Entity Bean are the EJB that survive to the system falls, in the case of a system failure, the data in memory is kept in a persistent device, with this, when the server is restarted they recovered without any problem. This type of EJB totally abstracts the persistence layer of the system and it works like a tool for translation from a relational database to an object, for example, you could change the a column name of a chart in a table and the rest of layers would not realize, since to that column will only be accessed through a get/set method of the Entity Bean. Maybe the critics to this type of components come for the slowness in the search functions (call finders). These methods return a remote collection of interfaces that follow a series of conditions, similar to the SQL instructions. Although it is true that it is slower than a simple SQL query, but usually is not much bigger if the queries make a correct use of the transactions and the number of calls is minimized through the net. If there is a use case that has to return a big object collection the Fast-Lane Reader pattern can be implemented to speed up the process, this patterns says that in these cases where we have a big collection of objects a DAO should be used instead of an entity EJB. We will discuss pattern more in detail later on. As it has been explained before, the EJB stays inside a pool in memory. In the case of the Entity Beans this means that we have several rows of the database in memory, and we can get very quick accesses to those rows, therefore is interesting to maintain those registrations that we believe are we going to use again in memory.
126
Inside the Entity Beans there are two forms of managing persistence: one lets the programmer to manually take care of the persistence, in the other the container takes care of everything. •
Bean Managed Persistence
The BMP is the Entity Bean that support persistence thanks to the programmer's explicit instructions; this has to introduce the necessary instructions in the methods defined by the interface EntityBean: ejbLoad, ejbRemove, ejbCreate, etc. Every time this type of Entity Beans is used less, but there are still some operations that can only be carried out thanks to the programmer abilities. In any of the cases, they continue being indispensable when the persistence is not gotten through a relational database. •
Container Managed Persistence
The CMP supports the persistence in a declarative or implicit way thanks to the container; this means that, it is not necessary to implement the methods of the EntityBean interface, it is only necessary to define in a correct way the describer so that the container has this way the necessary information to negotiate the persistence against a relational database. Although in the principles of the EJB, Entity Bean type was not very used, since the programmers didn't trust much of the containers, nowadays are most used ones and they are even recommended because of efficiency issues with regard to the BMP. To create a CMP is really simple and the amount of functions that it carries out is really impressive, many programmers, the first time that see how easy is to create an Entity Bean they get really surprise.
127 2.5.10.2.3 Message-Driven Beans They are very similar to the session beans but they receive messages without responding to the client, in other words, they are asynchronous. Purchase authorization or card checkout are examples of this new EJB introduce in the 2.0 specification. Their only method, onMessage, receives the message type and with him carries out a series of operations and the user won't obtain direct answer. When this type of operations will be carried out at an uncertain time and it is not necessary the immediate answer to the client, is when we use this kind of EJB.
128 2.5.10.3
J2EE EJB Structure
The general EJB structure, as we mention before, looks like it follows:
Figure 24
As we can see on the diagram the Enterprise JavaBeans are in charge of implement de business logic (Session Beans) and also the data layer (Entity Beans).
129 This is a more concrete example of J2EE architecture:
Figure 25
Here we have Apache as Web Server and Tomcat as a JSP container as part of the view layer. Apache is in charge of serving HTML pages and Tomcat is the JSP in charge of compiling the JSP pages into Servlets. Jboss is the EJB container and it manages the different EJB that are part of the model and also are the ones who access to the database.
130 2.5.10.4
EJB Operation
Now we will take a look on how the EJB work. We will use a small example to see how to develop using EJB. First, let’s review the EJB parts. Enterprise JavaBeans Parts: EJB class that implements the business methods and life cycle methods; uses other helper classes and libraries to implement. Client-view API: consists of EJB home interface and remote interface. o Home interface: controls life cycle: create, remove, and find methods. There should be one Home interface for each local or remote interface. o Remote interface: to invoke the EJB object methods (if the EJB is declared as remote). o Local Interface: Idem for local EJB. Deployment Descriptor: XML document for bean assembler and deployer on the container. o A declaration about EJB environment needed for customizing the bean to the operating environment. Container Runtime services include: transactions, security,distribution,load balancing, multithreading, persistence, failure recovery, resource pooling, state management, clustering…
131 Naming Convention:
EJB class is a descriptive name of the business entity or process with the word Bean appended. Ex: AccountBean.
Home interface is same as business entity name with the word “Home” appended. Ex: AccountHome.
Remote interface is just the name of the entity. Ex: Account.
The name of the entire EJB (reference in deployment descriptor) is same as the entity name with EJB appended. Ex: AccountEJB.
Enterprise JavaBean componets: Next, we show the classes used in the example with their usual methods.
<> AccountHome create() find() remove()
< AccountBean ejbCreate() ejbFind() ejbRemove() debit() credit() getBalance()
<> Account debit() credit() getBalance()
Deployment Descriptor name = AccountEJB class = AccountBean home = AccountHome remote = Account type = Entity transaction = required …..
132 General Diagram:
Figure 26
The EJB Object is the EJB interface; it can be local or remote. It specifies simple operations to manipulate the state of the bean or to recover it. It doesn't represent business logic, but the persistent state. In our case, the interface is remote (Account). It extends from the EJBObject interface. EJB Home is another additional EJB interface that usually has the searching operations. In our case it’s AccountHome. It extends from the EJBHome interface. Finally we have the Bean, in our example AccountEJB; which implements the EJB. Is important to realize that:
An CMP Entity Bean doesn't need to implement the search methods
In a BMP Entity Bean a DAO is used to implement the search methods
Additional services are provided by the EJB container.
133 Class diagram of the Remote and Home Interface:
Figure 27
As we can see, the EJB nucleus is RMI. We can see how EJB is just a specification that uses interfaces that the programmer has to follow, so we just have to extend from EJBObject and write our EJB interface (Account) and extend EJBHome and write our EJBHome interface (AccountHome).
134 This is the class diagram for the Bean:
Figure 28
In the case of Entity EJB, the programmer just has to implement the EntityBean interface, in our case the class is AccountEJB.
135 Implementation AccountHome Interface: import java.rmi.RemoteException; import javax.ejb.CreateException; import javax.ejb.FinderException; import java.util.Collection; public interface AccountHome extends javax.ejb.EJBHome { //create methods Account create (String lastName, String firstName) throws RemoteException, CreateException, BadNameException; Account create (String lastName) throws RemoteException, CreateException; // find methods Account findByPrimaryKey (AccountKey primaryKey) throws RemoteException, FinderException; Collection findInActive(Date sinceWhen) throws RemoteException, FinderException, BadDateException; EJBHome Interface:
import java.rmi.RemoteException; public interface EJBHome extends java.rmi.Remote { void remove(Handle handle) throws RemoteException, RemoveException; void remove(Object primaryKey) throws RemoteException, RemoveException; EJBMetaData getEJBMetaData( ) throws RemoteException; HomeHandle getHomeHandle() throws RemoteException; }
136 Account Interface: import java.rmi.RemoteException; public interface Account extends javax.ejb.EJBObject { BigDecimal getBalance() throws RemoteException; void credit(BiGDecimal amount) throws RemoteException; Void debit(BigDecimal amount) throws RemoteException, InSufficientFundsException; } EJBObject Interface: import java.rmi.RemoteException; public interface EJBObject extends java.rmi.Remote { public EJBHome getEJBHome() throws RemoteException; public Object getPrimaryKey() throws RemoteException; public void remove() throws RemoteException, RemoveException; Public Handle getHandle() throws RemoteException; Boolean isIdentical (EJBObject obj2) throws RemoteException; }
137 AccountBean class: public class AccountBean implements javax.ejb.EntityBean { // life cycle methods from home interface public AccountKey ejbCreate (String latName, String firstName) throws … {…} public AccountKey ejbCreate(String lastName) throws …{…} public AccountKey ejbFindByPrimaryKey(AccountKey primarykey)… {…} Public Collection ejbFindInactive( Data sinecWhen).. {…} // business methods from remote interface public BigDecimal getBalance() {….} public void credit(BigDecimal amt) {…} public void debit(BigDecimal amt) throws InsufficientFundException {….} // container callbacks from EntityBean container public ejbRemove( ) throws RemoveException{ …} public void setEntityContext(EntityContext ec) {…} public unsetEntityContext(EntityContext ec) {…} public void ejbActivate() {…} public void ejbLoad() {….} public void ejbStore() {….} }
138 As we can see in the example; EJB provides a simple way to build persistent and distributed objects. It may be difficult to understand the architecture and hot it works but once learned we can build distributed enterprise applications very easily. EJB is the key of the J2EE platform. It competes with other technologies like CORBA or COM+. Nowadays, CORBA is not suitable to develop Web applications and is only used on intranets; this is due to its complexity and because is still very difficult to make total portable applications and developers find many problems with the portability issue with CORBA. About COM+, the Microsoft solution, we go back again to the old dilemma: Sun or Microsoft? We will discuss in detail this issue on the next section.
139
2.6
J2EE vs. .NET
We have been talking a lot so far about these two rival platforms, now let’s summarize everything.
2.6.2 Similarities between J2EE and .NET •
The goal of J2EE and the .NET platform is to facilitate and simplify the development of enterprise or corporate applications. The JSP (Java Server Pages) are very similar to ASP (Active Server Pages) or to its descendant ASP .Net, and the EJB (Enterprise JavaBeans) are very similar to the COM/COM+ of Microsoft.
•
The J2EE applications servers and .Net provide a model of component access to data and of business logic, separated by an intermediate presentation layer implemented by ASP .Net (:Net) or Servlets (J2EE).
•
Visual Basic .Net and C # are objects oriented languages created for the Microsoft platform, and in their design the existence of Internet has a lot of importance.
•
From the perspective of the developers, J2EE and .Net provide the tools to create Web services.
•
As it has been exposed J2EE and .Net are multiplatform. Since .Net is using a compilation in two steps, it would allow it theoretically in the future to provide execution environments for different platforms in a similar way to Java and their JREs and SDKs.
140
2.6.3 Advantages of .Net over J2EE a) A very important advantage of the environment .Net in front of J2EE is the possibility to use different programming languages, whereas J2EE only works with one: Java. However, some theoretical could think that the best thing would be that there was only one programming language (to be possible standardized), this idea is as utopian as to think that Esperanto will finish substituting the other human languages. The reality is that this high diversity of languages is obligatory for the same variety of the necessities of the programmers. Today more code lines are written in Cobol than in C++ or Java. A modern language and object oriented like Java can be completely ineffective -and even inadequate - when approaching problems that involve massive and complex mathematical calculations, while those same calculations can be approached much more appropriately with such a primitive language as Fortran 77. On the other hand, .Net facilitates programmers of third languages to pass to this platform reducing the time of learning and training. b) The development tools included by Microsoft in their Visual Studio .Net are much more simple, intuitive and simple of managing than the equivalent development tools in J2EE given by other companies (among them, Sun). Any intermediate/advanced programmer will manage quickly with the programming of user's interface in Visual Studio .Net, the same as it happened to previous versions of Visual Studio. c) C # is an interesting language, easy to learn for the programmers from Java (in fact, Microsoft offers a conversor from Java to C #) that could be a very convenient language for certain programming tasks in different platforms in the case of being standardized. It is not written in any part that the languages cannot evolve (in fact, the programming languages and the human languages do it) and, in that sense, C # is an another evolutionary branch of the tree of the object oriented languages.
141 d) Microsoft has impulse with great energy the Web services and it has stood out its importance among the whole developers community. The platform .Net has been designed considering the Web services (but not J2EE) being these services characteristic of the platform and offers a new version of ASP, ASP .Net, that can really be considered a programming environment instead of an environment based on scripts. In terms of the own Microsoft, .Net was built for the integration through the XML Web services using protocols and file formats like SOAP (Simple Object Access Protocol), WSDL (Web Services Description Language), and UDDI (Universal Description, Discovery, and Integration). If we compare, .Net has advantage with regard to J2EE relating to Web services and these services are characteristic of the platform, although J2EE already responded with the launching of the Java Web Services Developer Pack. Anyway, the easiness, speed and simplicity that allow us to build Web services with the Assistant of services Web of Visual Studio .Net are very superior to the tools to build Web services within the environment of J2EE. But like always, J2EE changes more quickly than .NET platform and new Java platforms like Eclipse are emerging and integrating many Web services.
142
2.6.4 Advantages of J2EE over .NET a) The implementations of J2EE can be acquired to different companies, whereas .Net can only be bought to Microsoft. The fact that there are different organizations implementing J2EE offers big variety for the final users and it allows the existence of a certain competition among them to obtain better products that it doesn't exist in the case of Microsoft and his .Net platform. b) Due to the evolutionary process of the Microsoft products, and in many cases, because of reasons of compatibility the security against computer virus of the products of Microsoft is smaller than those based on Java, because from a beginning Java was based on a strict security model. c) Like it has already been written, the Java applications can run in a wide range of operative systems (from enterprise systems as Windows 2000, OS/390, Solaris, HP-UX, IRIX or other Unix versions to systems guided more to personal computers as Mac OS, Windows 9x or Linux , and in operative systems for mobile devices) and of architectures hardware. So far, .Net only runs on Microsoft operative systems (although this situation could change in the future), being J2EE the only development environment that offers a real independence of the platform. d) The Java technology is an open technology (in the sense that the code of the complete platform can be obtained, revised and studied by anyone that is interested) and it is largely based in standard of normalization organizations. This facilitates that the developers can know and understand completely how Java works and take advantage of it for their applications and, on the other hand, when being based in enterprise standard, it simplifies the integration with products of multiple companies.
143 In contrast, only the source code of the new C# language of the .Net platform has been open to the general public (although Microsoft allows companies that have common interest with them, the access to the source code of certain parts of .Net). a) Although Java was created originally by a company: Sun MicroSystems, the true is that J2EE are now the product of the collaboration of more than 400 companies and organizations of all type (public, non-profit private, profit private, and of normalization in national and international environments). The .Net platform is -and it will be - the product of a single company that although it has implemented some standards in .Net and tried to get that certain technologies become official standards, have the same consent that .Net (mainly keeping in mind that most of its code is not public). b) The Java technology already enjoys a certain maturity (many years in the market). J2EE and it has proven their effectiveness in many environments and different enterprise situations, while .Net has seen the light officially in 2004.
144
2.6.5 The Future Java is a language thought to last among the programmer community. Although Microsoft insists that within the .Net strategy Java is one language more, the true is that it has extended so much among the programmer, educational and investigator community, that its future is even promising, in spite of the strong competition of Microsoft. Possibly many C++ programmers will finally program in C #, for the own nature of the applications that they develop, but many of them also finished programming in Java when developing applications guided to the Net. Until the moment, the J2EE platform is the only platform that runs in multiple operating systems and multiple hardware and whose users can select the implementation that suits more to them. This platform runs at the moment not only in domestic computers or servers or work stations, but also in multitude of devices like mobile telephones, electronic calendars, industrial electronic components, etc. Their installation in the market of the mobile telephones GMS and UMTS can assure a prosperous future, since it is more than probable that will finally become a common media to access to Internet. Java has already made reality the dream of “write the code once, execute it anywhere.". Like it was pointed out before, it is perfectly possible that Microsoft provides in the future .NET execution environments for different platforms in a similar way to Sun (like for Windows 64 bits Itanium or for a Windows CE on a Pocket PC), but has not still made it for non-Windows platforms, and it would be strange that they make it for its own strategy till today. Even this way, it would arrive with a considerable delay with regard to J2EE. On the other hand, we should not forget that in the last announcements of Microsoft technologies transfers to other platforms (component DCOM, for example) they didn't end up being materialized.
145 The Microsoft policies, for internal (intents of incorporating new technologies and/or tendencies to their products) and legal reasons, have changed so much that, in some cases, they have abandoned developers and programmers that had adopted their solutions to their luck (a very curious case were the Active Documents; a solution that allowed the programmers of Visual Basic to create web applications without using script programming. This solution, although it looked promising, followed identical road that the dinosaurs). Also because of Microsoft commercial reasons, the substitution of products and technologies for other has been so quick and repetitive that many developers of small and medium companies have given up to follow that evolution, and they have kept technologies from Microsoft that no longer gives support (RDO, DAO, for example) or they have moved to Java. The Microsoft statement “to program is more and more easy with .Net “ are not enough for the companies that have invested multitude of technical, economic and personal resources in products and/or Microsoft technologies already obsolete, and also incompatible with the new products. Against this, J2EE offer some comparative perspectives much more stable (big multinationals have made the decision of not beginning to use .Net and to continue or to begin with J2EE). On the other hand, the Microsoft penetration in the market of the big corporate systems and in the enterprise applications of high level it is not excessively high. In the elaboration of J2EE multitude of companies have participated, many of them specialized in giving service software/hardware to big companies and corporate systems and that, therefore, they know that sector very well. This plurality, also makes more probable than J2EE it finishes becoming a “de facto standard", when having been developed with the participation of many companies that, inevitably, they will have looked toward its own products when elaborating it. J2EE maybe doesn’t end up becoming a standard type ISO or IEEE, but after all the protocol TCP/IP is also a “de facto standard."
146 As we mention before, inside the Visual Studio .Net the Visual Basic .Net language is a true object oriented language. But it also has its problems: although many professional programmers considered VB to be like a smaller language, it was (and it is) the most used language of the planet due overalls to its simplicity. With VB .Net, they are necessary some solid knowledge of programming OO to appreciate in depth the advantages of the same one and to create programs that take advantage of all their possibilities. A programmer that possesses all these knowledge will probably decide to work in C# or Java that have a more standard syntax. Who knows, maybe to suppress the simplicity of Visual Basic to make it more modern can make it loose its charm. C # is a language that can become a stupendous tool for developers that want to elaborate code of high efficiency, without having that deal with in C++, but it is still soon to be able to affirm anything sure about the future. Even this way, it is a language of high quality and it will surely be ideal to program inside .Net for their symbiosis with the platform. The web services should still travel a long road among standard, services providers and consumers, but until the moment Microsoft and specifically .Net takes a certain advantage on J2EE. Even this way, it continues planning the question of the independence of the platform. If .Net doesn't finish being really multiplatform, possibly J2EE will prevail in the development of Web services for big companies and for web services clients that require not to depend on a specific platform, and .Net will prevail in the development of Web services for small and medium companies that use Windows. Even this way, the future, as so many other things, it is uncertain and sure that right now there is somebody that is -still designing inside their head - a new programming language that will go an step further..
147
3.
NEW APPROACHES USING JAVA 2 PLATFORM
The Java platform is a technology that is on continuous changing. There are hundreds of companies and organizations working on this technology. Each year new technologies appear that offer new possibilities to the programmers. Besides the J2EE platform technologies there are right now in the market new technologies that are gaining more and more relevance. One platform that is gaining more relevance is the Eclipse platform. Eclipse is a kind of universal tool platform - an open extensible IDE for anything and nothing in particular. Eclipse is an open source project and is part of the Eclipse Foundation, a non-profit corporation formed to advance the creation, evolution, promotion, and support of the Eclipse Platform and to cultivate both an open source community and an ecosystem of complementary products, capabilities, and services. Eclipse started has an ambitious IBM project after some years running as proprietary software IBM decided to release it as an open source platform. Nowadays, there are many companies and organizations working on this project. The Eclipse Platform is designed for building integrated development environments (IDEs) that can be used to create applications as diverse as web sites, embedded JavaTM programs, C++ programs, and Enterprise JavaBeansTM. It has a great Java support.
148 Although the Eclipse Platform has a lot of built-in functionality, most of that functionality is very generic. It takes additional tools to extend the Platform to work with new content types, to do new things with existing content types, and to focus the generic functionality on something specific. The Eclipse Platform is built on a mechanism for discovering, integrating, and running modules called plug-ins. A tool provider writes a tool as a separate plug-in that operates on files in the workspace and surfaces its tool-specific UI in the workbench. When the Platform is launched, the user is presented with an integrated development environment (IDE) composed of the set of available plug-ins. The plug-ins are the key of the Eclipse platform, the success of this platform comes from the fact that his IDE is really generic and has a modular approach, so, for been open source anyone can add new modules (plug-ins) and personalize the IDE. This is the main advantage over other approaches like NetBeans (Sun IDE). Eclipse can be configured to give support to new technologies very quickly because of his architecture. Right now, there are plug-ins for various technologies like XDoclet, Spring, Hibernate, Lomboz, Jboss… There are right now many approaches using Eclipse with other technologies as a plugin. Nowadays, on the internet forums you can hear developer talk about famous “kits” for develop scalable enterprise web applications in a really easy way. Like the Struts+EJB “kit” or the Spring+Hibernate “kit”. There are so many choices that the developers go crazy each time they start a new project. That’s the big advantage of the open source software. First, we will talk about two different approaches for the implementation of the MVC controller and we will compare them with our choice: Struts. Then, we will introduce a powerful alternative to the EJB: Hibernate.
149 3.1
MVC Frameworks
3.1.1
JavaServer Faces (JSF)
JavaServer Faces has been standardized recently (JSF) (http://java.sun.com/j2ee/javaserverfaces). JSF a framework to implement the view layer of a web application, it includes: •
A set of APIs for representing UI components and managing their state, handling events and input validation, defining page navigation, and supporting internationalization and accessibility.
•
A Java Server Pages (JSP) custom tag library for expressing a JavaServer Faces interface within a JSP page.
The primary goal is to make the development of web applications easy and to separate the view from the model. JSF is focus fundamentally for built IDEs that allow developing of web applications graphically, which can be integrated in existent web frameworks. In the future, Struts will be integrated with JSF, and in particular, they will be able to use the JSF tags instead of the HTML tags of Struts (in a similar way to how the JSTL tags has replaced the tags of the Bean and Logic libraries of Struts).
150 3.1.2
Spring
Spring is another MVC framework who got born with the idea of simplify the development of web applications. Basically, it tries to solve the main EJB+Struts problems. Unlike other frameworks and APIs, spring does not impose itself wholly on to the design of a project. Spring is modular and has been divided logically into independent packages, which can function independently. The architects of an application have the flexibility to implement just a few spring packages and leave out most of the packages in spring. The "Spring Framework" would not feel bad with this attitude and on the contrary encourages users to introduce Spring into existing applications in a phased manner. So no matter what kind of framework you are using now Spring will co-exist with it without causing you nightmares and further more Spring will allow you to choose specific packages in Spring. Spring can be used along with Struts or JSF because of its layered architecture. So, the application code doesn’t depend on Spring APIs. Spring tries very hard to be as simple as possible and it can function as a container it its own right. This can remove the need for a complex, and sometimes expensive, J2EE container. Everything is defined in terms of beans and properties. This, reduce dependencies and specialization so that framework constrains the developer a little as possible. The Spring Framework provides a mechanism for designing systems, aiding you in the modularisation of components and hence in making components more readily testable. The crux of the framework is that you design your business service and data access objects as Java beans, and then provide a dependency mapping between them. This leads to very well structured systems with a pluggable feel.
151 Spring Framework is suited to a wide variety of architectures, and can be utilised in discrete parts of a system, as well as across the whole system. Let's give an example where we want to use Spring for the business and data access tiers of a system. 3.1.3 •
Struts vs. JSF vs. Spring
Struts o Advantages:
Is the “Standard”. Many web applications have been implemented using this framework that is running since 2001.
Many information and examples.
HTML tag library is one of the best.
Robust.
o Disadvantages:
It’s difficult to use. ActionForms make the work too complicate.
It doesn’t have unit test, making it really hard to test.
Too many checked exceptions that are not needed in some cases. This is because Java is a robust language.
•
JSF o Advantages:
J2EE Standard.
Fast and easy to develop with.
Rich Navigation framework.
o Disadvantages:
Immature technology.
No single source for implementation.
152 •
Spring o Advantages:
Lifecyle for overriding binding, validation, etc.
Integrates with many view options seamlessly: JSP/JSTL, Tiles, Velocity, FreeMarker, Excel, XSL, PDF.
Inversion of Control makes it easy to test.
Easy to use.
Layered Architecture, easy to integrate.
o Disadvantages:
Too immature. It was introduced in 2004 and there is not too many people using it.
Requires writing lots of code in JSPs.
Almost too flexible. No common parent Controller
As we can see, nowadays, the most powerful MVC framework is Spring. Mainly for its easy to use and his flexibility to integrate with other tools like hibernate.
153
Hibernate
3.2
For most of the applications, to store and to recover information implies some interaction form with a relational database. This has represented a fundamental problem for the developers because the data design and the object model share structures very different inside their respective environments. The relational databases are structured in tables and the objects are usually in a tree form. This difference has made developers of several objects persistence technologies to try to build a bridge among the relational world and the object oriented world. There are basically three ways to access to the database: 1. Using JDBC to send SQL queries directly to the database: This approach is very inefficient because is cause a completely dependence with the database and the result is a non scalable software. 2. Using DAOs: With this approach we have classes that the programmer creates to take care of the persistence. The DAOs are used in the BMP Beans. 3. Automatic managed persistence: Here we have a tool that manages the persistence for the programmer. In the case of the CMP Beans the EJB container takes care of this task. Hibernate is another option for manage the persistence. Hibernate is an alternative to the Entity Beans to handle the persistence of objects. It is a powerful open source tool with the goal to facilitate the object persistence on relational databases.
154 It allows you to design persistent objects that will be able to include polymorphism, relationships, collections, and a great number of data types. In a very quick and optimized way we will be able to generate DB in anyone of the supported environments: Oracle, DB2, MySql, etc… The key of Hibernate is that makes the persistence transparent to the developer, mapping automatically the business model objects to the relational database and providing a high level object-oriented query language allowing developers to get rid of the SQL queries. This is a great feature because it provides a total separation between the database and the application; this separation is not achieved with EJB that are somehow dependent of the database. Even do, the SQL language is a standard there are some differences between different DBMS. Hibernate supports a wide range of relational database and automatically maps his high level query language to the corresponding database language using standard XML files. One of the unique characteristics of Hibernate it is that it doesn't require that the developers implement interfaces or extend classes to be able to persist the classes. Instead of that, Hibernate uses Java reflection and the increase of classes in execution time using a very powerful Java code generation library called CGLIB. CGLIB is used to extend Java classes and to implement Java interfaces in execution time.
155 3.2.1
Hibernate Structure
Figure 29
Client's request will be send from the browser to a Java servlet that communicates with user's service and this, with the DAOs based on Hibernate.
156 3.2.2
Hibernate Overview
High level architecture of Hibernate can be described as shown in following illustration:
Figure 30
Hibernate makes use of persistent objects commonly called as POJO (POJO = "Plain Old Java Object".) along with XML mapping documents for persisting objects to the database layer. The term POJO refers to a normal Java objects that does not serve any other special role or implement any special interfaces of any of the Java frameworks (EJB, JDBC, DAO, JDO, etc...). Rather than utilize byte code processing or code generation, Hibernate uses runtime reflection to determine the persistent properties of a class. The objects to be persisted are defined in a mapping document, which serves to describe the persistent fields and associations, as well as any subclasses or proxies of the persistent object. The mapping documents are compiled at application start-up time and provide the framework with necessary information for a class. Additionally, they are used in support operations, such as generating the database schema or creating stub Java source files.
157 3.2.3 •
Hibernate Features
Transparent persistence without byte code processing − Transparent persistence − JavaBeans style properties are persisted − No build-time source or byte code generation / processing − Support for extensive subset of Java collections API − Collection instance management − Extensible type system − Constraint transparency − Automatic Dirty Checking − Detached object support
•
Object-oriented query language − Powerful object-oriented query language − Full support for polymorphic queries − New Criteria queries − Native SQL queries
•
Object / Relational mappings − Three different O/R mapping strategies − Multiple-objects to single-row mapping − Polymorphic associations − Bidirectional associations − Association filtering − Collections of basic types − Indexed collections − Composite Collection Elements − Lifecycle objects
158 •
Automatic primary key generation − Multiple synthetic key generation strategies − Support for application assigned identifiers − Support for composite keys
•
Object/Relational mapping definition − XML mapping documents − Human-readable format − XDoclet support (an open source code generation engine)
•
HDLCA (Hibernate Dual-Layer Cache Architecture) − Thread safeness − Non-blocking data access − Session level cache − Optional second-level cache − Optional query cache − Works well with others
•
High performance − Lazy initialization − Outer join fetching − Batch fetching − Support for optimistic locking with versioning/timestamping − Highly scalable architecture − High performance − No "special" database tables − SQL generated at system initialization time − Internal connection pooling and PreparedStatement caching
159 •
J2EE integration − JMX support − Integration with J2EE architecture (optional) − New JCA support
160 3.2.4
Hibernate Example
Now let’s see how easy is to build application using Hibernate. We will se how to create a table, create a persistent object, the object-table mapping and the access to the object. These are the steps: 1. Preparing Database Let’s consider a simple database schema with a singe table as APPLABSUSER that we create with this SQL code: CREATE TABLE `applabsuser` ( `USER_ID` int(11) NOT NULL default '0', `USER_NAME` varchar(255) NOT NULL default '', `USER_PASSWORD` varchar(255) NOT NULL default '', `USER_FIRST_NAME` varchar(255) default NULL, `USER_LAST_NAME` varchar(255) default NULL, `USER_EMAIL` varchar(255) default NULL, `USER_CREATION_DATE` date default NULL, `USER_MODIFICATION_DATE` date default NULL, PRIMARY KEY (`USER_ID`), UNIQUE KEY `USER_NAME` (`USER_NAME`) ); 2. Create Persistent Java Objects Hibernate works best with the Plain Old Java Objects programming model for persistent classes. Hibernate is not restricted in its usage of property types, all Java JDK types and primitives (like String, char and Date) can be mapped, including classes from the Java collections framework. You can map them as values, collections of values, or associations to other entities. The id is a special property that represents the database identifier (primary key) of that class, Hibernate can use identifiers only internally, but we would lose some of the flexibility in our application architecture.
161 No special interface has to be implemented for persistent classes nor do you have to subclass from a special root persistent class. Hibernate also doesn't require any build time processing, such as byte-code manipulation, it relies solely on Java reflection and runtime class enhancement (through CGLIB). So, without any dependency of the POJO class on Hibernate, we can map it to a database table. Following code sample represents a java object structure which represents the AppLabsUser table. Generally these domain objects contain only getters and setters methods. One can use Hibernate extension toolset to create such domain objects. AppLabsUser.java package org.applabs.quickstart; import java.io.Serializable; import java.util.Date; import org.apache.commons.lang.builder.ToStringBuilder; public class AppLabsUser implements Serializable { public void setName(String name) { /** identifier field */ private Long id; /** persistent field */ private String userName; /** persistent field */ private String userPassword; /** persistent field */ private String userFirstName; /** persistent field */ private String userLastName; /** persistent field */ private String userEmail;
162 /** persistent field */ private Date userCreationDate; /** persistent field */ private Date userModificationDate; /** full constructor */ public Applabsuser(String userName, String userPassword, String userFirstName, String userLastName, String userEmail, Date userCreationDate, Date userModificationDate) { this.userName = userName; this.userPassword = userPassword; this.userFirstName = userFirstName; this.userLastName = userLastName; this.userEmail = userEmail; this.userCreationDate = userCreationDate; this.userModificationDate = userModificationDate; } /** default constructor */ public Applabsuser() { } public Long getId() { return this.id; } public void setId(Long id) { this.id = id; } public String getUserName() { return this.userName; } public void setUserName(String userName) { this.userName = userName; } public String getUserPassword() { return this.userPassword; } public void setUserPassword(String userPassword) { this.userPassword = userPassword; } public String getUserFirstName() { return this.userFirstName; }
163
public void setUserFirstName(String userFirstName) { this.userFirstName = userFirstName; } public String getUserLastName() { return this.userLastName; } public void setUserLastName(String userLastName) { this.userLastName = userLastName; } public String getUserEmail() { return this.userEmail; } public void setUserEmail(String userEmail) { this.userEmail = userEmail; } public Date getUserCreationDate() { return this.userCreationDate; } public void setUserCreationDate(Date userCreationDate) { this.userCreationDate = userCreationDate; } public Date getUserModificationDate() { return this.userModificationDate; } public void setUserModificationDate(Date userModificationDate) { this.userModificationDate = userModificationDate; } public String toString() { return new ToStringBuilder(this) .append("id", getId()) .toString(); } }// End of class
164 3. Mapping POJO with persistence layer using hibernate mapping document Each persistent class needs to be mapped with its configuration file. Following code represents Hibernate mapping file for AppLabsUser class.
165 We can also generate Hibernate mapping documents using Hibernate extension toolset. Hibernate mapping documents are straight forward. The element maps a table with corresponding class. The element represents the primary key column, and its associated attribute in the domain object. The elements represent all other attributes available in the domain object 4. Hibernate Configuration File Hibernate configuration file information needed to connect to persistent layer and the linked mapping documents. You can either specify the data source name or JDBC details that are required for hibernate to make JDBC connection to the database. The element refers to the mapping document that contains mapping for domain object and hibernate mapping document. true org.hibernate.dialect.MySQLMyISAMDialect org.gjt.mm.mysql.Driver jdbc:mysql://localhost:3306/applabs root r00Tp@$wd
166 5. Hibernate Sample Code (Inserting new record) Here is how you can use Hibernate in your programs. Typical Hibernate programs begin with configuration that is required for Hibernate. Hibernate can be configured in two ways. Programmatically and Configuration file based. In Configuration file based mode, hibernate looks for configuration file hibernate.cfg.xml in the classpath. Based on the resource mapping provided hibernate creates mapping of tables and domain objects. In the programmatic configuration method, the details such as JDBC connection details and resource mapping details etc are supplied in the program using Configuration API. Following example shows programmatic configuration of hibernate. Configuration config = new Configuration() .addResource("org/applabs/hibernate/quickstart/Applabsuser.hbm.xml") Configuration config = new Configuration() .addClass(org.hibernate.quickstart.Applabsuser.class) .setProperty("hibernate.dialect", "org.hibernate.dialect. MySQLMyISAMDialect") .setProperty("hibernate.connection.driver_class", " org.gjt.mm.mysql.Driver") . . . SessionFactory sessions = config.buildSessionFactory(); In configuration file based approach, “hibernate.cfg.xml” is placed in the classpath, Following Hibernate code can be used in this method. SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory(); Session session = sessionFactory.openSession(); AppLabsUser user = new AppLabsUser(); Transaction tx = session.beginTransaction(); user.setUserCreationDate(new Date()); user.setUserEmail("[email protected]"); user.setUserFirstName("userFirstName"); user.setUserLastName("userLastName"); user.setUserName("userName-1"); user.setUserPassword("userPassword"); session.saveOrUpdate(user); tx.commit(); session.close();
167 6. Hibernate Sample Code (Quering the database) SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory(); Session session = sessionFactory.openSession(); ArrayList arrayList = null; String SQL_STRING = "FROM AppLabsUser as users"; Query query = session.createQuery(SQL_STRING); ArrayList list = (ArrayList)query.list(); for(int i=0; i
As we can see from the example, Hibernate manages the persistence in an efficient, transparent and easy way. Right now, I believe that is the best mapping tool and should be used instead of EJB to manage the data layer, at least until the EJB 3.0 specification gets finally completed.
168
4. DESIGN PATTERNS On this section we will describe the design patterns that are usually used to build enterprise applications. These patterns help developers to solve usual problems that programmers have to face when programming this kind of applications. First, we will take a general look to the OO Programming patterns to review the main aspects of these patterns. Then, we will focus on the enterprise applications patterns (J2EE Core Patterns). The knowledge of these patterns is crucial to develop scalable and robust applications. This section is more focus to analyst and designers who need to create model for the enterprise applications. For a software engineering, knowing the design patterns is fundamental.
169 4.1
USUAL OOP DESIGN PATTERNS
Design patterns can be classified in the next categories: 1. Creational Patterns: Creational design patterns abstract the instantiation process. They help make a system independent of how its objects are created, composed, and represented. A class creational pattern uses inheritance to vary the class that's instantiated, whereas an object creational pattern will delegate instantiation to another object. Here are some examples:
Abstract Factory: Provide an interface for creating families of related or dependent objects without specifying their concrete classes. Here is the structure:
Figure 31
Is recommended to use Abstract Factory pattern when: •
A system should be independent of how its products are created, composed, and represented.
•
A system should be configured with one of multiple families of products.
•
A family of related product objects is designed to be used together, and you need to enforce this constraint.
170 •
You want to provide a class library of products, and you want to reveal just their interfaces, not their implementations.
Example:
Figure 32
WidgetFactory class declares an interface for creating each basic kind of widget. There's also an abstract class for each kind of widget, and concrete subclasses implement widgets for specific look-and-feel standards. WidgetFactory's interface has an operation that returns a new widget object for each abstract widget class. Clients call these operations to obtain widget instances, but clients aren't aware of the concrete classes they're using-
171
Builder: Is used to separate the construction of a complex object from its representation so that the same construction process can create different representations.
Figure 33
We should use the Builder pattern when: •
The algorithm for creating a complex object should be independent of the parts that make up the object and how they're assembled.
•
The construction process must allow different representations for the object that's constructed.
Example:
Figure 34
172
Factory Method: Defines an interface for creating an object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses.
Figure 35
Use the Factory Method pattern when: •
A class can't anticipate the class of objects it must create.
•
A class wants its subclasses to specify the objects it creates.
•
Classes delegate responsibility to one of several helper subclasses, and you want to localize the knowledge of which helper subclass is the delegate.
173
Prototype: The intent is to specify the kinds of objects to create using a prototypical instance, and create new objects by copying this prototype.
Figure 36
Is better to use the Prototype pattern when a system should be independent of how its products are created, composed, and represented; and when the classes to instantiate are specified at run-time, for example, by dynamic loading; or to avoid building a class hierarchy of factories that parallels the class hierarchy of products; or when instances of a class can have one of only a few different combinations of state. It may be more convenient to install a corresponding number of prototypes and clone them rather than instantiating the class manually, each time with the appropriate state.
174
Singleton: It ensures that a class only has one instance, and provides a global point of access to it.
Figure 37
Use the Singleton pattern when: •
There must be exactly one instance of a class, and it must be accessible to clients from a well-known access point.
•
When the sole instance should be extensible by subclassing, and clients should be able to use an extended instance without modifying their code.
175 2. Structural Patterns: Structural patterns are concerned with how classes and objects are composed to form larger structures. Structural class patterns use inheritance to compose interfaces or implementations. Structural object patterns describe ways to compose objects to realize new functionality. The added flexibility of object composition comes from the ability to change the composition at run-time, which is impossible with static class composition.
Adapter: The idea is to convert the interface of a class into another interface that the clients expect. Adapter lets classes work together that couldn't otherwise because of incompatible interfaces. A class adapter uses multiple inheritance to adapt one interface to another:
Figure 38
176 An object adapter relies on object composition:
Figure 39
We can use the Adapter pattern when: •
You want to use an existing class, and its interface does not match the one you need.
•
You want to create a reusable class that cooperates with unrelated or unforeseen classes, that is, classes that don't necessarily have compatible interfaces.
•
(object adapter only) you need to use several existing subclasses, but it's impractical to adapt their interface by subclassing every one. An object adapter can adapt the interface of its parent class.
Example:
Figure 40
177
Bridge: The intent is to decouple an abstraction from its implementation so that the two can vary independently.
Figure 41
Use the Bridge pattern when: •
You want to avoid a permanent binding between an abstraction and its implementation. This might be the case, for example, when the implementation must be selected or switched at runtime.
•
Both the abstractions and their implementations should be extensible by subclassing. In this case, the Bridge pattern lets you combine the different abstractions and implementations and extend them independently.
•
Changes in the implementation of an abstraction should have no impact on clients; that is, their code should not have to be recompiled.
•
(C++) you want to hide the implementation of an abstraction completely from clients. In C++ the representation of a class is visible in the class interface.
•
You have a proliferation of classes as shown earlier in the first Motivation diagram. Such a class hierarchy indicates the need for splitting an object into two parts.
178 •
You want to share an implementation among multiple objects (perhaps using reference counting), and this fact should be hidden from the client.
Example:
Figure 42
179
Composite: The goal of this pattern is to compose objects into tree structures to represent part-whole hierarchies. Composite lets clients treat individual objects and compositions of objects uniformly. It is used when you want to represent part-whole hierarchies of objects. Or when you want clients to be able to ignore the difference between compositions of objects and individual objects. Clients will treat all objects in the composite structure uniformly. Structure:
Figure 43
180 Example:
Figure 44
Code that uses these classes must treat primitive and container objects differently; even if most of the time the user treats them identically. Having to distinguish these objects makes the application more complex. The Composite pattern describes how to use recursive composition so that clients don't have to make this distinction.
181
Decorator: It used to attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality.
Figure 45
Use Decorador in the next cases: •
To add responsibilities to individual objects dynamically and transparently, that is, without affecting other objects.
•
For responsibilities that can be withdrawn.
•
When extension by subclassing is impractical. Sometimes a large number of independent extensions are possible and would produce an explosion of subclasses to support every combination. Or a class definition may be hidden or otherwise unavailable for subclassing.
182
Facade: It provides a unified interface to a set of interfaces in a subsystem. Facade defines a higher-level interface that makes the subsystem easier to use. Structuring a system into subsystems helps reduce complexity. A common design goal is to minimize the communication and dependencies between subsystems. One way to achieve this goal is to introduce a facade object that provides a single, simplified interface to the more general facilities of a subsystem.
Figure 46
Structure:
Figure 47
183 Use the Facade pattern when: •
You want to provide a simple interface to a complex subsystem. Subsystems often get more complex as they evolve. Most patterns, when applied, result in more and smaller classes. This makes the subsystem more reusable and easier to customize, but it also becomes harder to use for clients that don't need to customize it. A facade can provide a simple default view of the subsystem that is good enough for most clients. Only clients needing more customizability will need to look beyond the facade.
•
There are many dependencies between clients and the implementation classes of an abstraction. Introduce a facade to decouple the subsystem from clients and other subsystems, thereby promoting subsystem independence and portability.
•
You want to layer your subsystems. Use a facade to define an entry point to each subsystem level. If subsystems are dependent, then you can simplify the dependencies between them by making them communicate with each other solely through their facades.
184 Example:
Figure 48
The Compiler class acts as a facade: It offers clients a single, simple interface to the compiler subsystem. It glues together the classes that implement compiler functionality without hiding them completely.
185
Flyweight: Use sharing to support large numbers of fine-grained objects efficiently. Some applications could benefit from using objects throughout their design, but a naive implementation would be prohibitively expensive. A flyweight is a shared object that can be used in multiple contexts simultaneously. The flyweight acts as an independent object in each context, it's indistinguishable from an instance of the object that's not shared. Flyweights cannot make assumptions about the context in which they operate. The key concept here is the distinction between intrinsic and extrinsic state. Intrinsic state is stored in the flyweight; it consists of information that's independent of the flyweight's context, thereby making it sharable. Extrinsic state depends on and varies with the flyweight's context and therefore can't be shared. Client objects are responsible for passing extrinsic state to the flyweight when it needs it.
Figure 49
186 The following object diagram shows how flyweights are shared:
Figure 50
The Flyweight pattern's effectiveness depends heavily on how and where it's used. Apply the Flyweight pattern when all of the following are true: •
An application uses a large number of objects.
•
Storage costs are high because of the sheer quantity of objects.
•
Most object state can be made extrinsic.
•
Many groups of objects may be replaced by relatively few shared objects once extrinsic state is removed.
•
The application doesn't depend on object identity. Since flyweight objects may be shared, identity tests will return true for conceptually distinct objects.
187
Proxy: It is used to provide a surrogate or placeholder for another object to control access to it. One reason for controlling access to an object is to defer the full cost of its creation and initialization until we actually need to use it. Structure:
Figure 51
Object Diagram:
Figure 52
Proxy is applicable whenever there is a need for a more versatile or sophisticated reference to an object than a simple pointer.
188 Example:
Figure 53
The document editor accesses embedded images through the interface defined by the abstract Graphic class. ImageProxy is a class for images that are created on demand. ImageProxy maintains the file name as a reference to the image on disk. The file name is passed as an argument to the ImageProxy constructor. ImageProxy also stores the bounding box of the image and a reference to the real Image instance. This reference won't be valid until the proxy instantiates the real image. The Draw operation makes sure the image is instantiated before forwarding it the request. GetExtent forwards the request to the image only if it's instantiated; otherwise ImageProxy returns the extent it stores.
189 3. Behavioural Patterns: Behavioural patterns are concerned with algorithms and the assignment of responsibilities between objects. Behavioural patterns describe not just patterns of objects or classes but also the patterns of communication between them. These patterns characterize complex control flow that's difficult to follow at run-time. They shift your focus away from flow of control to let you concentrate just on the way objects are interconnected. Behavioural class patterns use inheritance to distribute behaviour between classes. Behavioral object patterns use object composition rather than inheritance.
190
Chain of Responsibility: The intention of this pattern is to avoid coupling the sender of a request to its receiver by giving more than one object a chance to handle the request. Chain the receiving objects and pass the request along the chain until an object handles it. The idea of this pattern is to decouple senders and receivers by giving multiple objects a chance to handle a request. The request gets passed along a chain of objects until one of them handles it.
Figure 54
Use Chain of Responsibility in the next cases: •
More than one object may handle a request, and the handler isn't known a priori. The handler should be ascertained automatically.
•
You want to issue a request to one of several objects without specifying the receiver explicitly.
•
The set of objects that can handle a request should be specified dynamically.
191
Command: The intention is to encapsulate a request as an object, thereby letting you parameterize clients with different requests, queue or log requests, and support undoable operations.
Figure 55
Use the Command pattern when you want to: •
Parameterize objects by an action to perform, as MenuItem objects did above. You can express such parameterization in a procedural language with a callback function, that is, a function that's registered somewhere to be called at a later point. Commands are an objectoriented replacement for callbacks.
•
Specify, queue, and execute requests at different times. A Command object can have a lifetime independent of the original request. If the receiver of a request can be represented in an address spaceindependent way, then you can transfer a command object for the request to a different process and fulfill the request there.
192 •
Support undo. The Command's Execute operation can store state for reversing its effects in the command itself. The Command interface must have an added Unexecute operation that reverses the effects of a previous call to Execute. Executed commands are stored in a history list. Unlimited-level undo and redo is achieved by traversing this list backwards and forwards calling Unexecute and Execute, respectively.
•
Support logging changes so that they can be reapplied in case of a system crash. By augmenting the Command interface with load and store operations, you can keep a persistent log of changes. Recovering from a crash involves reloading logged commands from disk and reexecuting them with the Execute operation.
•
Structure a system around high-level operations built on primitives operations. Such a structure is common in information systems that support transactions. A transaction encapsulates a set of changes to data. The Command pattern offers a way to model transactions. Commands have a common interface, letting you invoke all transactions the same way. The pattern also makes it easy to extend the system with new transactions.
193
Interpreter: this pattern is used when given a language; we want to define a representation for its grammar along with an interpreter that uses the representation to interpret sentences in the language. Structure:
Figure 56
It’s recommended to use the Interpreter pattern when there is a language to interpret, and you can represent statements in the language as abstract syntax trees. The Interpreter pattern works best in the following cases: •
The grammar is simple. For complex grammars, the class hierarchy for the grammar becomes large and unmanageable. Tools such as parser generators are a better alternative in such cases. They can interpret expressions without building abstract syntax trees, which can save space and possibly time.
•
Efficiency is not a critical concern. The most efficient interpreters are usually not implemented by interpreting parse trees directly but by first translating them into another form. For example, regular expressions are often transformed into state machines. But even then, the translator can be implemented by the Interpreter pattern, so the pattern is still applicable.
194 Example:
Figure 57
195
Iterator: It provides a way to access the elements of an aggregate object sequentially without exposing its underlying representation. An aggregate object such as a list should give you a way to access its elements without exposing its internal structure. Moreover, you might want to traverse the list in different ways, depending on what you want to accomplish. But you probably don't want to bloat the List interface with operations for different traversals, even if you could anticipate the ones you will need. You might also need to have more than one traversal pending on the same list. The Iterator pattern lets you do all this. The key idea in this pattern is to take the responsibility for access and traversal out of the list object and put it into an iterator object. The Iterator class defines an interface for accessing the list's elements. An iterator object is responsible for keeping track of the current element; that is, it knows which elements have been traversed already. Structure:
Figure 58
196 Cases when we should use this pattern: •
To access an aggregate object's contents without exposing its internal representation.
•
To support multiple traversals of aggregate objects.
•
To provide a uniform interface for traversing different aggregate structures (that is, to support polymorphic iteration).
Example using lists:
Figure 59
197
Mediator: the idea is to define an object that encapsulates how a set of objects interact. Mediator promotes loose coupling by keeping objects from referring to each other explicitly, and it lets you vary their interaction independently. Though partitioning a system into many objects generally enhances reusability, proliferating interconnections tend to reduce it again. Lots of interconnections make it less likely that an object can work without the support of others; the system acts as though it were monolithic. Moreover, it can be difficult to change the system's behavior in any significant way, since behavior is distributed among many objects. As a result, you may be forced to define many subclasses to customize the system's behavior. The mediator is used to avoid problems handling the relations between multiple objects. The idea is encapsulating collective behavior in a separate mediator object. A mediator is responsible for controlling and coordinating the interactions of a group of objects. The mediator serves as an intermediary that keeps objects in the group from referring to each other explicitly. The objects only know the mediator, thereby reducing the number of interconnections. Structure:
Figure 60
198 We use the Mediator pattern when: •
A set of objects communicate in well-defined but complex ways. The resulting interdependencies are unstructured and difficult to understand.
•
Reusing an object is difficult because it refers to and communicates with many other objects.
•
A behaviour that's distributed between several classes should be customizable without a lot of subclassing.
199
Memento: The intention is that, without violating encapsulation, capture and externalize an object's internal state so that the object can be restored to this state later. Sometimes it's necessary to record the internal state of an object. This is required when implementing checkpoints and undo mechanisms that let users back out of tentative operations or recover from errors. You must save state information somewhere so that you can restore objects to their previous states. But objects normally encapsulate some or all of their state, making it inaccessible to other objects and impossible to save externally. Exposing this state would violate encapsulation, which can compromise the application's reliability and extensibility. Structure:
Figure 61
Use the Memento pattern when: •
A snapshot of (some portion of) an object's state must be saved so that it can be restored to that state later, and
•
A direct interface to obtaining the state would expose implementation details and break the object's encapsulation.
200
Observer: the goal is to define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically. A common side-effect of partitioning a system into a collection of cooperating classes is the need to maintain consistency between related objects. You don't want to achieve consistency by making the classes tightly coupled, because that reduces their reusability. The Observer pattern describes how to establish these relationships. The key objects in this pattern are subject and observer. A subject may have any number of dependent observers. All observers are notified whenever the subject undergoes a change in state. In response, each observer will query the subject to synchronize its state with the subject's state. Structure:
Figure 62
201 Use the Observer pattern in any of the following situations: •
When an abstraction has two aspects, one dependent on the other. Encapsulating these aspects in separate objects lets you vary and reuse them independently.
•
When a change to one object requires changing others, and you don't know how many objects need to be changed.
•
When an object should be able to notify other objects without making assumptions about who these objects are. In other words, you don't want these objects tightly coupled.
202
State: The intent is to Allow an object to alter its behavior when its internal state changes. The object will appear to change its class. Structure:
Figure 63
We recommend using this pattern in either of the following cases: •
An object's behaviour depends on its state, and it must change its behaviour at run-time depending on that state.
•
Operations have large, multipart conditional statements that depend on the object's state. This state is usually represented by one or more enumerated constants. Often, several operations will contain this same conditional structure. The State pattern puts each branch of the conditional in a separate class. This lets you treat the object's state as an object in its own right that can vary independently from other objects.
203 Example:
Figure 64
The class TCPConnection maintains a state object (an instance of a subclass of TCPState) that represents the current state of the TCP connection. The class TCPConnection delegates all state-specific requests to this state object. TCPConnection uses its TCPState subclass instance to perform operations particular to the state of the connection. Whenever the connection changes state, the TCPConnection object changes the state object it uses. When the connection goes from established to closed, for example, TCPConnection will replace its TCPEstablished instance with a TCPClosed instance.
204
Strategy: The idea is to define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it. Many algorithms exist for breaking a stream of text into lines. Hardwiring all such algorithms into the classes that require them isn't desirable for several reasons: •
Clients that need linebreaking get more complex if they include the linebreaking code. That makes clients bigger and harder to maintain, especially if they support multiple linebreaking algorithms.
•
Different algorithms will be appropriate at different times. We don't want to support multiple linebreaking algorithms if we don't use them all.
•
It's difficult to add new algorithms and vary existing ones when linebreaking is an integral part of a client.
We can avoid these problems by defining classes that encapsulate different linebreaking algorithms. An algorithm that's encapsulated in this way is called a strategy. Structure:
Figure 65
205 Use the Strategy pattern when: •
Many related classes differ only in their behaviour. Strategies provide a way to configure a class with one of many behaviours.
•
You need different variants of an algorithm. For example, you might define algorithms reflecting different space/time trade-offs.
•
An algorithm uses data that clients shouldn't know about. Use the Strategy pattern to avoid exposing complex, algorithm-specific data structures.
•
A class defines many behaviours, and these appear as multiple conditional statements in its operations. Instead of many conditionals, move related conditional branches into their own Strategy class.
206
Template Method: The goal is to define the skeleton of an algorithm in an operation, deferring some steps to subclasses. Template Method lets subclasses redefine certain steps of an algorithm without changing the algorithm's structure. Structure:
Figure 66
The Template Method pattern should be used in the following cases: •
To implement the invariant parts of an algorithm once and leave it up to subclasses to implement the behaviour that can vary.
•
When common behaviour among subclasses should be factored and localized in a common class to avoid code duplication.
•
To control subclasses extensions. You can define a template method that calls "hook" operations (see Consequences) at specific points, thereby permitting extensions only at those points.
207
Visitor: The intention is to represent an operation to be performed on the elements of an object structure. Visitor lets you define a new operation without changing the classes of the elements on which it operates. Structure:
Figure 67
208 Use the Visitor pattern when: •
An object structure contains many classes of objects with differing interfaces, and you want to perform operations on these objects that depend on their concrete classes.
•
Many distinct and unrelated operations need to be performed on objects in an object structure, and you want to avoid "polluting" their classes with these operations. Visitor lets you keep related operations together by defining them in one class. When the object structure is shared by many applications, use Visitor to put operations in just those applications that need them.
•
The classes defining the object structure rarely change, but you often want to define new operations over the structure. Changing the object structure classes requires redefining the interface to all visitors, which is potentially costly. If the object structure classes change often, then it's probably better to define the operations in those classes.
209 4.2
ENTERPRISE APPLICATIONS DESIGN PATTERNS
No we will take a closer look to the patterns that are commonly used on the development of enterprise applications. These patterns are call J2EE Core patterns and are essential for the design of enterprise application using the J2EE platform. Most of them are related with the EJB technology; trying to solve the main problems the developers face when using this technology. We are going to focus on the patterns from the Data and Model layer. We will use the following convention to describe the patterns (when available): Intention Also know as Motivation Applicability Structure Participants Collaborations Consequences Implementation Related patterns
210 4.2.1
Session Facade
Intention To provide a simple interface that supports a group of related use cases. It is an application of the Facade pattern. It represents workflow and not persistence. It can be use with EJB or not. Motivation Provide a simple interface that supports a group of related use cases (in general, an operation for each use case), hiding those existent relations on the implementation of each use case. Additionally, when EJB is used, tries to decrease the number of remote invocations and to avoid that the client has to use the transactions API. Applicability o When we want to offer a simplified version of a group of EJBs. o When we want to decrease the number of remote invocations from the client layer.
211 Structure (EJB):
Figure 68
Participants o Client: Can be a Business Delegate or another Session Facade. o SessionFacade: Usually, a Session Bean. Provides a simple interface to the client, hiding the relations among numerous business objects. o Business Object: Provides data (Entity Bean or DAO) or a service (Session Bean). Collaborations A SessionFacade coordinates a group of business objects to implement a group of related use case. Consequences o Simplifies the maintenance. o Reduces the number of remote invocations. o Simplifies the transactions administration.
212 Implementation It can be done with SLSB or SFSB EJBs depending if we want to save the state or nor when using EJB. Without EJB is implemented with a Java class. One problem with this pattern is that sometimes the Session Facade is too big and gets difficult to maintain and the performance decreases considerably. It recommendable that the Session Facade only implements operations that are 4 or 5 lines of code, delegating in other classes to implement bigger operations. Related patterns o Facade o Data Access Object o Service Locator o Business Delegate
213 4.2.2
Business Delegate
Intention Hides the technologies used in the model. Business Delegate usually always hides a Session Facade. o Without EJB, Business Delegate and Session Facade will be the same (no distributed environment). o With EJB, Business Delegate will be a proxy (local object) of Session Facade (remote object) Motivation In EJB, it facilities the client access to the EJB layer, hiding the EJB API. The Controller will access the model thru an interface that hides the technology used to implement the business logic. Applicability When we want to provide an access layer to the model that hides the technology used in the implementation. Structure
Figure 69
214 Participants o BusinessDelegate: Uses ServiceLocator to obtain a reference to the BusinessServiceFactory. It creates a BusinessService (using BusinesServiceFactory) who is the one that we delegate the operations. o BusinessService: it is Usually a Session Bean. o BusinessServiceFactory: Usually the Home interface of a Session Bean. o ServiceLocator: Allows to obtain a reference to BusinessServiceFactory (usually using JNDI). Collaborations The BusinessDelegate constructor uses a ServiceLocator to obtain a BusinessServiceFactory and to create a BusinessService in which will delegate all their operations. Consequences o Improves the maintenance. o Allows jobs separation: client layer developers and EJB layer developers. o Can provide cache to improve the efficiency. Implementation It is Java class with its methods synchronized. They have to be serializable when we need to keep the session. Related patterns o Proxy o Service Locator o Session Facade
215 4.2.3
Service Locator
Intention Have a generic mechanism that allows to obtain and to search references to Home interfaces. Also know as EJBHomeFactory Motivation The references to any Home Interface, local or remote, are obtained in a similar way. To obtain a reference to a Home Interface has certain computational cost associate, especially when the name service is on another machine.
Figure 70
EJBLocalHomeLocator and EJBHomeLocator search the references to the Home interfaces.
216 Applicability When we need to obtain references to Home interfaces. Structure
Figure 71
Participants o ServiceLocator: Obtains and searches references to Home interfaces. o Client: An EJB (usually a Session Bean) or a Business Delegate. o EJBHome: The Home interface of an EJB (Session Bean or Entity Bean). Collaborations A Service Locator obtains and it searches references to Home Interfaces. Consequences o Abstracts the way to obtain references to interfaces Home o Avoids replying code of obtaining references to Home interfaces. o Cache improves the efficiency. Related patterns o Factory
217 4.2.4
Value Object
Intention Group attributes coming from one or several domain objects. Also know as Transfer Object, Data Transfer Object, Replicate Object. Motivation Data access. Applicability When we need to represent a group of attributes coming from one or several domain objects.
Structure
<> java.io.Serializable
VO Attrbutes
<> DAO
get/set()
Figure 72
218
Participants o VO: Offers get/set methods to access to its attributes. o DAO: Has access to the values that are copied in the VO. The Session Facade (Business Delegates) also work with VOs. Collaborations A DAO returns VOs in its methods findXXX, and receives them in their methods create and update Consequences o Benefits
In the EJB context, efficiency. The CMP Beans are too slow and sometimes is better to write VOs and DAOs. Also produces less remote calls.
In the JDBC context, to be able to represent a group of attributes coming from one or several domain objects.
o Risks
A VO can contain obsolete information if we pretend to use it in a later update in another transaction.
219 Implementation We have to differentiate two kinds of VO: − Domain Value Objects: This kind of VO contains all attributes from the domain object and is reusable between applications because it has an exactly correspondence with a domain object. DAOs should only work with this kind of VOs to maintain the reusability. − Custom Value Objects: These VOs only have the necessary attibites to implement one use case. They are dependent from the application and are not reusable. This objects shouldn’t be used with DAOs, instead, they should be use by the Session Facades because they are application specific. These VOs are use to increase efficiently when implementing a specific use case. For example, if we have an object Car with 100 attributes and one use case only needs to get the engine attributes a custom value object can be use to represent that information and should be used only for the session facade.
Figure 73
HashMaps: It is possible than in an application we need a big number of VOs and this cause a maintenance problem. In this case, the solution is to use Java HashMaps to retrieve pairs: Related patterns o Page-by-Page Iterator. o Session Facade.
220 4.2.5
Value Object (EJB)
There are some differences when we use EJB with this pattern. Intention To allow efficient exchange of data between the client and EJB layers. Also know as Transfer Object, Data Transfer Object, Replicate Object Motivation Decrease the number of remote calls. Applicability When we need to access (read or modification) to a group of data coming from one or several business objects.
221 Structure
<> java.io.Serializable
<