<<

Session: L12

Hitchhikers Guide to JEE

Gary Ben-Israel National Institute for Testing & Evaluation

May 10, 2007 9:20 a.m. – 10:20 a.m.

Platform: Cross Platform

1 Agenda

• What is Enterprise Edition • The Web container • The EJB Container

2

2 Agenda

• What is Java Enterprise Edition • Definition • The three tier model • UI Design • The Web container • The EJB Container

3

3 What is Java Enterprise Edition Java Platform, Enterprise Edition (Java EE) • Is the industry standard for developing portable, robust, scalable and secure server-side Java applications. • Built on the solid foundation of Java SE • Provides web services, component model, management, and communications APIs • Is the industry standard for implementing enterprise class service-oriented architecture (SOA) and Web 2.0 applications.

4

4 JEE three tier model

5

5 UI Design

• UI Solutions • Rich Client Vs. Thin Client

6

6 UI Solutions

• Rich Client (Desktop Applications) • Thin Client (Classic web Applications)

Both address similar missions:

Event handling Layouting Data Binding Input validation Navigation flow I18N (Internationalization) Serialization L10N (Localization)

7

7 Rich Client Vs. Thin Client

☺ Asynchronous Synchronous Uninterrupted user UI reloaded and rendered interaction with each request

☺ Client-side logic may be Client-side logic may be implemented in Java implemented in Javascript

Requires Installation ☺Runs anywhere Multiple client With a browser deployments

8

8 Agenda

• What is Java Enterprise Edition • The Web container • The framework universe • Why so many? • Framework categories • • The EJB Container

9

9 The framework universe is vastly hugely mind-bogglingly big

Wicket WebObjects Chrysalis OpenEmcee FacesFreeway Struts JPublish (OpenLaszlo) Scope JSPWidget JSF VRaptor Warfare Caramba WebWork ThinkCap JX Swinglets JWAA Xopolon Spring MVC OXF wingWeb Helma Tapestry Canyamo Verge Jacuard Cocoon Anvil XUI Macaw And Turbine Jaffa Japple JOSSO many Expresso Millstone ZK XAMJ Maverick Jucas Bishop Smile More… Echo2 (FreeMarker) SwingWeb Chiba Sofia (Velocity) Weblets JBanana JATO Common Controls Baracuda Jeenius Rialto Folium Action Framework JWarp Dinamica Click Shocks Genie EchoPoint JAT TeaServlet Avatar SWF MyFaces wingS Dovetail Hijax Facelets Bento Cameleon OpenXava WebOnSwing jStateMachine JFormulator RIFE DWR jZonic Melati Trails Thinlet qooXdoo10 Struts Ti

10 Why so many?

• Different needs • A bad case of NIH syndrome • It’s fun writing • The de-facto standard isn’t good enough • No framework is good enough (we got to have more!)

11

11 Framework categories

• Action-Based frameworks • Struts, WebWork (Struts 2), Spring-MVC • Component oriented frameworks • Wicket, Tapestry, Facelets (JSF), Echo2, ZK, Zimbra, Millstone • Template Engines integration • FreeMarker, Velocity, JSP, Tiles, Tapestry, Facelets (JSF) • Full Stack frameworks • RIFE • CRUD applications frameworks (Influenced by ) • Trails, FacesFreeway, Struts Ti, RIFE-CRUD

12

12 AJAX Basics

Asynchronous Javascript + XML(HttpRequest) Not a single technology but a methodology • Built on two standards: • XMLHttpRequest • DOM (XHTML) • Relies on Javascript availability

13

13 Classic web

14

14 AJAX layer added

15

15 AJAX: to the server and back again

16

16 AJAX Consequences

Mostly great but…

• May increase server load • User interaction is innately synchronous • May require specialized, “dirty” model behavior • No common user experience (the Feel in L&F)

17

17 The EJB Container

• Entity beans • Session beans • Message Driven Beans • Resource Management and Primary Services

18

18 Entity Beans Entity beans in Java Persistence 1.0 specification are available only as plain old java objects (POJOs). To implement an entity bean you need to define a bean class and decide what field you will use as the identifier (primary key) of that identifier. In Java persistence, entity beans are not components like their EJB 2.1 counterparts. Application code works directly with the bean. So how is an entity queried? How is it stored? Is some magic involved? NO. Interaction with entity beans is done via a new service called the EntityManager. No Magic. No bytecode manipulation. No special proxies. Just Plain Java. 19

