Java EE 5 · No part of this book may be reproduced or utilized in any form or by any means,...

82
Java EE 5 Student Workbook

Transcript of Java EE 5 · No part of this book may be reproduced or utilized in any form or by any means,...

Page 1: Java EE 5 · No part of this book may be reproduced or utilized in any form or by any means, electronic or mechanical, including photocopying, recording, or by an information storage

Java EE 5

Student Workbook

Page 2: Java EE 5 · No part of this book may be reproduced or utilized in any form or by any means, electronic or mechanical, including photocopying, recording, or by an information storage

Page ii Rev 3.1.2 © 2007 ITCourseware, LLC

Java EE 5

Java EE 5

Published by ITCourseware, LLC, 7245 South Havana Street, Suite 100, Centennial, CO 80112

Contributing Authors: Jim Gallentine, John McAlister, Mike Naseef, and Jamie Romero

Editor: Jan Waleri

Editorial Assistant: Danielle North

Special thanks to: Many Java instructors whose ideas and careful review have contributed to the quality ofthis workbook and the many students who have offered comments, suggestions, criticisms, and insights.

Copyright © 2007 by ITCourseware, LLC. All rights reserved. No part of this book may be reproducedor utilized in any form or by any means, electronic or mechanical, including photocopying, recording, or byan information storage retrieval system, without permission in writing from the publisher. Inquiries should beaddressed to ITCourseware, LLC, 7245 South Havana Street, Suite 100, Centennial, CO 80112. (303)302-5280.

All brand names, product names, trademarks, and registered trademarks are the property of theirrespective owners.

Page 3: Java EE 5 · No part of this book may be reproduced or utilized in any form or by any means, electronic or mechanical, including photocopying, recording, or by an information storage

© 2007 ITCourseware, LLC Rev 3.1.2 Page iii

Java EE 5

Contents

Chapter 1 - Course Introduction ............................................................................................................. 9

Course Objectives .......................................................................................................................... 10Course Overview ........................................................................................................................... 12Using the Workbook ...................................................................................................................... 13Suggested References ..................................................................................................................... 14

Chapter 2 - Introduction to Java EE 5 ................................................................................................... 17

Introduction to Java EE ................................................................................................................... 18Java SE Building Blocks ................................................................................................................. 20Servlets, JSPs, and Web Applications ............................................................................................. 22Web Services ................................................................................................................................. 24Enterprise JavaBeans ...................................................................................................................... 26Additional Java EE APIs ................................................................................................................. 28POJO, Dependency Injection, and Annotations ............................................................................... 30The Java EE Platform ..................................................................................................................... 32

Chapter 3 - Introduction to JSP and JSTL ............................................................................................. 35

MVC and Web Applications ........................................................................................................... 36JSP As the View ............................................................................................................................. 38JSP Scripting Elements .................................................................................................................... 40Expression Language ...................................................................................................................... 42EL Operators ................................................................................................................................. 44Request and Response .................................................................................................................... 46include and forwards ....................................................................................................................... 48JSTL .............................................................................................................................................. 50Conditionals and Iteration in JSTL ................................................................................................... 52JSTL Variables And Output ............................................................................................................. 54Labs ............................................................................................................................................... 56

Chapter 4 - Introduction to Java Servlets and JavaBeans ...................................................................... 59

Java Servlets as the Controller ........................................................................................................ 60HttpServlet ..................................................................................................................................... 62HTTPServletRequest ...................................................................................................................... 64HTTPServletResponse ................................................................................................................... 66

Page 4: Java EE 5 · No part of this book may be reproduced or utilized in any form or by any means, electronic or mechanical, including photocopying, recording, or by an information storage

Page iv Rev 3.1.2 © 2007 ITCourseware, LLC

Java EE 5

HttpSession .................................................................................................................................... 68RequestDispatcher .......................................................................................................................... 70JavaBeans as the Model ................................................................................................................. 72Bean Scopes .................................................................................................................................. 74web.xml ......................................................................................................................................... 76Labs ............................................................................................................................................... 78

Chapter 5 - JavaServer Faces ............................................................................................................... 81

Frameworks ................................................................................................................................... 82JSF Benefits ................................................................................................................................... 84JSF Tag Libraries ........................................................................................................................... 86Components ................................................................................................................................... 88Managed Beans .............................................................................................................................. 90Event handling ................................................................................................................................ 92Navigation ...................................................................................................................................... 94Validators and Converters ............................................................................................................... 96Lifecycle ......................................................................................................................................... 98JSF Application Structure ............................................................................................................. 100Labs ............................................................................................................................................. 102

Chapter 6 - JMS ................................................................................................................................ 105

Messaging Concepts ..................................................................................................................... 106What is JMS ? .............................................................................................................................. 108Point-to-Point ............................................................................................................................... 110Publish/Subscribe ......................................................................................................................... 112Message Object ........................................................................................................................... 114Session ......................................................................................................................................... 116Creating the Client ........................................................................................................................ 118Labs ............................................................................................................................................. 120

Chapter 7 - JavaMail .......................................................................................................................... 123

Mail Systems and JavaMail ........................................................................................................... 124The javax.mail Packages ............................................................................................................... 126Establishing a Session ................................................................................................................... 128The MimeMessage Class .............................................................................................................. 130Sending a Message ....................................................................................................................... 132Retrieving Email Messages ............................................................................................................ 134Multi-part Messages ..................................................................................................................... 136

Page 5: Java EE 5 · No part of this book may be reproduced or utilized in any form or by any means, electronic or mechanical, including photocopying, recording, or by an information storage

© 2007 ITCourseware, LLC Rev 3.1.2 Page v

Java EE 5

Chapter 8 - EJB3 Overview ............................................................................................................... 139

The Enterprise JavaBean ............................................................................................................... 140EJB Benefits ................................................................................................................................. 142Defining the Bean Interface ........................................................................................................... 144Defining the Bean Class ................................................................................................................ 146Creating a Client Servlet ............................................................................................................... 148Assembly and Deployment of EJBs ............................................................................................... 150Labs ............................................................................................................................................. 152

Chapter 9 - Session Beans and Message-Driven Beans ....................................................................... 155

A Session Bean ............................................................................................................................ 156Stateless Session Beans ................................................................................................................ 158PostConstruct and PreDestroy ...................................................................................................... 160Lifecycle of a Stateless Session Bean ............................................................................................ 162Stateful Session Beans .................................................................................................................. 164Lifecycle of a Stateful Session Bean .............................................................................................. 166Lifecycle Callbacks ....................................................................................................................... 168Dependency Injection ................................................................................................................... 170Message-Driven Beans ................................................................................................................. 172MDB Lifecycle ............................................................................................................................. 174Sending a Message ....................................................................................................................... 176Labs ............................................................................................................................................. 178

Chapter 10 - Introduction to the Java Persistence API ......................................................................... 181

What is Java Persistence? ............................................................................................................. 182Persistence Objects and Metadata ................................................................................................ 184Creating an Entity Class ................................................................................................................ 186The Entity Manager ...................................................................................................................... 188Looking up Entities ....................................................................................................................... 190The Persistence Unit ..................................................................................................................... 192Deployment .................................................................................................................................. 194Labs ............................................................................................................................................. 196

Chapter 11 - Persisting Entities ............................................................................................................ 199

EntityManager and Persistence Context ......................................................................................... 200Entity Lifecycle ............................................................................................................................. 202Creating and Removing Entities ..................................................................................................... 204Transactions ................................................................................................................................. 206

Page 6: Java EE 5 · No part of this book may be reproduced or utilized in any form or by any means, electronic or mechanical, including photocopying, recording, or by an information storage

Page vi Rev 3.1.2 © 2007 ITCourseware, LLC

Java EE 5

Mapping Entities to Tables ............................................................................................................ 208Entity Relationships ....................................................................................................................... 210Primary Keys ............................................................................................................................... 212Lazy Loading and Cascading ........................................................................................................ 214Labs ............................................................................................................................................. 216

Chapter 12 - Transactions ................................................................................................................... 219

Transaction Terminology ............................................................................................................... 220The Java Transaction API ............................................................................................................. 222The UserTransaction Interface ....................................................................................................... 224Transactions in Java EE ................................................................................................................. 226Bean-Managed Transactions ......................................................................................................... 228Container-Managed Transactions .................................................................................................. 230Transaction Attributes ................................................................................................................... 232Transaction Rollbacks ................................................................................................................... 234Labs ............................................................................................................................................. 236

Chapter 13 - Data Binding with JAXB 2.0 .......................................................................................... 239

W3C XML Schema ..................................................................................................................... 240XML Data Binding Basics ............................................................................................................. 242JAXB Architecture ....................................................................................................................... 244Compiling Schema to Java ............................................................................................................ 246JAXBContext ............................................................................................................................... 248Unmarshalling ............................................................................................................................... 250Marshalling ................................................................................................................................... 252Validation ..................................................................................................................................... 254Custom Binding Declarations ........................................................................................................ 256Java to Schema ............................................................................................................................ 258Labs ............................................................................................................................................. 260

Chapter 14 - Java API for XML-Based Web Services (JAX-WS) ...................................................... 263

JAX-WS ...................................................................................................................................... 264Creating a Web Service Endpoint .................................................................................................. 266The Service Implementation .......................................................................................................... 268The Service Interface .................................................................................................................... 270apt and wsgen .............................................................................................................................. 272Generated Files ............................................................................................................................ 274Packaging and Deploying the Application ...................................................................................... 276

Page 7: Java EE 5 · No part of this book may be reproduced or utilized in any form or by any means, electronic or mechanical, including photocopying, recording, or by an information storage

© 2007 ITCourseware, LLC Rev 3.1.2 Page vii

Java EE 5

A JAX-WS Client ........................................................................................................................ 278wsimport ...................................................................................................................................... 280Labs ............................................................................................................................................. 282

Chapter 15 - Java Management Extension (JMX) ............................................................................... 285

What is JMX? .............................................................................................................................. 286MBeans ....................................................................................................................................... 288Creating a Standard MBean .......................................................................................................... 290Object Names .............................................................................................................................. 292The MBean Server ....................................................................................................................... 294Local Client .................................................................................................................................. 296Remote Client ............................................................................................................................... 298JConsole ...................................................................................................................................... 300Notifications ................................................................................................................................. 302Labs ............................................................................................................................................. 304

Chapter 16 - Case Study .................................................................................................................... 307

