EJB

advertisement

EJB

"Enterprise Java Beans"

Containers and components –

Practical!

1

EJB

• Heavyweight applications!

• EJB is NOT the technology that you should use to handle typical web-applications with a few forms accessing a single data table

– Servlet/JSP technology is appropriate in that context

• EJB should be considered for

– Applications where "distributed transactions" are needed (actually relatively rare!)

– Applications where you want both

• A web-app client (possibly using a subset of features of sever components)

• A "professional client" – systems administrator, advanced user (in house use)

– Applications with a large number of servlets containing related business logic – may be better to move all the business logic into a single session bean

– Applications used by other applications (your own "generic" services) – optionally these days using XML based RPC protocols

2

EJB

• Early objectives

– Distributed, transactional applications

– Automated data persistence

– Reusable business components

– Binary compatibility of components across different implementations of EJB

– Declarative style deployments

• Many of these objectives exceed actual needs of most business applications; consequently, EJB became viewed as overly complex and lost favour to lightweight frameworks such as Spring

3

EJB – 1 – 2 - 3

• An evolving technology

– 1998 EJB-1.0

– 1999 EJB-1.1

– 2001 EJB-2

– 2003 EJB-2.1

– 2006 EJB-3

4

EJB – 1

• Largely Sun (though some IBM contribution)

• A subset of early version of CORBA Component Model for building distributed transactional business systems

• Framework

– Lifecycle management of server objects ("beans")

• Session objects (stateless and stateful)

• Entity objects (optional in EJB-1)

– APIs for services

– Client access to beans – lookup, use

– Developer view of beans

• Factory class to create them ("Home" objects – as in draft CCM)