Unlike other EJB types entities can be allocated, serialized and sent across the network like any other POJO.

Entity beans model real world objects. These objects are usually persistent records in some kind of . In Java persistence application code works directly with the entity bean and does not interact through a component interface as you would with an EJB Session bean.

19 Entity bean example

import javax.presistence; @Entity @Table(name=“CABIN”) public class Cabin { private int id; private string name; @Id @GeneratedValue @Column(name=“CABIN_ID”) public int getId() { return id } public void setId(int pk) { this.id = pk; } @Column(name=“CABIN_NAME”) public string getName() { return name; } public void setName(string str) { this.name = str; } }

20

20 Session beans

• Definition • Interfaces • Stateful and Stateless session beans

21

21 Definition • Session beans are server side components that can be accessed using a variety of distributed object protocols. They are an extension of the client application that manage processes or tasks. • Example: A ship entity provides methods for doing things directly to a ship, but it doesn’t say anything about the context under which those actions are taken. • Session beans act as agents that manage business processes or tasks for the client. • Session beans are not persistent. They work with entity beans, data, and other resources to control workflow.

22

Booking passengers on a ship requires a ship entity, but also requires a lot of things that have nothing to do with the ship itself. We’ll need to know about passengers, ticket rates, schedules, and so on.

22 Interfaces

To implement a session bean you need to define their interfaces. • Remote interface The remote interface defines a session bean’s business methods, which can be accessed from applications outside the EJB container. • Local interface The local interface defines a session bean’s business methods that can be used by other beans in the same EJB container. • Endpoint interface The endpoint interface defines business methods that can be accessed from applications outside the EJB container via SOAP.

23

The session bean class contains business logic and must have at least one remote, local or endpoint interface. bean class may also have more then one interface of a given type. The EJB container usually determines whether a session bean is remote and/or local by the interfaces it implements. The session bean class must also be tagged with the @javax.ejb.stateful or @javax.ejb.stateless annotation so that the EJB container knows what session bean type it is.

23 Stateful and Stateless session beans

Session beans can be either stateful or stateless • Stateful session beans maintain conversational state when used by a client. Conversational state is not written to a database. It’s information that is kept in memory during the conversation and is lost when the conversation ends. • Stateless session beans do not maintain any conversational state. Each method is completely independent and uses only data passed in it’s parameters. Stateless session beans provide better performance and consume fewer resources then entity and stateful session beans.

24

Conversational state is kept only as long as the client application is using the bean. Once the client shuts down or releases the EJB, the conversational state id lost forever. Stateful session beans are not shared among clients;they are dedicated to the same client for the life of the enterprise bean. A few stateless session beans can serve hundreds and possibly thousands of clients.

24 Message Driven Beans • Message driven beans are integration points for other applications interested in working with EJB applications. • EJB 3.0 is not limited to JMS based message driven beans. Message driven beans can support any messaging system the implements the correct JCA 1.5 contracts. • In many ways the message driven beans are like stateless session beans. But unlike session beans that respond to business method invoked on their component interfaces, a JMS MDB responds to messages delivered through its onMesage() method. Since the messages are asynchronous the client that sends them does not expect a reply.

25

EJB 3.0 is not limited to JMS based message driven beans. Message driven beans can support any messaging system the implements the correct JCA 1.5 contracts. However, support for JMS based message driven beans in EJB 3.0 is mandatory.

25 Resource Management and Primary Services

• Instance pooling • The activation mechanism • Java EE connector architecture • Primary services

26

26 Instance pooling • It’s common to pool database connections so that business objects in the system can share database access. • Most EJB containers also apply resource pooling to server side components. This technique is called instance pooling. Instance pooling is possible because clients never access beans directly. Therefore, there’s no fundamental reason to keep a separate copy of each EJB for each client. • Stateless beans exist in one of 3 states: • No state • Pooled state • Ready state

27

The server can keep a much smaller number of enterprise beans around to do the work, reusing each enterprise bean object to service different requests. No state When a bean instance is in this state it has not yet been instantiated. We identify this state to provide a beginning and end for the life cycle of a bean instance. Pooled state When an instance is in this state., it has been instantiated by the container but has not yet been associates eith an EJB request. Ready State When a bean instance id in this state, it has been associated with an EJB request and is ready to respond to business method invocation.