Case Study Overview ................................................................................................................... 308Persistence ................................................................................................................................... 310Stateless Session Bean .................................................................................................................. 312Web Tier Client: HTML ................................................................................................................ 314Web Tier Client: Controller Servlet ................................................................................................ 316Web Tier Client: Data Transfer JavaBean ....................................................................................... 318Web Tier Client: JSP ..................................................................................................................... 320Web Tier Client: web.xml .............................................................................................................. 322Message-Driven Bean .................................................................................................................. 324JMS Client ................................................................................................................................... 326JAX-WS Endpoint ....................................................................................................................... 328Web Service Client ....................................................................................................................... 330

Appendix A - Underlying Technologies: RMI, JNDI, and JDBC .......................................................... 333

RMI ............................................................................................................................................. 334Steps to Create a Remote Object ................................................................................................. 336An RMI Client .............................................................................................................................. 338An RMI Server ............................................................................................................................ 340RMI Utilities ................................................................................................................................. 342JNDI Naming and Directory Services ........................................................................................... 344Namespaces and Contexts ............................................................................................................ 346

Page 8: Java EE 5 · No part of this book may be reproduced or utilized in any form or by any means, electronic or mechanical, including photocopying, recording, or by an information storage

Page viii Rev 3.1.2 © 2007 ITCourseware, LLC

Java EE 5

Naming Operations ....................................................................................................................... 348Bindings ....................................................................................................................................... 350JNDI in JAVA EE ......................................................................................................................... 352The JDBC Connectivity Model ..................................................................................................... 354Connecting to the Database .......................................................................................................... 356Creating a SQL Query .................................................................................................................. 358Getting the Results ........................................................................................................................ 360Updating Database Data ............................................................................................................... 362

Appendix B - Ant ............................................................................................................................... 365

What Is Ant? ................................................................................................................................ 366build.xml ....................................................................................................................................... 368Tasks ........................................................................................................................................... 370Properties and Property Files ........................................................................................................ 372Managing Files and Directories ..................................................................................................... 374Filesets ......................................................................................................................................... 376Java Tasks .................................................................................................................................... 378Creating Java Archives .................................................................................................................. 380Specifying Paths ........................................................................................................................... 382Miscellaneous Tasks ..................................................................................................................... 384

Solutions ............................................................................................................................................ 387

Index .................................................................................................................................................. 493

Page 9: Java EE 5 · No part of this book may be reproduced or utilized in any form or by any means, electronic or mechanical, including photocopying, recording, or by an information storage

Course IntroductionChapter 1

© 2007 ITCourseware, LLC Rev 3.1.2 Page 9

Chapter 1 - Course Introduction

Page 10: Java EE 5 · No part of this book may be reproduced or utilized in any form or by any means, electronic or mechanical, including photocopying, recording, or by an information storage

Java EE 5

Page 10 Rev 3.1.2 ©22007ITCourseware, LLC

Describe the architecture and use of Java EE technologies.

Write web applications that combine Java Servlets, JavaServer Pages, andJavaBeans using the Model-View-Controller architecture.

Develop web applications using the component-based and event-drivenJavaServer Faces framework.

Send and receive asynchronous messages with the Java Message Service.

Interface with mail servers with JavaMail.

Describe the Enterprise JavaBean architecture.

Write session and message-driven EJBs.

Access a relational database with the Java Persistence API.

Map XML content to domain-specific objects with JAXB.

Handle transactions with the Java Transaction API.

Integrate legacy systems with JAX-WS web services.

Use JMX to monitor and manage Java applications.

Course Objectives

Page 11: Java EE 5 · No part of this book may be reproduced or utilized in any form or by any means, electronic or mechanical, including photocopying, recording, or by an information storage

Course IntroductionChapter 1

© 2007 ITCourseware, LLC Rev 3.1.2 Page 11

Page 12: Java EE 5 · No part of this book may be reproduced or utilized in any form or by any means, electronic or mechanical, including photocopying, recording, or by an information storage

Java EE 5

Page 12 Rev 3.1.2 ©22007ITCourseware, LLC

Audience: Java programmers who need to learn about Java EE 5

Prerequisites: Java Programming

Classroom Environment:

One Java development environment per student

DBMS Server

Course Overview

Page 13: Java EE 5 · No part of this book may be reproduced or utilized in any form or by any means, electronic or mechanical, including photocopying, recording, or by an information storage

Course IntroductionChapter 1

© 2007 ITCourseware, LLC Rev 3.1.2 Page 13

Using the Workbook

Chapter 2 Servlet Basics

© 2002 ITCourseware, LLC Rev 2.0.0 Page 17

Add an init() method to your Today servlet that initializes a bornOn date, then print the bornOn date

along with the current date:

Today.java

...

public class Today extends GenericServlet {

private Date bornOn;

public void service(ServletRequest request,

ServletResponse response) throws ServletException, IOException

{

...

// Write the document

out.println("This servlet was born on " + bornOn.toString());

out.println("It is now " + today.toString());

}

public void init() {

bornOn = new Date();

}

}

Hands On:

The init() method is

called when the servlet is

loaded into the container.

This workbook design is based on a page-pair, consisting of a Topic page and a Support page. When youlay the workbook open flat, the Topic page is on the left and the Support page is on the right. The Topicpage contains the points to be discussed in class. The Support page has code examples, diagrams, screenshots and additional information. Hands On sections provide opportunities for practical application of keyconcepts. Try It and Investigate sections help direct individual discovery.

In addition, there is an index for quick look-up. Printed lab solutions are in the back of the book as well ason-line if you need a little help.

Java Servlets

Page 16 Rev 2.0.0 © 2002 ITCourseware, LLC

� The servlet container controls the life cycle of the servlet.

� When the first request is received, the container loads the servlet class

and calls the init() method.

� For every request, the container uses a separate thread to call

the service() method.

� When the servlet is unloaded, the container calls the destroy()

method.

� As with Java’s finalize() method, don’t count on this being

called.

� Override one of the init() methods for one-time initializations, instead of

using a constructor.

� The simplest form takes no parameters.

public void init() {...}

� If you need to know container-specific configuration information, use

the other version.

public void init(ServletConfig config) {...

� Whenever you use the ServletConfig approach, always call the

superclass method, which performs additional initializations.

super.init(config);

The Servlet Life Cycle

The Topic page providesthe main topics for

classroom discussion.

The Support page hasadditional information,

examples and suggestions.

Code examples are in afixed font and shaded. Theon-line file name is listedabove the shaded area.

Screen shots showexamples of what youshould see in class.

Topics are organized intofirst ( ), second ( ) and

third ( ) level points.

Pages are numberedsequentially throughout

the book, making lookupeasy.

Callout boxes point outimportant parts of the

example code.

Page 14: Java EE 5 · No part of this book may be reproduced or utilized in any form or by any means, electronic or mechanical, including photocopying, recording, or by an information storage

Java EE 5

Page 14 Rev 3.1.2 ©22007ITCourseware, LLC

Basham, Bryan, Kathy Sierra, and Bert Bates. 2004. Head First Servlets and JSP: Passing the SunCertified Web Component Developer Exam. O'Reilly Media, Sebastopol, CA.ISBN 0596005407.

Burke, Bill and Richard Monson-Haefel. 2006. Enterprise JavaBeans 3.0. O'Reilly Media,Sebastopol, CA. ISBN 059600978X.

Dudney, Bill, Jonathan Lehr, Bill Willis, and LeRoy Mattingly. 2004. Master JavaServer Faces. JohnWiley and Sons, Hoboken, NJ. ISBN 0471462071.

Geary, David and Cay Horstmann. 2004. Core JavaServer Faces. Prentice Hall PTR, Upper SaddleRiver, NJ. ISBN 0131463055.

Hall, Marty and Larry Brown. 2003. Core Servlets and JavaServer Psges, Vol. 1: CoreTechnologies. Prentice Hall PTR, Uppder Saddle River, NJ. ISBN 0130092290.

Hall, Marty, Larry Brown, and Yaakov Chaikin. 2006. Core Servlets and JavaServer Pages, Vol. 2:Core Technologies. Prentice Hall PTR, Upper Saddle River, NJ. ISBN 0131482602.

Keith, Mike and Merrick Schincariol. 2006. EJB3: Java Persistence API. Apress, Berkeley, CA. ISBN 1590596455.

Mann, Kito. 2005. JavaServer Faces in Action. Manning, Greenwich, CT. ISBN 1932394125.

Schalk, Chris, Ed Burns, and James Holmes. 2006. JavaServer Faces: The Complete Reference.McGraw-Hill Osborne Media, San Francisco, CA. ISBN 0072262400.

Sriganesh, Rima Patel, Gerald Brose, and Micah Silverman. 2006. Mastering Enterprise JavaBeans3.0. Wiley, Hoboken, NJ. ISBN 0471785415.

http://java.sun.com/javaee/5/docs/tutorial/doc

Suggested References

Page 15: Java EE 5 · No part of this book may be reproduced or utilized in any form or by any means, electronic or mechanical, including photocopying, recording, or by an information storage

Course IntroductionChapter 1

© 2007 ITCourseware, LLC Rev 3.1.2 Page 15

Page 16: Java EE 5 · No part of this book may be reproduced or utilized in any form or by any means, electronic or mechanical, including photocopying, recording, or by an information storage

Java EE 5

Page 16 Rev 3.1.2 ©22007ITCourseware, LLC

Page 17: Java EE 5 · No part of this book may be reproduced or utilized in any form or by any means, electronic or mechanical, including photocopying, recording, or by an information storage

Chapter 2 Introduction to Java EE 5

© 2007 ITCourseware, LLC Rev 3.1.2 Page 17

Chapter 2 - Introduction to Java EE 5

Objectives

Describe the technologies that make upJava EE 5.

Architect Java EE solutions with varioustypes of external clients.

Define Java EE ease-of-use features,such as POJO, annotations, anddependency injection.

Page 18: Java EE 5 · No part of this book may be reproduced or utilized in any form or by any means, electronic or mechanical, including photocopying, recording, or by an information storage

Java EE 5

Page 18 Rev 3.1.2 © 2007 ITCourseware, LLC

The Java Enterprise Edition (Java EE) was designed to make the integration oflarge distributed applications as simple and flexible as possible.

Java EE helps the developer focus on the part of the application that isspecific to the business, instead of on the semantics of making the pieceswork together.

There is a limited set of skills that developers need to learn for their part of theapplication.

Some developers may focus on business logic with EJBs, while othersmay focus on presentation logic in JSPs, for example.

The Java EE specification describes the architecture of an application aswell as the specific protocols for communication.

The various developers are guaranteed that their section of theapplication will communicate seamlessly with the others.

The choice of tools and products is also less of a concern, because they alladhere to the same standards.

Introduction to Java EE

Page 19: Java EE 5 · No part of this book may be reproduced or utilized in any form or by any means, electronic or mechanical, including photocopying, recording, or by an information storage

Chapter 2 Introduction to Java EE 5

© 2007 ITCourseware, LLC Rev 3.1.2 Page 19

Application servers such as BEA WebLogic, IBM WebSphere, and JBoss implement the Java EEspecification. They provide containers as runtime environments for the various Java EE components. Theweb container hosts JSPs and servlets. The EJB container runs Enterprise JavaBeans within it.

The most common Java EE architecture separates the application into multiple tiers. The Client Tier isusually made up of a browser that is responsible for displaying the user interface on the client's system. TheMiddle Tier can be broken up across the two containers. The web container is responsible for readingHTTP requests and generating HTTP responses. The EJB container holds the business and database accesslogic. The Data Tier contains the database.

You can create Java EE applications that do not make use of the EJB container. These applications typicallyhandle all business and database access logic with servlets or JavaBeans, rather than through EJBs.

You can also create Java EE applications that do not make use of the web container. Clients to theseapplications are typically stand-alone clients, rather than browser-based clients.

Client Tier Middle Tier Data Tier

Application Server

DatabaseWeb Browser Web Container

EJB Container

Page 20: Java EE 5 · No part of this book may be reproduced or utilized in any form or by any means, electronic or mechanical, including photocopying, recording, or by an information storage

Java EE 5

Page 20 Rev 3.1.2 © 2007 ITCourseware, LLC

Java SE Building Blocks

The Java Enterprise Edition builds on the Java Standard Edition (Java SE).

Java SE contains the Java Virtual Machine and various tools, such as the javaccompiler.

Java SE also contains many bundled libraries that Java EE applications also use.

Java Database Connectivity (JDBC) allows Java EE applications toconnect to relational databases.

Remote Method Invocation (RMI) is the underlying protocol for remotecommunications to Enterprise JavaBeans (EJB).

RMI/IIOP allows non-Java clients to interact with Java EEapplications.

Java Naming and Directory Interface (JNDI) is used to perform lookupson naming services to find EJBs, among other things.

Java API for XML Processing (JAXP) can be used by Java EEapplications when working with XML content.

Page 21: Java EE 5 · No part of this book may be reproduced or utilized in any form or by any means, electronic or mechanical, including photocopying, recording, or by an information storage

Chapter 2 Introduction to Java EE 5

© 2007 ITCourseware, LLC Rev 3.1.2 Page 21

Application Server

DatabaseWeb Browser Web Container

EJB Container

RMI/IIOP

HTTP

JDBC

Standalone Client

RMI/IIOP

Page 22: Java EE 5 · No part of this book may be reproduced or utilized in any form or by any means, electronic or mechanical, including photocopying, recording, or by an information storage

Java EE 5

Page 22 Rev 3.1.2 © 2007 ITCourseware, LLC

Servlets, JSPs, and Web Applications

A web application reads HTTP request information from a browser andgenerates a response in HTML.

JavaScript and Cascading Style Sheets (CSS) can also be generated aspart of the response.

The web container hosts web applications.

A container is a runtime environment for Java EE components.The web container hosts JavaServer Pages (JSP), Java Servlets, andJavaBeans.

A servlet is a Java program that runs in the web container.

Servlets typically act as controllers, reading request information anddelegating calls to JavaBeans and JSPs to fulfill the client's needs.

JavaBeans are simple Java classes that follow a few coding conventions.

In Java EE, JavaBeans either call Enterprise JavaBeans to perform thebusiness and data access logic, or they do it themselves.

JavaServer Pages (JSP) are HTML documents with embedded JSP tags.

The JSP tags usually access JavaBeans to present the results of thebusiness logic invocation.JSPs are devoted to generating the view back to the browser.

Web applications are packaged in Web Archive (WAR) files.

Java Server Faces (JSF) is a framework that makes developing web applicationseasier through the use of tag libraries and a provided controller servlet.

JSF is new to Java EE 5.

Page 23: Java EE 5 · No part of this book may be reproduced or utilized in any form or by any means, electronic or mechanical, including photocopying, recording, or by an information storage

Chapter 2 Introduction to Java EE 5

© 2007 ITCourseware, LLC Rev 3.1.2 Page 23

Some of the coding conventions for JavaBeans include:

All JavaBeans have get and set methods to expose properties.JavaBeans must have a no-argument constructor.JavaBeans should implement the java.io.Serializable interface.

Application Server

Database

Web BrowserWeb Container

EJB Container

1) HTTP Request