• Beans must extend framework defined classes (as in RMI's class

UnicastRemoteObject or CORBA's XXX_POA classes)

5

EJB 1.1

• Entity beans become mandatory for compatible EJB engine Beginning to match deployment and distribution goals of CCM

• XML style deployment descriptors

• Standardized JAR archives for distributing binary compatible beans (components)

• CORBA IIOP compatible communications

• "Role" based declarative security constraints

6

1

Some problems

• Client access to Entity beans –

– Fine grain access is a performance killer

• "Work around" (data access objects) involves extra classes and increases complexity of application

– Some issues about propagating transactional contexts to clients

• Framework defined interfaces for components assumes

"distribution"

– So a call to a component involves building a CORBA style "Request" object for transmission across network

• In practice, Entity beans mainly used by Session beans and both are incarnated (!) in same EJB engine ( though one could choose to deploy system with multiple EJB engines – some with session beans, others with entity beans )

– Why do calls to object in same JVM go all the way down to TCP and then come all the way back up?

Very costly

7

More problems

• Home objects (bean creating factory classes)

– Home objects for session beans were not complex – but they were essentially cut-&-paste code; developers repeatedly writing out same code; ( clearly, goals of simplifying and standardizing haven't been met )

– Home objects for entity beans

• Much better than CORBA's PSDL approach

• These Home objects could have multiple application defined methods for finding collections of entities that satisfied SQL like constraints.

• But still a lot of code – mostly of a highly repetitive character.

8

Still more problems

• Implementation classes for Entity and Session beans have to implement framework defined interfaces

– Interfaces define all sorts of "hook" methods

• Hook methods exist to handle special needs processing

– setEntityContext, unsetEntityContect, ejbActivate, ejbPassivate, ejbPostCreate, ejbRemove

– Sometimes there may be extra initialization steps that should be performed when a bean is to be removed – so provide ejbRemove hook function

• Mostly though, there was no need for any special processing

– but the programmer of a "bean" still had to provide (empty) definitions for all these hook functions.

9

Persistence for Entity Beans

• Choose –

– You use "Bean Managed Persistence" and work with JDBC

– You hope for automated support and employ "Container managed Persistence"

• With "Bean Managed Persistence"

– You write ejbLoad and ejbStore functions for your beans

• "Lookup" request to get reference to database connection

(something like those CORBA "initial_reference" requests to ORB – a deployment descriptor would have had to set up the database connection)

• Use JDBC to read and write data

10

Container managed persistence

• EJB 1.1 – limited

– Simple entities only – no relations (~foreign keys)

– XML document contained details of mappings of object data members to columns

• Might have to be hand composed – complicated and long winded

11

EJB - 2

• Changes –

– Much more sophisticated automated data persistence model that allowed for relations amongst objects

(foreign keys, mapping tables etc)

• EJBQL – elaborate query language for use in association with new CMP

– More standardisation of deployment aspects

– "Message beans" – not really achieving CCM objective of unifying messaging and RMI; session beans can generate events for a messaging system;

"message beans" in EJB container can receive events.

– Local and Remote interfaces

• An optimization, but a complication as well

12

2

EJB 2.1

• Support of XML protocols (SOAP) and hence some measure of interoperability with .NET etc

• Internal timer events to trigger regular actions

• Refinements to EJBQL

• Rule – you cannot propagate transactions out to client;

Suggestion – don't ever access entity beans from client.

13

But even more complexity

• None of previous complexities removed.

• New refined container managed persistence made CMP entity beans even more complex

– Define an abstract class that has abstract get/set methods for data fields and which implements complex framework defined interfaces

– Real entity class auto-generated (but there are differences in implementations and things aren't really compatible across different vendors).

14

Huge coding overheads

• EJB

– Widely used but subject to increasingly hostile perception

• Too much framework-attachment code to write (all those Home classes)

• Issues of "Data Access Objects" etc

• Complexities of CMP

• Huge XML configuration files (OK, mostly generated by your development environment)

• Performance

• Local/Remote complications (different semantics for seemingly identical calls)

– Microsoft had fun comparing application sizes EJB and .NET for standard tutorial examples (usually unfairly as the Microsoft versions generally simplified the problem), EJB could be 3 times as much code (if include all the XML deployment files)

15

Hybrid EJB/other

• Increasingly, companies looked to simpler frameworks like Spring,

• Or used EJB for "session" and "message" only, abandoning overly complex EJB entity classes; instead, used 3 rd party "object relational mapping" system like Hibernate.

16

Finding collaborators

• One of the more tiresome features of EJB-1/EJB-2 programming was coding the way that "beans" got to talk to one another.

– Example "session bean" uses "entity beans"

• Need lots of code along lines

– Get reference to a "naming service"

– Lookup name of "Home" (factory) for the entity class that you want to use

– Get reference to Home object

– Use Home object to find entity bean

• But all you really want is that reference to entity's Home object

• Container knows where it is – couldn't you just have some deployment descriptor that told the container to automatically set a reference variable to point to the required Home?

17

Spring – "resource injection"

• Simpler Spring framework provided a

"resource injection" framework

– "annotate" a reference member in a class as needing initialization

– Provide deployment data (XML) that defines appropriate initial value

– Framework initializes value when instance of that class instantiated

(Also fits with CCM's idea of configuration data automatically setting attributes – but the "resource injection" terminology is sexier)

18

3

Aside comment – " the meaning of version numbers "

• The meaning of version numbers:

– 0.1 -- WE GOT A REALLY GREAT NEW WAY TO DO THINGS !!!

– <0.9 -- Not ready for prime time.

– 0.9 -- We think it works, but we won't bet our lives on it.

– 1.0 -- Management is on our case; seems like a low risk.

– 1.01 -- Okay, we knew about that. All known bugs are fixed.

– 1.02 -- Fixes bugs you won't see in 27,000 years

– 1.03 -- Fixes bugs in the bug fixes.

– 1.04 -- All right, this REALLY fixes all known bugs.

– 1.05 -- Fixes bugs introduced in rev 1.04.

– 1.1 -- A new crew hired to write documentation.

– 1.11 -- From now on, no comma after "i.e." or "e.g.".

– 1.2 -- Somebody actually changed a functional feature.

– 2.0 -- New crew hired to write software. Old crew blamed for bugs.

– 2.01 -- New crew sending out resumes to placement agencies.

– 3.0 -- Re-write the software in another language, go back ten squares.

– ... -- return to line 0.1

19

EJB 3

• It hasn't really changed

– Still really have Home (factory) objects creating session objects etc

– Still have Local and Remote interfaces

– Still have all sorts of hook methods that can be implemented

– Still need to find your collaborators

– …

20

EJB 3

• But it appears to have changed

– There really is no need to define those Home classes – the system can do it and look after any instances at run time

– There is no need for lookup code to find collaborators – the EJB container can sort those out and "inject" the references

– There really is no need to define those hook methods if you don't need to implement them – if you do want one, just annotate your code so that system recognizes it as a hook method

– There really is no need to inherit from framework defined base classes – can use a delegation model; framework stuff can all be handled by the framework

– There is no need for complex fragile Entity bean classes – JPA is simple and it works

21

EJB

Sun's view EJB3

23

3-tier

• Professional client

– Java GUI etc

– "Client container"

• 'trick' that will help set up environment variables etc needed to contact server

• Browser

– HTML, CSS, Javascript; maybe XSLT etc (URL used to contact servlet)

• Application-server

– JVM with separated containers

• Web container

– Tomcat based, holds servlets (mainly generated from JSPs) and beans etc

• Enterprise container

– Holds session beans and message beans

– "Local" interfaces work for EJB beans accessed from within paired web container (efficiency concerns)

– "Remote" interfaces work for EJB beans accessed from 'professional client'

24

22

4

What is "Enterprise Java"?

• Now viewed as all those Java packages with classes needed to build

– "Web applications",

– "Enterprise applications",

– Applications using mail

– Applications working with XML data

– Applications (in)directly using Java

Transaction API (CosTransactions)

– …

Servlet, XML stuff etc initially organized separately

25

Enterprise - includes

• Web

– javax.faces.*; javax.servlet.*; javax.servlet.jsp.*, javax.el

• Mail

– javax.mail

• Persistence

– javax.persistence, javax.annotation

• Enterprise container

– javax.ejb, javax.enterpirse.*;javax.annotation; javax.resource; javax.transaction

• XML

– javax.xml.*

26

APIs

27

Deployment and configuration standardized

JAR archives

Standard deployment data ("application.xml")

Implementation specifics like sun-application.xml

Integral EJB Services

• A naming service –

– Find the server objects

– Find the right database!

– JNDI – Java Naming and Directory Interface

• A transaction monitor

• Limited notifications service (Java Message

Service)

• Persistence services for entities (JPA)

29

Integral services

• With EJB-3, tend not to see any of these services

– All handled through configuration XML files then "resource injection"

30

5

Development

• Essentially impossible without an IDE

– There are command line tools supplied with some EJB servers, but the build procedures are quite complex and it isn't sensible to attempt manual build of program

31

Aside comment

Why beans?

32

Beans

• Part of "coffee" analogy in Java.

• Bean

– lump of pure perfect Java

– Can be put into some machine, ground up, utilized to produce a beautiful brew

– (or something like that)

33

Java bean – not the right kind of bean

• Java Bean

– “component” for use in a GUI based application (Sun’s version of

Windows ActiveX control)

– To be used with a GUI editing tool

– Is an instance of a GUI related class that handles mouse/keyboard events

– Class follows strict programming guidelines

– Java introspection allows GUI editor tool to work with bean

– Tool used to compose GUI

• Pick bean

• Link up event sources and event user objects

• Set properties of objects

– Tool generates code that essentially instantiates an object from class, sets the properties, and links with other beans (also generates helper classes)

– This generated code added to application

34

Enterprise bean

• Enterprise Bean

– “ component ” for building a business application

– To be used by an application builder tool that builds applications that run in application servers

– Is instance of a class that

• Represents some data entity

• Or is a typical stateful/stateless server object

• Or which consumes events (CORBA style events)

– Follows strict programming guidelines

– Java introspection allows application creation tool to generate helper classes that manage instances of class.

– This generated code packaged along with deployment attribute data

– Package loaded into an application server

35

Session beans

- served with or without state

36

6

Enterprise bean

• Sun:

" Written in the Java programming language, an enterprise bean is a serverside component that encapsulates the business logic of an application.

"

37

Session bean

• Session bean?

– A service:

• Set of functions that can be invoked by client components

• Stateless

– Each request is completely independent

• Calculate currency conversion

• Enlighten me

• Select from data table and display

– (There may be internal state such as a database connection, but this isn't perceived by client)

• Stateful

– Responses depend on past history

• Deposit into "shopping cart"

• Show "shopping cart" contents

• …

38

Threading?

• Sun policy:

– " A session bean represents a single client inside the Application

Server.

"

– Enterprise beans are single threaded.

– (Avoids all sorts of problems of race conditions, code making buggy use of locks etc)

• But doesn't that reduce throughput?

• Multiple copies of bean are created

– Typically, a pool of instances of a bean class will be created at start up

– Clients mostly get to (re-)use an existing bean

– Each concurrent client is handled by separate thread and will utilize different bean instances.

39

Stateless / Stateful : costs

• Small pool of stateless beans can effectively serve large number of clients

– Each bean in use only during invocation of a single method

– Returns to pool (or, conceivably, gets garbage collected) when method completes

– Can be reused

• Stateful:

– Each concurrent client creates instance of stateful bean

– Instance must continue to exist in server until discarded by client

40

• Stateless:

"Lifecycles"

1. "The client initiates the life cycle by obtaining a reference to a stateless session bean.

2. The container performs any dependency injection and then invokes the method annotated@PostConstruct, if any.

3. The bean is now ready to have its business methods invoked by theclient.

4. At the end of the life cycle, the EJB container calls the method annotated

@PreDestroy, if any.

5. The bean’s instance is then ready for garbage collection."

(Earlier EJB implementations referenced a "pool" of reusable instances; probably implementations still work that way rather than the described "create on demand".

This description is like the CORBA "Locator" with single use servant.)

41

• Stateful

Lifecycles

42

7

Lifecycle: stateful bean

1. The client initiates the life cycle by obtaining a reference to a stateful session bean.

2. The container performs any dependency injection and then invokes the method annotated with@PostConstruct, if any.

3. The bean is now ready to have its business methods invoked by the client.

4. While in the ready stage, the EJB container may decide to deactivate, or passivate , the bean by moving it from memory to secondary storage. The

EJB container invokes the method annotated @PrePassivate, if any, immediately before passivating it.

5. If a client invokes a business method on the bean while it is in the passive stage, the EJB container activates the bean, calls the method annotated

@PostActivate, if any, and then moves it to the ready stage.

6. At the end of the life cycle, the client invokes a method annotated

@Remove, and the EJBcontainer calls the method annotated @PreDestroy, if any.

7. The bean’s instance is then ready for garbage collection.

43

Passivate and activate

• Idea was similar to the CORBA Locator working with a cache.

• EJB engine could only host certain number of client stateful session beans.

– If demand too heavy, swap out least recently used bean to make more room

– Bean state must be saved – implication is that session beans should implement serializable

• Used to come as part of bean having to implement a framework defined interface that implemented serializable

• With EJB3, comes via annotatons

• In practice, passivation rare.

• PrePassivate/PostActivate

– Bean might use a JDBC connection, or other resource that cannot be serialized

– PrePassivate – get rid of resource!

– PostActivate – re-create resource!

44

Examples

45

Firstly, the inevitable Guru

• Stateless

• Single method – enlightenMe

• Web and "professional" clients

• How?

• By Magic!

46

EJB-3 Magic

• All aspects of remote access etc are going to be handled either by

– "Annotations" – that add additional magic code

– XML deployment files – generated by

NetBeans (too hard to try by hand)

47

Set up your AppServer domain

• NetBeans 7.1

– It will create “domain” (a directory where it stores things like configuration files) and set up connections to Glassfish 3.1 when you first create a web or EJB project

• Glassfish starts of with no admin password set (unsafe)

– Give it administrator name/password that you can remember

– Try to remember the ports that it picked for your instance of AppServer

– Start your server

48

8

New Project - Enterprise

49

Enterprise projects

• Really several projects

1. Enterprise (server/business) code

2. Web client

3. "Professional client"

• Four projects are created – the three parts and an overall deployment project

50

Set server

• Set server and get EJB and web projects created

EJB 7.1/Glassfish 3.1

• Change to way professional client projects are handled

– Have to have a “Java library” project to hold the

“Remote” interface for your EJB session beans

• Project needs to exist (though empty) before any parts of remote interface get created.

51 52

EJB 7.1/Glassfish 3.1

• EJB client application project also has to be created as no longer done when creating main

EJB project

Five part Enterprise project!

• You don't do much with the overall project except give commands like "Build", "Undeploy and Deploy" and Run

• Code etc go in the related projects

53 54

9

Start with the business code ( ejb sub-project )

• All beans should be defined in a specific

Java package, not the default package

• So start by adding a package to the

"Source" of the ejb sub-project

Add a "session bean" - Guru

• Want both "local" and "remote" usage

55

It insists that you identify a

Java library project for the remote interface – which is why you have to create that first (it offers a list of all library projects that it knows, pick the right one)

56

Auto-generated beginnings …

• NetBeans generates (initially empty) stubs for

GuruBean, GuruBeanLocal, and GuruBeanRemote

– Bean annotations identify roles

57

Annotations and those interfaces

• These provide the information needed to generate all the "glue" code used by the framework

– Interfaces – how clients will see service

(naturally, they actually work with autogenerated stub classes)

• Local – for use by servlet in web-container that shares same JVM as EJB-container

• Remote – for use by "professional client"

Semantics of Local and Remote invocations differ with regard to arguments; get warnings about methods defined in both interfaces

58

Define the business methods

• Don't just hack in code!

• Bean, Local, and Remote must be kept consistent – automated in NetBeans via add business method

Right-click in the body of the bean in the edit-window : pop-up “Insert Code”/

“Add business method” …

59

Method definition

• Dialog used to set name, return type, and whether method belongs in Local, Remote, or Both interfaces

Quite likely that a return type, argument, or exception will belong to a class that you are defining (e.g. you define your own exception class, and you want to return a JPA entity).

Your classes (MyException, MyJPAEntity) must be defined in “Java library” projects that you have already built and added as libraries for the current project.

60

10

Interface and empty body autogenerated by NetBeans

Implement your business method

(NetBeans worries unnecessarily about methods appearing in both interfaces – it’s not an issue if method takes no argument or when arguments are “final”) 61

Probably worth selecting the ejb-project and doing a "build" on it at this point

62

"Professional" client

• Inevitable code

– Some form of lookup – returns an instance of a client stub class that implements the

GuruRemote interface

– Code using the stub to invoke method

• Need to add necessary libraries, like the

.jar file obtained by building the ejb

– NetBeans will automate most of this

63

Professional client

• You don't get much to start with

64

That inevitable lookup step

• EJB 3 automates this through "injection"

(~CCM's idea of initialized attributes)

• Just add a resource reference to code

– Extra code generated

– XML deployment data generated

• Client-container will interpret XML "inject" reference before your main() gets called.

65

Adding resource

66

11

Resource added

• EJB annotation (must be attached to a static member in a professional client) identifies variable that is to be initialized with a stub connecting to service

• Service called via stub

67

That's all

• No Naming.lookup

• No construct CosNaming path, obtain reference to NameServer, do lookup etc

• (That code is all there, it's just that you don't have to write it.)

• But, but, but …

– Where's the server?

– What port is it using?

• Magic

(actually, hidden configuration files)

68

Try the "professional client"

• Build the EJB project

• Deploy onto running Glassfish

• Build the client project

• Run the client

69

Running from NetBeans

• NetBeans output window will show innumerable grumbles, and finally will run the client properly

("from within client container")

70

Web project

• Edit the auto generated index.jsp page to add link to a servlet

Define the servlet

• Servlets must be defined in specific package so start by adding a package to source of web client project

71 72

12

Next, define a servlet

73

Lookup that EJB service

• Servlet is a client

• Servlet will be using a client stub (one that implements the Local interface of server)

• Servlet will need to "lookup" that EJB service

• In EJB-3, this is again automated via

"annotations" ( and corresponding auto-generated code and XML deployment information )

74

Of course, you can use JSPs

Code to invoke operation Implement a JSP to display result

75

You have finished coding!

• Painless!

• So easy a "Business Studies" graduate could do it.

• So – Build (pick the overall Enterprise project and select Build)

77

Deploy

• Deploy onto running server

– Typically get all kinds of messages at this point

• Some being obscure error reports

– (Some make sense, if this is the first "deploy" step then the "Undeploy and Deploy" action will get errors for the undeploy step)

– Others don't make sense

– Some are configuration issues (where are those damn log files, I can't find them)

– Usually, despite some grumbles, it does deploy¶

¶And if it doesn't deploy ... Curse, play n 78 try going home and returning tomorrow

76

13

Run!

• Right-click on overall Enterprise project offers a Run option

Try the servlet

• You receive enlightenment from the EJB

Guru

79

The web side is now running; can just open up browsers normally and connect

80

Back to “professional” client

• Running app-client from within NetBeans is inconvenient.

• Two alternatives

1. Use "appclient" script

• This one of the numerous support programs for glassfish Application Server

2. Construct a stand-alone client

81

appclient

1.

This needs to access a configuration file that contains data such as the port that your glassfish appserver is using.

– Its default location is the glassfish's own directory – this would work on a windows platform where you typically use the default domain; it doesn't work on Linux where you must create you own domain.

• You must provide argument identifying xml configuration file in own domain.

2.

Configuration file may need to be edited – mine had the wrong port number

3.

appclient is in the bin directory of your glassfish installation – and will not be on your default path, so need to specify full name.

4.

appclient should be run when in the Guru/dist directory (or equivalent)

82

appclient

$ cd/home/nabg/AppServer/Try2/Guru/dist

$ /usr/local/glassfish-v2ur2/bin/appclient -client GuruClient.jar –xml \

/home/nabg/mydomain/config/sun-acc.xml

The Guru said Inside every older person is a younger person wondering what the hell happened.

83

Stand-alone client

• Doesn't rely on any "container" to inject resources

• Instead uses good old-fashioned "lookup" style code

– Here use an "InitialContext" object – it is equivalent to CosNaming stub's root context

– Configuration details have to go in a properties file

84

14

Stand-alone client

• Separate NetBeans project

• Needs libraries

– "Project" (the ejb project)

– Lots from glassfish (in /usr/local/glassfish…

Add-project & add-jar

85

Lookup style code

1.

Load properties file with configuration parameters

2.

Create an InitialContext referencing these properties

3.

"lookup" bean type via InitialContext

– Since stateless, just need a bean of this type, any of them will do

Properties

• jndi.properties file – in stand alone client's project directory

• What is your CORBA port? Probably need to use administrator console on your AppServer to find out!

87 88

Stand-alone client

$ cd ./AppServer/Try2/StandAloneSupplicant

$ java -jar ./dist/StandAloneSupplicant.jar

The Guru said Education is an admirable thing, but it is well to remember from time to time that nothing that is worth knowing can be taught.

It's all magic

• Not one hint as to how it works

• But you should know

1.

Client (web or professional) uses naming service to lookup service

(here simply defined by bean type) and get stub

– Information as to location of naming service hidden in configuration files

2.

Client's initial contact is with factory object (Home object) that

"creates" a servant (instance of bean class)

3.

Bean life-cycle somewhat similar to CORBA activatable object

4.

Client uses bean

90 89

86

15

How on earth does it find the server?

• Configuration file.

– Not associated with project

– Configuration files belong to your domain

• Port number, hostname of glassfish appserver and other data

– May need to edit config files

» Check on admin console of appserver to see what ports are used

91

Example – sun-acc.xml

<client-container>

<target-server name="pc406c" address="pc406c" port="3265"/>

< log-service file ="" level="WARNING"/>

< message-security-config auth-layer="SOAP">

<!-- turned off by default -->

<provider-config class-name="com.sun.xml.wss.provider.ClientSecurityAuthModule" provider-id="XWS_ClientProvider" provider-type="client">

<request-policy auth-source="content"/>

<response-policy auth-source="content"/>

<property name="debug" value="false"/>

</provider-config >

< provider-config class-name="com.sun.xml.wss.provider.ClientSecurityAuthModule" provider-id="ClientProvider" provider-type="client">

<request-policy auth-source="content"/>

<response-policy auth-source="content"/>

<property name="encryption.key.alias" value="s1as"/>

</provider-config >

</message-security-config>

</client-container>

92

EJB-3 achieves some of CCM deployment goals

• It is largely automated

• "Resource injection" achieves what CCM wanted for a deployment tool that would correctly configure components before they would get used.

• Stateless session illustrated via Guru is equivalent to CCM's "Service" class of component

93

EJB

Stateful server

94

95

The application

• Hangman game

– Each concurrent client gets a different game

– Game state, held in stateful bean, includes

• Target word for this player

• Number of guesses

• Letters already used as guesses

96

16

How does it work : 1

• Bean has two methods exposed in both Remote and

Local interfaces public interface HangerRemote {

ResultOfGuess newGame();

ResultOfGuess handleGuessedLetter( final String guessedLetter) throws MyException;

}

• newGame

– Picks a new word etc

– Called for "Get" from servlet, or at start of app-client

• handleGuessedLetter

– Processes a guess

– Called from "Post" in servlet, or from in a game-loop in app-client

97

How does it work : 2

• Methods return a 'struct' public class ResultOfGuess implements Serializable { private boolean won; private String lettersGuessed; private String knowLetters; private String imageString;

• Servlet formats in HTML along with form used to submit next letter guess

• App-client prints fields, prompts for guess on standard input

98

How does it work : 3

• Server-side: Hangman-ejb project

– Bean

– Dictionary (static class)

• Collection of words

– Images (static class)

• Here defined as array of strings showing gibbet and hanging player

• Server and client:

– Application defined exception

– "ResultOfGuess" struct

99

How does it work : 4

• State data:

@Stateful public class HangerBean implements HangerRemote, HangerLocal { private boolean gameInProgress; private int numGuesses; private int badGuessCount; private String guessedLetters; private String wordToGuess; private String knownLetters; private static final String letters =

"abcdefghijklmnopqrstuvwxyz";

100

How does it work : 5

• newGame

– Ask dictionary for word; initialize other fields

– Build and return struct with "image" and guess data

• handleGuessedLetter

– Make sure it is a single letter, possible exception

– Check not previously guessed

– If letter is used, update target word to show occurrences; else increase count of bad guesses

– If appropriate, build and return struct with "image" and guess data

101

Creating it …

1.

A Java library project for classes used in both client and server

1.

MyException

2.

Result of Guess

2.

A Java library project (empty) that will hold the generated remote interface

3.

The EJB triple

1.

EJB overall project

2.

The bean project

3.

The web project

102

17

Auxiliary classes

• Before defining the bean, it is useful to define auxiliary classes that it will use.

– MyException –

– ResultOfGuess –

• Code, build, and add generated library to other projects

103

ResultOfGuess

104

Other auxiliary classes

• Dictionary of words, and class defining string images for “hanged men” are only used by EJB stateful session bean

– Belong in ejb project – but in a different package from the bean itself

@Stateful annotation

105

Need business methods:

ResultOfGuess newGame(); boolean gameOverMan();

ResultOfGuess handleGuessedLetter( final String guessedLetter) throws MyException;

106

Add business methods Implement business logic

• NetBeans generates stubs

107

• Implement the code

– Nothing relevant here

108

18

App-client

• EJB Resource popup-menu

– Call EJB bean

• Select bean via dialog, naturally "Remote" interface public class Main {

@EJB private static HangerRemote hangerBean; private static void displayState(

ResultOfGuess rog)

{ … } public static void main(String[] args)

{ … }

}

Stateful bean is created in server when the "client container" handles resource injection (it does a lookup to find Home (factory) object, then invokes create method in Home object, gets a reference back which it inserts 'hangerBean').

109

Build and deploy the ejb

• This done at this stage to get it’s “JNDI” name –

– This will be printed when bean is deployed

110

Create client

• Edit the main() generated for the client application – inject a resource reference

111

App-client

public static void main(String[] args) {

BufferedReader input = new BufferedReader( new InputStreamReader(System.in));

ResultOfGuess rog = hangerBean.newGame(); while(!rog.isWon()){ displayState(rog); try {

System.out.print("Guess letter : ");

String line = input.readLine().trim(); rog = hangerBean.handleGuessedLetter(line);

} catch(Exception e) { … }

}

112

Try client (appclient style)

• Launch from inside NetBeans (it sorts out the appclient setup):

113

Stand alone client

• ? Glassfish 3 seems to have simplified this slightly

Just request initial context & do lookup

How to find server? Set ORBInitialPort

(and ORBInitialHost) as JVM arguments

114

19

Web client

• Create a new package in –war subproject

• Create a new servlet in this package

• Use Enterprise popup menu to insert field and annotation?

public class HangManServlet extends HttpServlet {

@EJB private HangerLocal hangerBean ; protected void doGet(HttpServletRequest request,

HttpServletResponse response) throws ServletException, IOException { … } protected void doPost(HttpServletRequest request,

HttpServletResponse response) throws ServletException, IOException { … }

}

115

Problem – reference to stateful bean in a servlet!

• Stateful bean has data unique to a client

• There is only one instance of servlet

– If try to store a reference to EJB bean in an instance member of a servlet, then all users get to share the same EJB bean!

• But resource injection only works with instance variables.

• 

116

Don’t inject stateful beans

• Injection works for stateless beans, servlet just gets to use (any) available stateless session bean in the EJB container.

• That isn’t what you want if they are stateful

– you want your own bean.

– (Hangman will work when there is only one client, but if there are several they share the same state, or groups of clients share state)

117

Need to use Servlet’s

HTTPSession

• Use HTTPSession – so there is state in servlet linked to client browser via cookie etc.

• Check whether your HTTPSession contains a reference to EJB Session bean –

– If not, use JNDI lookup and (hopefully) get a new one created

– Store reference in HTTPSession

118

Servlet sessional bean reference

• Use explicit JNDI lookup, store returned reference in servlet session state

Invoking methods of Local bean

119 120

20

Multiple web clients

Persistent data

JPA entities

121 122

Entity classes

• EJB-1 : too limited

• EJB-2 : too absurdly complex

• EJB-3 : use JPA

– Remember a JPA entity is "a plain old (serializable)

Java object"

• Session bean can be asked to find and return entity

• Client can modify entity and return updated version to session bean

• Session bean merges it back into database

• So it is as if entities were being made available to client – but this scheme is much more effective than accessing actual entity beans via remote (or even local) interfaces

123

But first …

• You have to configure your NetBeans environment and your AppServer (Glassfish)

1. Add the appropriate JDBC drivers to the

Databases/Drivers section of "Services" in

NetBeans

– Oracle driver probably in /usr/local/instantclient_10_2

2. Create a connection using the driver to your database

– You should now be able to view your tables

124

JDBC connection in NetBeans

Covered in CSCI399

See http://www.uow.edu.au/~nabg/399/E4.html

for more examples

125

JPA

• Covered in CSCI399

– See http://www.uow.edu.au/~nabg/399/E5.html

– Need to set up a persistence unit and add

Eclipselink libraries to projects using JPA

• Specify a datasource for persistence unit

• In an EJB application, you should add the persistence unit to the ejb sub-project

126

21

Persistence unit in a project

Use JPA to create entity automatically

127 128

Entity

• Entity class can be generated automatically from data table

– Minor edits usually required

• Effective toString() method etc

• If using sequence to generate pseudo primary keys then may need to add annotations to generated entity bean that add reference to sequence

129

Configure AppServer 1

• You can do it the hard way via the admin console of your glassfish AppServer

Login – using administrator name and password; note that port isn't the same as that used for webapplications.

Application Server:JVM settings/Path settings

130

Configure AppServer 2

• Create JDBC resource and connection pool

131

AppServer

• There are more dialogs – some asking for obscure parameters!

• Once connection pool set up (and tested) from inside admin console it can be used for connections; can select it when defining a persistence unit in NetBeans

132

22

AppServer – the easier way to configure

• If you simply define the DataSource in the persistence unit set up, NetBeans will add the necessary elements to AppServer for you

• See demo in http://www.uow.edu.au/~nabg/399/E5.html

133

Start again – JPA for Entity

Schools Example http://www.uow.edu.au/~nabg/399/JPA/JPA.pdf

134

Schools example

• From note written for CSCI399 explaining JPA technology

– http://www.uow.edu.au/~nabg/399/JPA/JPA.pdf

• Three Entity classes

– Pupil

• Simple data fields plus reference to School

– Teacher

• Simple data fields plus reference to School

– School

• Simple data fields

• Collection of teachers

• Collection of pupils

135

Schools example

• Lots of operations

– Add/Remove Teacher/Pupil

– Change properties of Teacher or Pupil

– Get lists of employees

– Get details of school

– …

• Servlet based version:

– Ten different servlets; each handling one of operations

• EJB version

– Stateless session bean defines all functionality

– Single servlet for viewing data plus "professional client" that offers other options

136

JPA Entity class ejb sub-project

• Session bean with local and remote interface, three entity beans, application defined exception

– Also persistence unit and Toplink added to library

137 138

23

Interface defining session bean operations

Session bean with EntityManager reference

139 140

app-client sub-project

• "Call EJB bean" – inserts reference to remote; actual value "injected" by client container when run

• Invoke operations via "injected" stub

141

Servlet gets a reference to "local" interface

142

The usual …

• Define the session bean; only difference from earlier examples is that this one has injected resource reference for entity manager

– Implement the operations

– No "transaction" code

• No begin, no commit, no get either JTA' or EntityManager's transaction context (as would be done in a servlet only solution)

• Code "professional" and "web" client – injected references to "remote" and "local" interfaces respectively

• Build and deploy

143

• App-client

Run

144

24

• Web client

Run

Messages & EJB

145 146

Using JMS

• Session bean can generate messages that get sent to a queue.

• Example of use

– Session bean dealing with orders

• Creates new order record in database (for use by some billing application)

• Sends message to Queue

– “Warehouse” runs a standard JMS receiver client application

• Receives order details for dispatch

147

Netbeans will generate code template

• “Insert code” dialog has option for generating JMS code

– By default creates a stub function that can be used to send a jms TextMessage

148

Two generated functions

And resources referencing

Queue

Code has been modified to use an ObjectMessage rather than default TextMessage.

Actual object is instance of (serializable) application defined class “WarehouseOrder”

149 150

25

Order processing code sends message after saving record

Standard JMS receiver client handles message

• Connect to Queue in usual way

• Create a thread to receive from queue

– Thread unpacks message and adds to list displayed in a GUI

151 152

JMS client code

Connecting

JMS client

153 154

Beans receiving messages

“Message Driven Bean”

155

Example

• “WolUsedCars” application

– Supposed commercial site for 2 nd hand car yard

– Application has Web and professional clients

– Add extra option

• “Delete record” requests can be sent from some message source via a queue

– TextMessage

– Simply id of car record

156

26

Changes to EJB app

• Add a method to session bean that will actually delete the record

Changes to EJB app

• Define a simple “Message Driven Bean”

– This simply invokes session bean to do work

157 158

Client

• Just a standard JMS client that sends

TextMessages

159

27

Download