27 The activation mechanism • Unlike other enterprise beans stateful session beans maintain state between method invocations. Hence they cannot participate in instance pooling. • Passivation is the act of disassociating a stateful bean instance from its EJB object and saving its state. After the bean has passivated it is safe to remove the bean from the EJB object and evict it from memory. • Activating Is the act of restoring a stateful bean instance’s state relative to its EJB object. When a method on a passivated EJB object is invoked, the container automatically creates a new instance and sets its fields equal to the data stored during passivation.

28

Conversational state represents the continuing conversation with the stateful session bean’s client. Clients are unaware of the deactivation process. Remember that the client uses the bean’s remote interface which is implemented by an EJB stub proxy, and therefore dose not directly communicate with the bean instance. As a result client’s connection to the EJB Object can be maintained while the bean is passive. Note that the transient property is not treated as you might expect when activating a passivated bean. In EJB transient fields are not necessarily set back to their initial values but can maintain their original values.

28 Java EE connector architecture

The Java EE connector Architecture (JCA) defines an interface between Enterprise Information systems (EIS) and Java EE container systems. • JCA 1.5 defines a portable programming model for interfacing with EIS. The use of JCA in Java EE is analogous to the use of USB in computer hardware. An EJB 3.0 container that supports JCA 1.5 can interface with any JCA 1.5 compliant resource.

29

Java EE defines a number of enterprise APIs, including JDBC, JMS, JNDI, Java IDL, and JavaMail, in addition to EJB. Although the enterprise APIs are vendor agnostic the products behind them are not. EJB 2.0 required support for the new Java EE connector architecture, which went a long way toward solving this problem. However it did not go far enough. In particular it did not support the push model for messaging. Both EJB 2.1 and EJB 3.0 require support for JCA 1.5 which supports the push model.

29 Primary services • Concurrency • Transactions • Persistence • Distributed objects • Asynchronous messaging • Timer service • Naming • Security • Authentication • Authorization • Secure communication

30

Concurrency Session beans do not support concurrent access. A stateful bean is an extension of one client and serves only that client. It doesn’t make sense to make stateful beans concurrent if they are used only by the client that created them. Stateless session eans don’t need to be concurrent because they do not maintain state that needs to be shared. Entity beans represent data that is shared and may be accessed concurrently. In Java persistence specification, the persistent container protects shared entity data by making a copy of the entity bean instance on a per transaction basis. In Message driven beans, concurrency refers to the processing of more then one message at a time. Transactions A transaction is a unit of work or a set of tasks that are executed together. Persistence In an object-oriented application persistence allows an object to outlive the process that created it. Distributed objects Supporting non Java remote clients via RMI-IIOP and JAX-RPC protocols. Asynchronous messaging. Support of enterprise messaging requires that the EJB container reliably route messages from JMS clients to JMS-MDBs. EJB Timer service The EJB timer service can be used to schedule notifications that are sent to enterprise beans at specific times. Naming Provide clients with a mechanism for locating distributed objects or resources.

30 The persistence layer

• Persistence in object oriented application • The Paradigm mismatch • Persistence alternatives

31

31 Persistence in object oriented application

In an object-oriented application persistence allows an object to outlive the process that created it.

When we talk about persistence in Java we ‘re normally talking about storing data in a relational database using SQL.

The object-oriented program uses a Domain model The relational database uses a relational model

32

32 The Paradigm mismatch

• The problem of granularity • The problem of subtypes • The problem of Identity • Problems related to associations • Problem of object graph navigation • The cost of the mismatch

33

33 The problem of granularity Granularity refers to the relative size of the objects you’re working with. As an example let’s look at the address fields in a RDBMS table user. In Java we will have an address class. We can us UDTs but they are poorly supported by SQL and not portable between different . The standard solution will be to map the address class to: create table user( name varchar(50), address_street varchar(50), adress_city varchar(15), adress_state varchar(15), adress_zipcode varchar(15) ) 34

34 The problem of subtypes In Java we implement inheritance using a super and sub class. Let’s look at the following example:

1.. * User BillingDetails

CreditCard BankAccount

In an SQL database we can’t declare that credit_card_details table is a subtype of billing_details by: create table credit_card_details extends billing_details. Hence it is not surprising that SQL will not support polymorphisem 35

35 The problem of Identity

Java objects define two different notations of sameness: • Object identity (Checked with a==b) • Equality as determined by the implementation of the equals() method. On the other hand identity of a database row is expressed as the primary key value. Neither equals() nor == is naturally equivalent to the primary key value.

36

36 Problems related to associations