7) HTTP Response

HTM

L

Servlet

2) method()

5) fo

rward

()

6) get

...()

JSP

JavaBean

3) method() 4) JDBC

Page 24: Java EE 5 · No part of this book may be reproduced or utilized in any form or by any means, electronic or mechanical, including photocopying, recording, or by an information storage

Java EE 5

Page 24 Rev 3.1.2 © 2007 ITCourseware, LLC

Web Services

A web service reads request information from an XML document and sends backan XML response.

The XML content is typically structured as a Simple Object AccessProtocol (SOAP) document.

A Web Service Description Language (WSDL) document describes theinterface to the web service.

Universal Description, Discovery, and Integration (UDDI) registries canbe used to locate web services.

Java EE provides several APIs to support web service development.

The Java API for XML-based Web Services (JAX-WS) supports bothservlets and EJBs as web service endpoints.

JAX-WS uses WSDL documents to generate client-side helper filesto simplify client development.

On the server side, the WSDL can be automatically generated byJAX-WS.

The SOAP with Attachments API for Java (SAAJ) represents a SOAPdocument as a data structure.

Additionally, as the name implies, SAAJ can be used to add non-XML attachments to your SOAP messages.

The Java API for XML Registries (JAXR) can be used to interface withUDDI.

Web service clients can be written in any language.

Page 25: Java EE 5 · No part of this book may be reproduced or utilized in any form or by any means, electronic or mechanical, including photocopying, recording, or by an information storage

Chapter 2 Introduction to Java EE 5

© 2007 ITCourseware, LLC Rev 3.1.2 Page 25

Application Server

DatabaseWeb Container

EJB Container

HTTP

Standalone ClientServlet

web service

endpoint

SOAP

SOAP

Page 26: Java EE 5 · No part of this book may be reproduced or utilized in any form or by any means, electronic or mechanical, including photocopying, recording, or by an information storage

Java EE 5

Page 26 Rev 3.1.2 © 2007 ITCourseware, LLC

Enterprise JavaBeans

Enterprise JavaBeans (EJB) contain the business logic for Java EE applications.

There are two types of Enterprise JavaBeans.

Session Beans contain task-oriented business logic.

Message-Driven Beans (MDBs) act as asynchronous message consumers.

EJBs use persistent objects called entities for persisting data to the database.

EJBs and entities run within the EJB container of the application server.

The container handles system-level services for the EJB, allowing thedeveloper to focus on business logic.

Examples of system-level services include transactions, security,and concurrency.

EJBs are packaged in Java Archive (JAR) files.

When the application server also serves as the web container, JAR and WARfiles can be packaged and deployed in an Enterprise Archive (EAR) file.

Page 27: Java EE 5 · No part of this book may be reproduced or utilized in any form or by any means, electronic or mechanical, including photocopying, recording, or by an information storage

Chapter 2 Introduction to Java EE 5

© 2007 ITCourseware, LLC Rev 3.1.2 Page 27

Application Server

DatabaseWeb Browser

Web ContainerEJB Container

HTTPJDBC

Standalone Client

Session Entity

MDB

RMI/IIO

P

Page 28: Java EE 5 · No part of this book may be reproduced or utilized in any form or by any means, electronic or mechanical, including photocopying, recording, or by an information storage

Java EE 5

Page 28 Rev 3.1.2 © 2007 ITCourseware, LLC

Additional Java EE APIs

In addition to JSPs, servlets, and EJBs, Java EE also supports several otherAPIs.

The Java Transaction API (JTA) is used to demarcate transactionalboundaries for Java EE applications.

The JTA integrates Java EE applications with an application server'stransaction manager to allow for distributed transactions.

JavaMail can be used to create user agents for sending email messages.

JavaMail integrates into existing mail transfer agents, such assendmail or Microsoft Exchange Server.

Java Message Service (JMS) uses Message-Oriented Middleware (MOM)for asynchronous point-to-point or publish/subscribe communication.

Point-to-Point messaging guarantees that a message is delivered toa single receiver.

Publish/Subscribe messaging broadcasts messages to allregistered subscribers.

MDBs are consumers of JMS messages.

The Java EE Connector Architecture allows Java EE applications to integratewith existing Enterprise Information Systems (EIS).

EIS examples include applications from SAP, PeopleSoft, and IBM'sCICS, as well as non-Java legacy applications.

Page 29: Java EE 5 · No part of this book may be reproduced or utilized in any form or by any means, electronic or mechanical, including photocopying, recording, or by an information storage

Chapter 2 Introduction to Java EE 5

© 2007 ITCourseware, LLC Rev 3.1.2 Page 29

Application Server

DatabaseWeb Browser

Web Container

EJB Container

HTTP JDBC

Standalone Client

Session Entity

MDB

Mail Server EIS

Asynchronous

Message Client

MOM

JMS

JMS

JTA

Transaction

Manager

RMI/IIOP

Java

Mai

l

Connec

tor

Note:There are five different types of external Java EE clients.

1. Browser-based clients access web applications over HTTP.

2. Web service clients use SOAP over the HTTP protocol to access servlet or EJB endpoints.

3. Stand-alone Java clients can use RMI to call EJBs.

4. Non-Java clients can use RMI/IIOP to access EJBs.

5. JMS clients send messages to MOM implementations to be delivered to MDBs.

Page 30: Java EE 5 · No part of this book may be reproduced or utilized in any form or by any means, electronic or mechanical, including photocopying, recording, or by an information storage

Java EE 5

Page 30 Rev 3.1.2 © 2007 ITCourseware, LLC

POJO, Dependency Injection, and Annotations

The primary goal of the Java EE 5 release is ease of development.

Java EE 5 embraces new and existing ideas to attain this goalincluding POJOs, dependency injection, and annotations.

Use Plain Old Java Objects (POJO) in Java EE 5 for creating sessionand message-driven beans, as well as for building persistent entities.

As the name implies, a POJO is a simple Java class.

Previous versions of Java EE required EJBs to implement specificinterfaces to conform to the specification.

This made it difficult to extract the EJB from the container fortesting.