Object-oriented languages represent association using object references and collections of object references. In the relational world, an association is represented by a foreign key column. Object references are inherently directional, from one object to another. If you need both directions you must define the association twice. Once in each class. Java associations can be many to many. If you have a many to many relationship in a relational database using a link table, this table doesn’t appear anywhere in the object model.

37

37 Problem of object graph navigation In Java when you access the billing information of a user you call aUser.getBillingDetails().getAccountNumber() This is often described as walking the object graph. Unfortunately this is not an efficient way to retrieve data from an SQL database. In the database you would want to use a join to minimize the number of SQL queries.

This mismatch in the way we access objects in Java and in a relational database is perhaps the single most common source of performance problems in Java applications.

38

38 The cost of the mismatch • About 30% of the Java application code handles the tedious SQL/JDBC and the manual bridging of object/relational paradigm mismatch. • This can be done successfully, but only at the cost of loosing some of the advantages of object orientation. • Another cause of inflexibility is the JDBC API itself. JDBC and SQL provide statement approach for moving data to and from the database. A structural relationship must be defined 3 times (Insert, Update, Delete) adding to the time required for design and implementation. • The dialect for every SQL database doesn’t improve the situation

39

39 Persistence alternatives

• Hand-coding a persistence layer with SQL/JDBC • Using Serialization • Other options • ORM – Object/Relational Mapping • Why ORM

40

40 Hand-coding a persistence layer with SQL/JDBC

• The most common approach to Java persistence is to work directly with SQL and JDBC. • You can always use a well known and widely used DAO (Data Access Object) design pattern to hide complex JDBC code and none portable SQL from the business logic. • However, the work involved in manually coding persistence for each domain class is considerable particularly when multiple SQL dialects are supported.

41

41 Using Serialization • Java has a built-in persistence mechanism: serialization provides the ability to write a graph of objects to a byte-stream which may then be persisted to a file or a database. • Why not us serialization for the persistent layer? Unfortunately, a serialized graph of interconnected objects can only be accessed as a whole. • Thus, the resulting byte-stream is unsuitable for arbitrary search or aggregation. It isn’t even possible to access or update a single object or subgraph independently. • Clearly, serialization is inadequate as a persistence mechanism for high concurrency web and enterprise applications.

42

42 Other options

• XML persistence. This is a variation on the serialization theme. It addresses some of the limitations of the byte-stream serialization but is itself subject to an object/hierarchical impedance mismatch. Further more there is no additional benefit from XML because it’s just another text file format. • Using stored procedures (Even write them as Java UDRs) and move the problem into the database tier. • There are plenty of other examples but none of them are likely to become popular in the immediate future.

43

43 Object Relational Mapping (ORM) • Java persistence is a plain java based model (POJO) • Entities can be created outside the scope of the EJB container. • They are allocated using the new() operator. • Bean instances are attached to persistence storage through the EntytyManager service. • The EntytyManager service provides methods to create, find, query, remove and update entity beans. • When a bean instance is attached, the container manages the persistent state of the bean and automatically synchronizes the bean with its data source.

44

An interesting thing about the Java persistence model is that bean instances can be detached from the EJB container. Bean instances are usually detached from the EJB container when a transaction completes. These detached instances can be sent around the network to a remote clients or even saved to disk. The Java persistence specification provides rich relational database mapping with advanced features such as inheritance, multitable mappings, versioning and extended EJBQL support.

44 Why ORM • Productivity Persistence-related code can be the most tedious code in a java application. The ORM eliminates much of the grunt work and lets you concentrate on the business problem. • Maintainability Fewer line of code makes the system more understandable and easier to refactor. ORM provides a buffer between the two models, allowing more elegant use of object orientation on the Java side, and insulating each model form minor changes to the other. • Performance • Vendor independence

45

Since O/R mapping is mandated by the specification it makes EJB applications much more portable between vendors

45 A none-benefit A supposed advantage of ORM is that it “shields” developers from “messy” SQL. This view holds that object-oriented developers can’t be expected to understand SQL and find it somehow offensive.

On the contrary, Java developers must have a sufficient level of familiarity with, and appreciation of, SQL in order to work with ORM.

To use an ORM effectively, you must be able to view and interpret the SQL statements it issues and understand the implications for performance.

46

46 Questions

47

47 Session: L12 Hitchhikers Guide to JEE

Gary Ben-Israel

National Institute for Testing & Evaluation [email protected]

48

48