Use dependency injection to access resources such as EJBs, JDBCDataSources, and JMS Destinations.

The container will find the resource and inject an instance of it into a fieldfor you.

Before injection was available, you would write several lines of JNDI codeto look up resources.

Java SE 5 introduced annotations to the Java language as a way to addmetadata directly within source code.

Java EE 5 makes heavy use of annotations as an alternative to theverbose XML deployment descriptors used in previous versions.

Page 31: Java EE 5 · No part of this book may be reproduced or utilized in any form or by any means, electronic or mechanical, including photocopying, recording, or by an information storage

Chapter 2 Introduction to Java EE 5

© 2007 ITCourseware, LLC Rev 3.1.2 Page 31

ShoppingCartBean.java...@Stateful(mappedName="ShoppingCartJNDIName")public class ShoppingCartBean implements ShoppingCart {

@Resource(mappedName = "jms/MyQueueFactory")private ConnectionFactory connectionFactory;@Resource(mappedName = "jms/MyQueue")private Queue queue;@EJBprivate CreditCardValidator validator;private ShoppingBasket shoppingBasket;

public void addItem(String code, int quantity) {shoppingBasket.addItem(code, quantity);

}...

}

Use the @Stateful annotationto identify this EJB as astateful session bean.

Use the @Resourceannotation to instruct the

container to inject aninstance of the Queue

class into the queue field.

Page 32: Java EE 5 · No part of this book may be reproduced or utilized in any form or by any means, electronic or mechanical, including photocopying, recording, or by an information storage

Java EE 5

Page 32 Rev 3.1.2 © 2007 ITCourseware, LLC

The Java EE Platform

Java EE encompasses more than just the application programming model thathas been described.

The Java EE Platform specifies a set of required APIs and policies needed torun Java EE applications.

Any operating system can be used, as long as the Java EE platform isavailable.

The Sun Java System Application Server Platform Edition can be used todevelop and deploy Java EE applications.

Production use of the Sun Application Server is free of charge; however,commercial application servers may be more reliable and scalable.

The Java EE Compatibility Test Suite is a set of tests designed to verify that aproduct is compatible with the Java EE platform standard.

Vendors compete on implementations, rather than on standard APIs.

This ensures application portability.

Page 33: Java EE 5 · No part of this book may be reproduced or utilized in any form or by any means, electronic or mechanical, including photocopying, recording, or by an information storage

Chapter 2 Introduction to Java EE 5

© 2007 ITCourseware, LLC Rev 3.1.2 Page 33

All EJB implementations, even the Sun Java System Application Server, have proprietary entries indeployment descriptors for defining things such as security and database connections. While the code maywork across implementations, adjustments will have to be made to the deployment descriptors that arepackaged with the JARs.

The Sun Java System Application Server Platform Edition can be downloaded for free from http://java.sun.com.

Java EE APIs and Technologies

Web Application Technologies:JavaServletsJSP — JavaServer PagesJSF — JavaServer FacesJSTL — JSP Standard Tag Library

Enterprise Application Technologies:EJB — Enterprise JavaBeansJava Persistence APIJavaMail (with MIME types)JAF — JavaBeans Activation Framework (for MIME types with JavaMail)J2EE Connector ArchitectureJMS — Java Message ServiceJTA — Java Transaction API

Web Service Technologies:JAX-WS — Java API for XML-Based Web ServicesJAX-RPC — Java API for XML-Based RPCJAXB — Java Architecture for XML BindingJAXR — Java API for XML RegistriesSAAJ — SOAP with Attachments API for JavaStAX — Streaming API for XML

List of Java SE Supporting APIs and TechnologiesJAAS — Java Authentication and Authorization Service (for use with JCA)JDBC — Java DataBase ConnectivityJAXP — Java API for XML ProcessingJMX — Java Management ExtensionJNDI — Java Naming and Directory InterfaceRMI-IIOP — Java Remote Method Invocation over Internet Inter-ORB ProtocolRMI-JRMP — Java Remote Method Invocation over JRMPJavaIDL — Java Interface Definition Language (for interfacing with CORBA)

Page 34: Java EE 5 · No part of this book may be reproduced or utilized in any form or by any means, electronic or mechanical, including photocopying, recording, or by an information storage

Java EE 5

Page 34 Rev 3.1.2 © 2007 ITCourseware, LLC

Page 35: Java EE 5 · No part of this book may be reproduced or utilized in any form or by any means, electronic or mechanical, including photocopying, recording, or by an information storage

Chapter 9 Session Beans and Message-Driven Beans

© 2007 ITCourseware, LLC Rev 3.1.2 Page 155

Chapter 9 - Session Beans and Message-Driven Beans

Objectives

Write a session bean.

Identify the differences betweenstateless and stateful session beans.

Create a message-driven bean toreceive asynchronous messages.

Describe the lifecycle of sessionbeans and message-driven beans.

Page 36: Java EE 5 · No part of this book may be reproduced or utilized in any form or by any means, electronic or mechanical, including photocopying, recording, or by an information storage

Java EE 5

Page 156 Rev 3.1.2 © 2007 ITCourseware, LLC

A session bean implements business logic.

The bean methods conceal the complexities of business tasks from theclient.

Business logic is decoupled from the client presentation layer, enabling amore flexible and reusable design.

State is an object's awareness of its attributes.

Conversational state is maintenance of object attributes across methodcalls.

Stateful session beans have conversational state and attribute values that can beused by other methods.

Stateless session beans do not have conversational state.

They maintain state only within the duration of one method call.

A Session Bean

Page 37: Java EE 5 · No part of this book may be reproduced or utilized in any form or by any means, electronic or mechanical, including photocopying, recording, or by an information storage

Chapter 9 Session Beans and Message-Driven Beans

© 2007 ITCourseware, LLC Rev 3.1.2 Page 157

Page 38: Java EE 5 · No part of this book may be reproduced or utilized in any form or by any means, electronic or mechanical, including photocopying, recording, or by an information storage

Java EE 5

Page 158 Rev 3.1.2 © 2007 ITCourseware, LLC

Stateless session beans are only dedicated to a single client for the duration ofone method call.

The container maintains a pool of stateless session beans.

While it is possible to place attributes in a stateless session bean, thelifecycle management of the container makes them unreliable formaintaining a persistent state.

Annotate a stateless session bean with @Stateless and implement an interface.

The interface can be annotated with @Remote or @Local.

It contains the methods to be exposed to any client that wishes to use thebean.

Stateless Session Beans

Page 39: Java EE 5 · No part of this book may be reproduced or utilized in any form or by any means, electronic or mechanical, including photocopying, recording, or by an information storage

Chapter 9 Session Beans and Message-Driven Beans

© 2007 ITCourseware, LLC Rev 3.1.2 Page 159

The isValid() method usesthe Luhn algorithm to

determine if the given creditcard number is valid.

shoppingcart/CreditCardValidator.javapackage shoppingcart;

import javax.ejb.Remote;

@Remotepublic interface CreditCardValidator {

public boolean isValid(String cardNumber);}

shoppingcart/CreditCardValidatorBean.javapackage shoppingcart;

import javax.ejb.Stateless;...@Statelesspublic class CreditCardValidatorBean implements CreditCardValidator {

public boolean isValid(String cardNumber) {String digitsOnly = getDigitsOnly(cardNumber);int sum = 0;int digit = 0;int addend = 0;boolean timesTwo = false;

for (int i = digitsOnly.length () - 1; i >= 0; i--) {digit = Integer.parseInt (digitsOnly.substring (i, i + 1));if (timesTwo) {

addend = digit * 2;if (addend > 9) {

addend -= 9;}

}else {

addend = digit;}sum += addend;timesTwo = !timesTwo;

}int modulus = sum % 10;return modulus == 0;

}...

}

Try It:Build and deploy the application using the asant command. To view the application, go to http://localhost:8080/ShoppingCart/validator.jsp.

Page 40: Java EE 5 · No part of this book may be reproduced or utilized in any form or by any means, electronic or mechanical, including photocopying, recording, or by an information storage

Java EE 5

Page 160 Rev 3.1.2 © 2007 ITCourseware, LLC

PostConstruct and PreDestroy

Annotate a method with @PostConstruct to perform custom setup duties forthe session bean.

Use the @PreDestroy annotation to perform shutdown duties for the sessionbean.

This method typically tidies-up resources that were performed in the@PostConstruct method.

The @PostConstruct and @PreDestroy methods can have any name, mustreturn void, have no parameters, and throw no checked exceptions.

These methods are optional in your session bean.

Page 41: Java EE 5 · No part of this book may be reproduced or utilized in any form or by any means, electronic or mechanical, including photocopying, recording, or by an information storage

Chapter 9 Session Beans and Message-Driven Beans

© 2007 ITCourseware, LLC Rev 3.1.2 Page 161

shoppingcart/CreditCardValidatorBean.javapackage shoppingcart;

import javax.ejb.Stateless;import javax.annotation.PreDestroy;import javax.annotation.PostConstruct;

@Statelesspublic class CreditCardValidatorBean implements CreditCardValidator {

...@PostConstructpublic void postConstruct(){

System.out.println("In @PostConstruct method.");}@PreDestroypublic void preDestroy(){

System.out.println("In @PreDestroy method.");}

}

postConstruct() is calledafter a session bean isinstantiated and after all

injections have completed.

preDestroy() is calledbefore a session bean

is destroyed.

Page 42: Java EE 5 · No part of this book may be reproduced or utilized in any form or by any means, electronic or mechanical, including photocopying, recording, or by an information storage

Java EE 5

Page 162 Rev 3.1.2 © 2007 ITCourseware, LLC

There are two states in the lifecycle of a session bean.

The bean is in the Does Not Exist state when the bean is not instantiated.

The bean is available for use by the container in the Method-Ready state.

When the session bean is first created, these steps are performed:

1. The session bean is instantiated by the container.

2. The container injects any resources as specified by the annotations in thesession bean code.

3. The container calls the @PostConstruct method.

When a client calls a business method on a session bean, the container allocatesan available bean from the pool (and returns the session bean to the pool whencomplete).

When the session bean is moved to the Does Not Exist state, the bean is readiedfor destruction and the container calls the method annotated by @PreDestroy.

The container dereferences the session bean and the bean is eventuallygarbage collected.

Lifecycle of a Stateless Session Bean

Page 43: Java EE 5 · No part of this book may be reproduced or utilized in any form or by any means, electronic or mechanical, including photocopying, recording, or by an information storage

Chapter 9 Session Beans and Message-Driven Beans

© 2007 ITCourseware, LLC Rev 3.1.2 Page 163

Lifecycle of a stateless session bean:

Container management of the Method Ready Pool:

noitisnarT sllaCreniatnoC

morf tsixEtoNseoDot ydaeRdohteM

gnisureniatnocehtybdetaitnatsnisinaebnoissesehT)(ecnatsnIwen.ssalC .

ehtsllacreniatnocehT tcurtsnoCtsoP@ .dohtemdetatonna

morf ydaeRdohteMot tsixEtoNseoD

ehtsllacreniatnocehT yortseDerP@ .dohtemdetatonna

Does Not Exist

Method Ready Pool

@PreDestroyClass.newInstance()injections@PostConstruct

BusinessMethod

Page 44: Java EE 5 · No part of this book may be reproduced or utilized in any form or by any means, electronic or mechanical, including photocopying, recording, or by an information storage

Java EE 5

Page 164 Rev 3.1.2 © 2007 ITCourseware, LLC

Stateful session beans are dedicated to one client for the life of the beaninstance.

They are not pooled.

Stateful session beans have conversational state across method calls.

They should be used when the task cannot be accomplished via onemethod call.

They use more memory than stateless session beans.

Define a session bean with the @Stateful annotation.

When this method is called, the container is informed that it can garbagecollect the bean.

You should provide an extra method in your stateful session bean that a clientwill call when they are finished with the bean instance.

Annotate the method with @Remove and include it in the bean interface.

Stateful Session Beans

Page 45: Java EE 5 · No part of this book may be reproduced or utilized in any form or by any means, electronic or mechanical, including photocopying, recording, or by an information storage

Chapter 9 Session Beans and Message-Driven Beans

© 2007 ITCourseware, LLC Rev 3.1.2 Page 165

Add the mappedNameelement to specify a JNDIlookup name for this bean.

Use the @Remote annotationto indicate that the interface is

remotely accessible.

shoppingcart/ShoppingCart.java...import javax.ejb.Remote;

@Remotepublic interface ShoppingCart {

public void addItem(String code, int quantity);public String getSummary();public void setCardNumber(String cardNumber);public void setCustomerName(String customerName);public boolean purchase();public void remove();

}

shoppingcart/ShoppingCartBean.java...@Stateful(mappedName="ShoppingCartJNDIName")public class ShoppingCartBean implements ShoppingCart {

...@EJBprivate CreditCardValidator validator;private ShoppingBasket shoppingBasket;

public void addItem(String code, int quantity) {shoppingBasket.addItem(code, quantity);

}public String getSummary() {

return shoppingBasket.getSummary();}public void setCustomerName(String customerName) {

shoppingBasket.setCustomerName(customerName);}public void setCardNumber(String cardNumber) {

shoppingBasket.setCardNumber(cardNumber);}...

@Removepublic void remove() {

System.out.println("In @Remove method.");shoppingBasket = null;

}}

Try It:Test the ShoppingCartBean by adding items to the cart at http://localhost:8080/ShoppingCart/shoppingcart.jsp.

Page 46: Java EE 5 · No part of this book may be reproduced or utilized in any form or by any means, electronic or mechanical, including photocopying, recording, or by an information storage

Java EE 5

Page 166 Rev 3.1.2 © 2007 ITCourseware, LLC

The three stages in the lifecycle of a stateful session bean are:

Does Not Exist, when no instances are created.

Method Ready, when the bean is assigned to its client and ready to beused.

Passive, when the non-transient attributes are serialized to secondarymemory.

Lifecycle of a Stateful Session Bean

Lifecycle of a stateful session bean:

Does Not Exist

Class.newInstance()injections@PostConstruct

@PreDestroy

Method Ready Passive@PostActivate()

@PrePassivate()

timeout

instance throws system exception

BusinessMethod

timeout

Page 47: Java EE 5 · No part of this book may be reproduced or utilized in any form or by any means, electronic or mechanical, including photocopying, recording, or by an information storage

Chapter 9 Session Beans and Message-Driven Beans

© 2007 ITCourseware, LLC Rev 3.1.2 Page 167

Note:Stateful session bean timeout is specified in a vendor-dependent manner.

noitisnarT sllaCreniatnoC

morf tsixEtoNseoDot ydaeRdohteM

.naebehtnodohtemssenisubasllactneilcehT

sekovnireniatnocehT )(ecnatsnIwen.ssalC .ssalcnaebehtetaitnatsniot

naebnoissesehtotdengissatcejboreniatnocBJEehtoteldnahasnruteR.tneilcehtotecnatsni

.ssalcnaebotniseicnednepedstcejnireniatnocehT

sllacreniatnocehT tcurtsnoCtsoP@ .dohtem

ehtybdeificepsdohtemssenisubehtotllacehthtiwseunitnocreniatnocehT.tneilc

morf ydaeRdohteMot evissaP

ybdetatonnadohtemehT etavissaPerP@ devassinaebehterofebdellacsi.egarotsyradnocesot

.egarotsyradnocesotdezilaireserasecnatsninaeB

morf evissaPot ydaeRdohteM

.dohtemssenisubasekovnitneilcehT

.yromemyramirpotderotserera)s(etubirttaecnatsnI

ybdetatonnadohtemehT etavitcAtsoP@ .reniatnocehtybdellacsi

morf evissaPot tsixEtoNseoD

.devomerebotsdeennaebehttahtsenimretedreniatnocehT

morf ydaeRdohteMot tsixEtoNseoD

ybdetatonnadohtemehtsllactneilcehT evomeR@ .

ybdetatonnadohtemehtsllacreniatnocehT yortseDerP@ .

Page 48: Java EE 5 · No part of this book may be reproduced or utilized in any form or by any means, electronic or mechanical, including photocopying, recording, or by an information storage

Java EE 5

Page 168 Rev 3.1.2 © 2007 ITCourseware, LLC

Lifecycle Callbacks

Lifecycle callback annotations allow you to specify methods that will be calledby the container at important times during the lifetime of the session bean.

@PostConstruct — Called after a session bean is instantiated and allinjections have completed.

@PostActivate — Called after a session bean is moved from thepassivated state.

@PrePassivate — Called before a session bean is moved to thepassivated state.

@PreDestroy — Called before a session bean is destroyed.

These methods must be public, return void, and have no parameters.

Use @PostActivate and @PrePassivate only in stateful beans; the rest can beused in both stateful and stateless session beans.

Page 49: Java EE 5 · No part of this book may be reproduced or utilized in any form or by any means, electronic or mechanical, including photocopying, recording, or by an information storage

Chapter 9 Session Beans and Message-Driven Beans

© 2007 ITCourseware, LLC Rev 3.1.2 Page 169

Initialize your fields in the@PostConstruct method.

shoppingcart/ShoppingCartBean.java...import javax.annotation.PreDestroy;import javax.annotation.PostConstruct;import javax.annotation.Resource;import javax.ejb.EJB;import javax.ejb.PrePassivate;import javax.ejb.PostActivate;...@Stateful(mappedName="ShoppingCartJNDIName")public class ShoppingCartBean implements ShoppingCart {

...@PostConstructpublic void create() {

System.out.println("In @PostConstruct method.");shoppingBasket = new ShoppingBasket();

}@PostActivatepublic void postActivate() {

System.out.println("In @PostConstruct method.");}@PrePassivatepublic void prePassivate() {

System.out.println("In @PrePassivate method.");}@PreDestroypublic void destroy() {

System.out.println("In @PreDestroy method.");}@Removepublic void remove() {

System.out.println("In @Remove method.");shoppingBasket = null;

}}

Page 50: Java EE 5 · No part of this book may be reproduced or utilized in any form or by any means, electronic or mechanical, including photocopying, recording, or by an information storage

Java EE 5

Page 170 Rev 3.1.2 © 2007 ITCourseware, LLC

Dependency Injection

Servlets and EJBs may have dependencies upon other beans, connectionfactories, JMS connection factories, and datasources.

The Java EE container provides services that allocate needed resources to JavaEE components.

Dependency annotations are attached to fields which indicate which resourceshould be assigned to the field.

Fields that are labeled with dependency annotations are automatically initialized(called injection) by the Java EE container to the required resource.

@EJBprivate CreditCardValidator validator;

The dependency annotation may include the reference name and type,when the simple annotation is not sufficient to uniquely identify therequired resource.

@EJB(name="creditCardValidatorBean",beanInterface=CreditCardValidator.class)

private CreditCardValidator validator;

Dependency injection makes most JNDI lookups unnecessary for resourceassignment.

You should still use JNDI lookups if you want to store a resource in alocal variable rather than a field.

A servlet should not store a stateful session bean for variousreasons: For example, threading concerns.

Page 51: Java EE 5 · No part of this book may be reproduced or utilized in any form or by any means, electronic or mechanical, including photocopying, recording, or by an information storage

Chapter 9 Session Beans and Message-Driven Beans

© 2007 ITCourseware, LLC Rev 3.1.2 Page 171

Inject an EJB instanceinto the validator field.

Steps taken by the container for EJB field injection are:

1. The bean is instantiated.2. The Java EE container locates the correct EJB by looking for a resource that matches the field's

datatype.3. The field is injected with the proper resource.

shoppingcart/ShoppingCartBean.java...import javax.ejb.EJB;...@Stateful(mappedName="ShoppingCartJNDIName")public class ShoppingCartBean implements ShoppingCart {

...@EJBprivate CreditCardValidator validator;private ShoppingBasket shoppingBasket;...public boolean purchase() {

String cardNumber = shoppingBasket.getCardNumber();boolean valid = validator.isValid(cardNumber)if (valid) {

String summary = shoppingBasket.getSummary();sendItemsToQueue(summary);

}...

}

shoppingcart/ShoppingCartServlet.java...public class ShoppingCartServlet extends HttpServlet {

public void doGet(HttpServletRequest req, HttpServletResponse res)throws ServletException, IOException {...try {

Context jndi = new InitialContext();shoppingCart =

(ShoppingCart) jndi.lookup("ShoppingCartJNDIName");session.setAttribute("cart", shoppingCart);

}...

}...}

Any client that uses JNDI tolook up this bean will use the

mappedName.

You should not inject astateful resource into a

servlet's field. Instead useJNDI to look up the resource.

Page 52: Java EE 5 · No part of this book may be reproduced or utilized in any form or by any means, electronic or mechanical, including photocopying, recording, or by an information storage

Java EE 5

Page 172 Rev 3.1.2 © 2007 ITCourseware, LLC

Message-Driven Beans (MDBs) allow Java EE applications to leveragemessaging functionality.

MDBs are JMS MessageConsumers that exist inside an EJB container.

The only way to invoke an MDB is to send a message to the JMSdestination of which the MDB is a consumer.

When a message arrives, the container calls the MDB's onMessage()method to process the message.

Message-Driven Beans include the following properties:

MDBs are stateless.

The container may pool MDBs.

All MDBs in the pool are identical.

An MDB implements the javax.jms.MessageListener interface.

An MDB is annotated with @MessageDriven.

MDBs are never passivated.

Message-Driven Beans

Page 53: Java EE 5 · No part of this book may be reproduced or utilized in any form or by any means, electronic or mechanical, including photocopying, recording, or by an information storage

Chapter 9 Session Beans and Message-Driven Beans

© 2007 ITCourseware, LLC Rev 3.1.2 Page 173

shoppingcart/ShippingMDB.javapackage shoppingcart;

import javax.ejb.MessageDriven;import javax.jms.MapMessage;import javax.jms.Message;import javax.jms.MessageListener;

@MessageDriven(mappedName = "jms/MyQueue")public class ShippingMDB implements MessageListener {

public void onMessage(Message message) {try {

MapMessage mapMessage = (MapMessage) message;String summary = mapMessage.getString("summary");System.out.println(summary);// To do: notify shipping department to send items to customer.

}catch (Exception e) {

System.err.println(e);}

}}

Try It:To test the application, go to http://localhost:8080/ShoppingCart/shoppingcart.jsp and purchase anitem. View the output of the MDB in the server log.

Specify thename of the

queue within theannotation.

Page 54: Java EE 5 · No part of this book may be reproduced or utilized in any form or by any means, electronic or mechanical, including photocopying, recording, or by an information storage

Java EE 5

Page 174 Rev 3.1.2 © 2007 ITCourseware, LLC

MDB Lifecycle

An MDB is created in the following steps:

1. The MDB is instantiated by the Class.newInstance() method.

2. The container injects dependencies into the MDB.

3. The container calls the @PostConstruct method.

4. The container places the MDB in the Method-Ready Pool.

An MDB listens for messages in the Method-Ready state:

When a message arrives, the container calls the onMessage() method.

An MDB terminates when entering the Does Not Exist state:

At the end of the lifecycle, the container calls the method annotated with@PreDestroy, if any.

The bean instance is then ready for garbage collection.

Page 55: Java EE 5 · No part of this book may be reproduced or utilized in any form or by any means, electronic or mechanical, including photocopying, recording, or by an information storage

Chapter 9 Session Beans and Message-Driven Beans

© 2007 ITCourseware, LLC Rev 3.1.2 Page 175

noitisnarT sllaCreniatnoC

morF tsixEtoNseoD otlooPydaeRdohteM

)(ecnatsnIwen.ssalCsnoitcejnI

tcurtsnoCtsoP@

morF looPydaeRdohteM ottsixEtoNseoD

yortseDerP@

Does Not Exist

Method Ready Pool

@PreDestroyClass.newInstance()injections@PostConstruct

onMessage()

Page 56: Java EE 5 · No part of this book may be reproduced or utilized in any form or by any means, electronic or mechanical, including photocopying, recording, or by an information storage

Java EE 5

Page 176 Rev 3.1.2 © 2007 ITCourseware, LLC

Sending a Message

To send a message to an MDB, you must specify the connection factory andqueue.

The connection factory and queue can be specified by injection:

@Resource(mappedName = "jms/MyQueueFactory")private ConnectionFactory connectionFactory;

@Resource(mappedName = "jms/MyQueue")private Queue queue;

Using the connection factory, you can obtain a connection, and then a session.

Connection connect =connectionFactory.createConnection();

Session session = connect.createSession(false,Session.AUTO_ACKNOWLEDGE);

The session allows you to create a message producer, based upon the queue.

MessageProducer sender = session.createProducer(queue);

With the message producer, you can create a message and place data into it.

MapMessage message = session.createMapMessage();

message.setString("customerID", 4523A67);

Send the message after the data is set into it.

sender.send(message);

Page 57: Java EE 5 · No part of this book may be reproduced or utilized in any form or by any means, electronic or mechanical, including photocopying, recording, or by an information storage

Chapter 9 Session Beans and Message-Driven Beans

© 2007 ITCourseware, LLC Rev 3.1.2 Page 177

This stateful session bean is sending a message to the queue, to be picked up later by the MDB.

shoppingcart/ShoppingCartBean.java...@Stateful(mappedName="ShoppingCartJNDIName")public class ShoppingCartBean implements ShoppingCart {

@Resource(mappedName = "jms/MyQueueFactory")private ConnectionFactory connectionFactory;@Resource(mappedName = "jms/MyQueue")private Queue queue;...private void sendItemsToQueue(String summary) {

try {Connection connect = connectionFactory.createConnection();Session session = connect.createSession(false,

Session.AUTO_ACKNOWLEDGE);

MessageProducer sender = session.createProducer(queue);MapMessage message = session.createMapMessage();message.setString("summary", summary);sender.send(message);connect.close();

}catch(Exception e) {

System.err.println(e);}

}...

}

Page 58: Java EE 5 · No part of this book may be reproduced or utilized in any form or by any means, electronic or mechanical, including photocopying, recording, or by an information storage

Java EE 5

Page 178 Rev 3.1.2 © 2007 ITCourseware, LLC

In these labs, you will write an expense report application that allows an employee to use a browserto input expense report information. For example:

Name: Jeff JohnsonDescription: HotelAmount: $233.75

Description: Rental CarAmount: $195.00

Description: DinnerAmount: $8.95

❶ Write a stateful session bean that stores expenses. Make sure to include methods that allow a newexpense to be added, a listing of the currently-stored expenses, and a way to indicate that allexpenses have been submitted.(Solutions: Expenses1/expensereport/ExpenseReport.java, Expenses1/expensereport/ExpenseReportBean.java, Expenses1/expensereport/ReportInfo.java)

❷ Write a client to test your bean.(Solutions: Expenses1/expenseReport.jsp, Expenses1/expensereport/ExpenseReportServlet.java, Expenses1/web.xml, Expenses1/expenseReportResults.jsp)

❸ Deploy and test your application.(Solutions: Expenses1/build.xml)

❹ Modify the expense report application to notify an MDB whenever an expense report is submitted.(Solutions: Expenses2/expensereport/ExpenseReportMDB.java, Expenses2/expensereport/ExpenseReportBean.java)

Labs

Page 59: Java EE 5 · No part of this book may be reproduced or utilized in any form or by any means, electronic or mechanical, including photocopying, recording, or by an information storage

Chapter 9 Session Beans and Message-Driven Beans

© 2007 ITCourseware, LLC Rev 3.1.2 Page 179

Page 60: Java EE 5 · No part of this book may be reproduced or utilized in any form or by any means, electronic or mechanical, including photocopying, recording, or by an information storage

Java EE 5

Page 180 Rev 3.1.2 © 2007 ITCourseware, LLC

Page 61: Java EE 5 · No part of this book may be reproduced or utilized in any form or by any means, electronic or mechanical, including photocopying, recording, or by an information storage

Chapter 15 Java Management Extension (JMX)

© 2007 ITCourseware, LLC Rev 3.1.2 Page 285

Chapter 15 - Java Management Extension (JMX)

Objectives

Use JMX to monitor and manage Javaapplications.

Model attributes, operations, andnotifications in an MBean.

Implement a standard MBean.

Access MBeans from a JMX client.

Generate notifications when problems aredetected.

Page 62: Java EE 5 · No part of this book may be reproduced or utilized in any form or by any means, electronic or mechanical, including photocopying, recording, or by an information storage

Java EE 5

Page 286 Rev 3.1.2 © 2007 ITCourseware, LLC

The Java Management Extension (JMX) provides the means for managing andmonitoring Java applications at runtime.

Use JMX to view and modify configuration settings.

Use JMX to obtain statistics about your application, or include failurenotification.

There is a low barrier to entry for introducing JMX into an application.

Any code can be managed, including business components, such asServlets and EJBs, as well as infrastructure components, such as queuesand pools.

Your applications make use of the provided JMX server — you don'twrite your own.

The Java 5 SDK ships with a JMX client tool called JConsole that you canuse to interact with your JMX components.

The JMX architecture is divided into three levels: instrumentation, agent, anddistributed services.

The instrumentation level includes wrapper objects, called MBeans, thatexpose properties and operations of underlying manageable resources.

The agent level includes the MBean server, a registry which enables localand remote clients access to an MBean's attributes and operations.

The distributed services level defines the interfaces that tools may use tointeract with MBean servers.

As a developer, you will create the MBeans and register them with the MBeanserver.

What is JMX?

Page 63: Java EE 5 · No part of this book may be reproduced or utilized in any form or by any means, electronic or mechanical, including photocopying, recording, or by an information storage

Chapter 15 Java Management Extension (JMX)

© 2007 ITCourseware, LLC Rev 3.1.2 Page 287

Note:There are several Java Specification Requests (JSR) that directly affect JMX. The original JavaManagement Extension API was developed as JSR 3 through the Java Community Process (JCP). JSR 77defines a standard method for managing Java EE application servers. JSR 255 is the next version of JMX(JMX 2.0), that adds annotations, among other things. JMX 2.0 is included in Java 6.

For remote access, JSR 160 defines the Remote API for accessing JMX resources using RMI. JSR 262specifies how SOAP web service clients can interact with JMX.

Like most advanced Java APIs, JMX is a specification, not an implementation. Sun provides a ReferenceImplementation that we will use in this chapter, but others are available, including the open source MX4Jproject available at http://mx4j.sourceforge.net/.

For more information about JMX in general, see http://java.sun.com/jmx.

DistributedServices

Level

AgentLevel

InstrumentationLevel

RMI Client

Web ServiceClient

Type XClient

RMI Connector

Web ServiceConnector

Type XConnector

RMI SOAP Type XProtocol

MBean MBean

MBean Server

Page 64: Java EE 5 · No part of this book may be reproduced or utilized in any form or by any means, electronic or mechanical, including photocopying, recording, or by an information storage

Java EE 5

Page 288 Rev 3.1.2 © 2007 ITCourseware, LLC

A managed bean, or MBean, defines the attributes, operations, and notificationsthat are exposed to a JMX client.

An attribute represents data that needs to be managed or monitored.

The number of allocated connections in a connection pool wouldbe an attribute, for example.

Invoke behavior on an MBean by calling an operation.

An example would be an operation that tests a connection in aconnection pool.

Notification alerts you if something interesting happens within the MBean,such as an error.

To create a standard MBean, you need to write an interface and a class thatimplements it.

The interface defines the attributes and operations.

The implementation class contains the code you intend to monitor, orserves as an adapter to an underlying resource or device.

The class can also produce notifications.

Each MBean has a management interface that is made up of its attributes,operations, notifications, and public constructors.

Clients only see the management interface, not the Java interface orimplementation class.

MBeans

Page 65: Java EE 5 · No part of this book may be reproduced or utilized in any form or by any means, electronic or mechanical, including photocopying, recording, or by an information storage

Chapter 15 Java Management Extension (JMX)

© 2007 ITCourseware, LLC Rev 3.1.2 Page 289

The JMX specification defines four types of MBeans: standard, dynamic, open, and model.

Standard MBeans are the simplest and most common.

Dynamic MBeans do not define a static interface like standard MBeans. Instead, they definemethods that clients can call to dynamically determine the available JMX attributes andoperations.

Open MBeans are portable and dynamic MBeans that allows clients to work with them even ifthey don't have access to the original .class files where they were defined. This is accomplishedby building open MBeans with extra metadata and composing them of a small set of predefinedtypes.

Model MBeans are generic and configurable. They add MBean functionality to existing codewithout modification.

This chapter covers standard MBeans.

Page 66: Java EE 5 · No part of this book may be reproduced or utilized in any form or by any means, electronic or mechanical, including photocopying, recording, or by an information storage

Java EE 5

Page 290 Rev 3.1.2 © 2007 ITCourseware, LLC

When you implement the MBean interface and class, you must follow a fewrules:

The interface name must be the same name as the implementation class,with MBean appended to it.

For example, if your implementation class is namedConnectionPool, then the interface should be namedConnectionPoolMBean.

Define attributes in the interface by writing public get and set methods.

You must follow the naming convention getAttribute() andsetAttribute().

The name of the attribute is dynamically derived by reflection fromthe get and set methods.

The return type of the get method must match the parameter type ofthe set method.

Define a read-only attribute by not including the set method.

Any other methods in the interface are the operations.

The class must be public, have a public constructor, and implement theinterface.

If any of the rules are violated, you will get a NotCompliantMBeanExceptionupon registration with the MBean server.

Creating a Standard MBean

Page 67: Java EE 5 · No part of this book may be reproduced or utilized in any form or by any means, electronic or mechanical, including photocopying, recording, or by an information storage

Chapter 15 Java Management Extension (JMX)

© 2007 ITCourseware, LLC Rev 3.1.2 Page 291

This MBean has twoattributes: NumValid and

NumInvalid.

Make sure to implementthe MBean interface.

The reset() methodsets the numberValidand numberInvalidfields back to zero.

The example below tracks the number of valid and invalid credit cards that have been processed by theCreditCardValidatorBean.

validator/CreditCardValidatorBeanMBean.javapackage validator;

public interface CreditCardValidatorBeanMBean {// attributespublic int getNumValid();public int getNumInvalid();//operationspublic void reset();

}

validator/CreditCardValidatorBean.java...@Statelesspublic class CreditCardValidatorBean

extends NotificationBroadcasterSupportimplements CreditCardValidator, CreditCardValidatorBeanMBean {

private static int nextId;private int id;private int numberValid;private int numberInvalid;private ObjectName objectName;private int notificationSequenceNumber = 0;

public void reset() {setNumValid(0);setNumInvalid(0);

}public int getNumValid() {

return numberValid;}public int getNumInvalid() {

return numberInvalid;}...

}

Page 68: Java EE 5 · No part of this book may be reproduced or utilized in any form or by any means, electronic or mechanical, including photocopying, recording, or by an information storage

Java EE 5

Page 292 Rev 3.1.2 © 2007 ITCourseware, LLC

Your MBeans must be given unique names before they can be registered withinthe MBean Server.

Use an instance of javax.management.ObjectName to accomplish this.

An ObjectName is made up of two parts: the domain and key properties.

The domain is any sequence of characters except for a colon (:).

The convention is to use your DNS name in reverse, like packages.

The key properties are an unordered set of key/value pairs.

Separate each key/value pair with a comma (,).

Separate the domain from the key properties with a colon (:).

Create an ObjectName instance by passing in a single String with both thedomain and key properties embedded in it.

ObjectName name =new ObjectName("com.example:name=Pool1,type=ConnectionPool");

Alternatively, you can pass in the domain name as the first argument and aHashtable with the key/value pairs as the second argument.

A third constructor allows you to pass in three Strings, one for thedomain, one for the key, and one for the value.

Object Names

Page 69: Java EE 5 · No part of this book may be reproduced or utilized in any form or by any means, electronic or mechanical, including photocopying, recording, or by an information storage

Chapter 15 Java Management Extension (JMX)

© 2007 ITCourseware, LLC Rev 3.1.2 Page 293

The key called Name isnot predefined; you canuse any key you want,as long as it yields aunique ObjectName.

validator/CreditCardValidatorBean.java...import javax.management.ObjectName;...@Statelesspublic class CreditCardValidatorBean

extends NotificationBroadcasterSupportimplements CreditCardValidator, CreditCardValidatorBeanMBean {

private static int nextId;private int id;private int numberValid;private int numberInvalid;private ObjectName objectName;private int notificationSequenceNumber = 0;...public void initialize() {

id = nextId++;try {

MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();objectName =

new ObjectName("Validator:Name=CreditCardValidatorBean" + id);mbs.registerMBean(this, objectName);

}catch (Exception e) {

System.err.println(e);}

}...

}

Note:For detailed coverage of ObjectName syntax, see the Java API documentation.

Page 70: Java EE 5 · No part of this book may be reproduced or utilized in any form or by any means, electronic or mechanical, including photocopying, recording, or by an information storage

Java EE 5

Page 294 Rev 3.1.2 © 2007 ITCourseware, LLC

Before you can access an MBean, you must register it with a managed beanserver, which is a repository and manager for MBeans.

Clients never interact directly with MBeans; all of their JMXcommunications are funneled through the MBean server.

An MBeanServerConnection object represents a local or remote connectionto an MBean server.

Retrieve an MBeanServer instance from the ManagementFactory classwith the getPlatformMBeanServer() method.

MBeanServerConnection mbs;mbs = ManagementFactory.getPlatformMBeanServer();

This MBean server comes with built-in platform MBeans torepresent JVM properties, such as memory usage.

Once you have an instance of the server, register your MBean object with itusing the registerMBean() method.

ConnectionPoolMBean mbean = new ConnectionPool();ObjectName name = new ObjectName("com.example:type=pool");mbs.registerMBean(mbean, name);

Alternatively, you can call the createMBean() method to instantiate andregister your MBean in one call.

mbs.createMBean(ConnectionPool.class,new ObjectName("com.example:type=pool"));

Call unregisterMBean() to remove an MBean from the MBeanServer.

The MBean Server

Page 71: Java EE 5 · No part of this book may be reproduced or utilized in any form or by any means, electronic or mechanical, including photocopying, recording, or by an information storage

Chapter 15 Java Management Extension (JMX)

© 2007 ITCourseware, LLC Rev 3.1.2 Page 295

An EJB method tagged with the@PostConstruct annotation is

called upon object creation.

Because of the @PreDestroyannotation, the cleanup()

method is called just before thisinstance becomes available for

garbage collection.

validator/CreditCardValidatorBean.java...@PostConstructpublic void initialize() {

id = nextId++;try {

MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();objectName =

new ObjectName("Validator:Name=CreditCardValidatorBean" + id);mbs.registerMBean(this, objectName);

}catch (Exception e) {

System.err.println(e);}

}

@PreDestroypublic void cleanup() {

try {MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();mbs.unregisterMBean(objectName);

}catch (Exception e) {

System.err.println(e);}

}...}

Try It:Run the asant command in the chapter directory to build and deploy the credit card validator example.Go to http://localhost:8080/CreditCardValidator/ValidateCard.html to validate a credit card.

Note:MBeanServer and ObjectName are members of the javax.management package.ManagementFactory is part of the java.lang.management package.

Page 72: Java EE 5 · No part of this book may be reproduced or utilized in any form or by any means, electronic or mechanical, including photocopying, recording, or by an information storage

Java EE 5

Page 296 Rev 3.1.2 © 2007 ITCourseware, LLC

A local JMX client is one that runs in the same Virtual Machine as the MBeanserver.

Use the getPlatformMBeanServer() method, as before, to get aninstance of the MBeanServer.

Then call the getAttribute() method, passing in the ObjectName of theMBean you wish to query as well as the name of the attribute.

ObjectName name = new ObjectName("com.example:type=pool");Object obj = mbs.getAttribute(name, "NumberAllocatedConnections");

Call the setAttribute() method to modify a read/write MBean attribute.

Pass in the ObjectName as the first parameter and an Attributeobject as the second.

Invoke an operation with the invoke() method, pass in:

An ObjectName instance containing the name of the MBeanThe name of the operation to invoke as a StringAny parameter values as an array of ObjectsThe signature of the operation as an array of Strings

Local Client

Page 73: Java EE 5 · No part of this book may be reproduced or utilized in any form or by any means, electronic or mechanical, including photocopying, recording, or by an information storage

Chapter 15 Java Management Extension (JMX)

© 2007 ITCourseware, LLC Rev 3.1.2 Page 297

Attribute names arederived from the MBean's

get/set methods.

validator/MonitorServlet.java...import java.lang.management.ManagementFactory;import javax.management.MBeanServer;import javax.management.ObjectName;

public class MonitorServlet extends HttpServlet {

public void doGet(HttpServletRequest req, HttpServletResponse res)throws ServletException, IOException {

try {MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();ObjectName objName =

new ObjectName("Validator:Name=CreditCardValidatorBean0");

if (mbs.isRegistered(objName)) {if (req.getParameter("reset") != null) {

mbs.invoke(objName, "reset", null, null);}

Integer valid =(Integer) mbs.getAttribute(objName, "NumValid");

Integer invalid =(Integer) mbs.getAttribute(objName, "NumInvalid");

req.setAttribute("NumValid", valid);req.setAttribute("NumInvalid", invalid);

}else {

req.setAttribute("NumValid", new Integer(0));req.setAttribute("NumInvalid", new Integer(0));

}forwardToJSP(req, res, "/Monitor.jsp");

}catch (Exception e) {

throw new ServletException(e);}

}...

}

Try It:After validating several credit card numbers at http://localhost:8080/CreditCardValidator/ValidateCard.html, take another web browser to http://localhost:8080/CreditCardValidator/Monitor to see the number of valid and invalid credit card transactions. Press the reset button toinvoke the reset operation and set the attributes back to zero.

Page 74: Java EE 5 · No part of this book may be reproduced or utilized in any form or by any means, electronic or mechanical, including photocopying, recording, or by an information storage

Java EE 5

Page 298 Rev 3.1.2 © 2007 ITCourseware, LLC

Remote Client

The original Java Specification Request for JMX (JSR 3) specifies how toconnect to a JMX-enabled application locally.

JSR 160 defines how to connect remotely to a JMX-enabled applicationusing RMI.

The client JMX implementation need not be from the same vendoras the implementation on the server.

A remote client will call the same getAttribute(), setAttribute(), and invoke()methods as the local client did, but will need to retrieve the MBean server objectdifferently.

Use the MBeanServerConnection interface for local and remotecommunications.

The child interface MBeanServer only allows for local communications.

To retrieve an MBeanServerConnection object, you must first get aJMXConnector from a JMXConnectorFactory, and then call thegetMBeanServerConnection() method on it.

JMXConnector connector =JMXConnectorFactory.connect(serviceURL, env);

MBeanServerConnection mbs =connector.getMBeanServerConnection();

The JMXConnectoryFactory.connect() method takes two parameters:the URL of the remote JMX application and a Hashtable with additionalproperties.

You can use the Hashtable to pass in authentication information,for example.

Page 75: Java EE 5 · No part of this book may be reproduced or utilized in any form or by any means, electronic or mechanical, including photocopying, recording, or by an information storage

Chapter 15 Java Management Extension (JMX)

© 2007 ITCourseware, LLC Rev 3.1.2 Page 299

The Sunapplication server

listens for JMXcommunication at

this URL.

RemoteClient.javaimport java.util.Hashtable;import javax.management.MBeanServerConnection;import javax.management.ObjectName;import javax.management.remote.JMXConnector;import javax.management.remote.JMXConnectorFactory;import javax.management.remote.JMXServiceURL;

public class RemoteClient {public static void main(String[] args) {

try {String url =

"service:jmx:rmi:///jndi/rmi://localhost:8686/jmxrmi";ObjectName objName =

new ObjectName("Validator:Name=CreditCardValidatorBean0");String[] credentials = new String[] {"admin", "password"};

Hashtable<String, String[]> env =new Hashtable<String, String[]>();

env.put(JMXConnector.CREDENTIALS, credentials);

JMXServiceURL serviceURL = new JMXServiceURL(url);JMXConnector connector =

JMXConnectorFactory.connect(serviceURL, env);MBeanServerConnection mbs = connector.getMBeanServerConnection();

if (mbs.isRegistered(objName)) {System.out.println("Num Valid: " +

mbs.getAttribute(objName, "NumValid"));System.out.println("Num Invalid: " +

mbs.getAttribute(objName, "NumInvalid"));}else {

System.err.println("No object named: " + objName + " found");}

}catch (Exception e) {

e.printStackTrace();}

}}

Try It:Compile and run RemoteClient.java to retrieve the number of valid and invalid credit cardtransactions remotely. Make sure the MBean is registered by validating at least one credit card athttp://localhost:8080/CreditCardValidator/ValidateCard.html before running the client code.

Page 76: Java EE 5 · No part of this book may be reproduced or utilized in any form or by any means, electronic or mechanical, including photocopying, recording, or by an information storage

Java EE 5

Page 300 Rev 3.1.2 © 2007 ITCourseware, LLC

JConsole

The Sun JRE provides extra support for JMX via system properties and theJConsole JMX client tool.

The Java 5 SDK comes with a graphical monitoring and management tool calledJConsole.

Use it to manage both platform and user-defined MBeans remotely, ratherthan write your own remote client.

Start JConsole by running the jconsole command from%JAVA_HOME%\bin.

To use JConsole to monitor an application on the local system, start theapplication with the com.sun.management.jmxremote system property.

java -Dcom.sun.management.jmxremote MainClass

This installs the platform MBean server, registers the platform MBeanswith it, and creates an RMI connector for access to the server.

Enable JMX access from a remote system by setting thecom.sun.management.jmxremote.port property instead.

java -Dcom.sun.management.jmxremote.port=4321 MainClass

You can use JConsole or your own client application to remotely orlocally monitor and manage the JMX-enabled application.

Page 77: Java EE 5 · No part of this book may be reproduced or utilized in any form or by any means, electronic or mechanical, including photocopying, recording, or by an information storage

Chapter 15 Java Management Extension (JMX)

© 2007 ITCourseware, LLC Rev 3.1.2 Page 301

Try It:Run the jconsole command on the command line:

jconsole

In the JConsole: NewConnection dialog, choose the Remote Process radio button, and enter thefollowing:

Remote Process: localhost: 8686Username: adminPassword: password

Click the Connect button.

On the MBeans tab, you should see a tree on the left side, choose Validator | CreditCardValidatorBean |Attributes. On the right you should now see the current values of the NumInvalid and NumValidattributes. You can invoke the reset operation by choosing Operations in the tree.

Note:You may also need to set the com.sun.management.jmxremote.authenticate andcom.sun.management.jmxremote.ssl properties to false to turn off authentication and SSL whenaccessing a JMX server remotely.

java -Dcom.sun.management.jmxremote.port=4321-Dcom.sun.management.jmxremote.authenticate=false-Dcom.sun.management.jmxremote.ssl=false MainClass

For additional system properties, see http://java.sun.com/javase/6/docs/technotes/guides/management/agent.html.

Page 78: Java EE 5 · No part of this book may be reproduced or utilized in any form or by any means, electronic or mechanical, including photocopying, recording, or by an information storage

Java EE 5

Page 302 Rev 3.1.2 © 2007 ITCourseware, LLC

Notifications

JMX notifies you of problems or state changes.

Subscribing client code can be notified if an attribute value goes over athreshold or if an exception is generated.

The order in which you receive the notifications may not be the same asthe order in which they were sent.

Each notification carries a sequence number that you can check iforder is important.

The javax.management package provides the classes and interfaces thatsupport notifications.

To add notifications to your MBean code, implement the NotificationEmmitterinterface.

For simplicity, you can extend the NotificationBroadcasterSupportclass instead.

Override the getNotificationInfo() method to describe to clients whatkinds of notifications your MBean can generate.

To generate a notification, create an instance of a Notification, or one of itssubclasses, and pass it to the sendNotification() method.

Use an instance of the AttributeChangeNotification subclass for statechanges.

Pass the ObjectName, sequence number, timestamp, message string,name of the attribute that changed, type of the attribute that changed, oldvalue of the attribute, and new value of the attribute to the constructor.

Page 79: Java EE 5 · No part of this book may be reproduced or utilized in any form or by any means, electronic or mechanical, including photocopying, recording, or by an information storage

Chapter 15 Java Management Extension (JMX)

© 2007 ITCourseware, LLC Rev 3.1.2 Page 303

validator/CreditCardValidatorBean.java...public class CreditCardValidatorBean

extends NotificationBroadcasterSupportimplements CreditCardValidator, CreditCardValidatorBeanMBean {...public void setNumValid(int num) {

int oldNumberValid = numberValid;numberValid = num;

// notification codeNotification n = new AttributeChangeNotification(objectName,

notificationSequenceNumber++, System.currentTimeMillis(),"Num valid changed to " + numberValid, "NumValid", "int",oldNumberValid, numberValid);

sendNotification(n);}...@Overridepublic MBeanNotificationInfo[] getNotificationInfo() {

String[] types =new String[] {AttributeChangeNotification.ATTRIBUTE_CHANGE};

String name = AttributeChangeNotification.class.getName();MBeanNotificationInfo info1 =

new MBeanNotificationInfo(types, name, "NumValid changed");MBeanNotificationInfo info2 =

new MBeanNotificationInfo(types, name, "NumInvalid changed");return new MBeanNotificationInfo[] {info1, info2};

}...

}

Try It:In JConsole, choose the CreditCardValidatorBean. Choose Notifications in the tree and clickSubscribe. Go to http://localhost:8080/CreditCardValidator/ValidateCard.html and validate acouple of credit cards. Go back to JConsole and view what is now listed in the Notifications area.

Page 80: Java EE 5 · No part of this book may be reproduced or utilized in any form or by any means, electronic or mechanical, including photocopying, recording, or by an information storage

Java EE 5

Page 304 Rev 3.1.2 © 2007 ITCourseware, LLC

❶ In the chapter directory, you will find the following files: IQueue.java, Queue.java,QueueAdder.java, QueueRemover.java, and QueueGUI.java. The Queue class implementsthe IQueue interface and represents a simple queue implementation with enqueue() anddequeue() methods. QueueAdder and QueueRemover are Runnable classes which canadd and remove Integers from the queue at varying rates. QueueGUI represents a userinterface that shows what item was most recently enqueued and dequeued as well as allowingthe user to control the rate of queue additions and removals with a pair of sliders. Compile andrun QueueGUI.java to become familiar with running the application. Review the code inQueue.java; you will be converting it into an MBean next.

❷ Create an MBean interface that defines two read-only attributes called throughput andNumItemsInQueue. The throughput attribute defines the number of items that the queuehas processed (enqueued and dequeued). Also add two operations to the interface calledresetThroughput() and clearQueue().(Solution: QueueMBean.java)

❸ Modify Queue.java to support the interface you wrote in ❷. Make sure to add the necessarycode to register the MBean with the MBean server.(Solution: Queue.java)

❹ Create a remote JMX client that prints out the value of each of the attributes.

Hint:If you start the QueueGUI with the following options:

-Dcom.sun.management.jmxremote.port=1234-Dcom.sun.management.jmxremote.authenticate=false-Dcom.sun.management.jmxremote.ssl=false

then the remote service URL will be:service:jmx:rmi:///jndi/rmi://localhost:1234/jmxrmi

(Solution: QueueClient.java)

❺ Add notification code to Queue.java to notify clients if the number of items in the queue isabove 100.(Solution: Queue2.java, Queue2MBean.java, QueueGUI2.java)

❻ Use JConsole to monitor the application and test the notification you added in ❺.

Labs

Page 81: Java EE 5 · No part of this book may be reproduced or utilized in any form or by any means, electronic or mechanical, including photocopying, recording, or by an information storage

Chapter 15 Java Management Extension (JMX)

© 2007 ITCourseware, LLC Rev 3.1.2 Page 305

Page 82: Java EE 5 · No part of this book may be reproduced or utilized in any form or by any means, electronic or mechanical, including photocopying, recording, or by an information storage

Java EE 5

Page 306 Rev 3.1.2 © 2007 ITCourseware, LLC