You are on page 1of 75

J2EE Guru Night

Atlanta Java Users Group www.ajug.org May 20, 2003

AJUG Announcements
Jeff Mitchell Certified Java Programmer June Esoteric Night: J2ME, Jini, alternative web tier frameworks, JMX July Aspect Oriented Programming August TBD September Dave Thomas (Pragmatic Programmer)

Guru Night
Elements of Guru Night: The overall goal is to educate the audience on what element of knowledge are vital to making someone the "guru", architect or senior/key player on a J2EE based project. To hold an interactive discussion on best practices for J2EE application design, development and deployment.

Event Format
Event Format
Two

halves with an intermission: 6:30 until 8:00 and 8:15 until 9:15 PM A host presenter covering the materials An expert panel that has collaborated on these materials and feels comfortable talking to the issues. An allowance for interaction with the audience members with ad-hoc questions and moderated Q&A.

What is this presentation about?


Presentation Focus:
Definition

of terminology and decision criteria for J2EE application design and construction techniques. Apply the right tool to the right job. Define what does the lead/senior developer/architect on a J2EE project need to know Java & Web Application Architectural Patterns

What is this presentation NOT about?


Out of scope:
Lifecycle

development methodologies like Rational Unified Process or Extreme Programming (waterfall, agile, Information Engineering, IDEF, blah, blah) Documentation techniques like UML

Audience
Audience
Background

in J2EE development usage Background in software application development lifecycles Understanding of Java and Web application architecture terminology (e.g. SOAP, HTML, HTTP, XML, GET/POST, WAR, JSP, CSS)

Expert Panel
Jason Chambers

Advisory Developer - Delta Technology responsible for Delta.com and Flysong.com. Open Source Developer: CacheCow, Edgar, Commando, WebDoctor AJUG Presenter on JUnit Author of Ant Developer's Handbook from SAMS and is a Senior Consultant for BravePoint in Atlanta. Published author in the Java Developers Journal. AJUG Presenter on Ant Struts project committer, Creator of Struts Console, Oracle Magazine Java Developer of the Year (2002) Author: The Art of Java" from McGraw-Hill Future AJUG Presenter on AOP Host/Presenter/Moderator - otherwise not important ;-)

Joey Gibson

James Holmes

Burr Sutter (sutter@bravepoint.com)

What is a Guru?
A personal spiritual teacher A teacher and guide in spiritual and philosophical matters. A trusted counselor and adviser; a mentor. A recognized leader in a field

Architects Concerns
Some considerations when creating the application architecture and starting up a J2EE project:

System Functionality when/why to use the right tool Ownership of the frameworks: UI, Distribution, Persistence, Integration Team development Code modification and redeployment (maintainability and manageability) Supportability of code (message handling, I18N, logging) Ongoing System Management Security Documentation and/or model-driven design - CASE ;-) Builds and release cycles Understand the distribution of interacting components Client-side device capabilities Network and server infrastructure Future needs of the user base extensibility Code-level best practices (standards, performance, thread-safety) Politics Legacy Futurist Communication

10

Futures
Keeping your eye on the crystal ball:
JDK

1.5 (Tiger) JSP Standard Tag Library (JSTL) JSP 2.0 Java Server Faces

11

Futures JDK 1.5


wrapper type myCollection.add(5) // instead of myCollection.add(new Integer(5)).

Typesafe Enums Autoboxing - Automatic conversion from primitive type to corresponding

Static imports - Avoid qualifying static members with class names


import static org.iso.Physics.*;

Enhanced For statement


for (Iterator i = c.iterator(); i.hasNext(); ) { TimerTask tt = (TimerTask) i.next(); tt.close(); } //rewritten using the enhanced for statement for (Object o : c) ((TimerTask)o).close();

12

Generics eliminate downcasts

Futures - JSTL
Four Libraries:
Core:

provides programmatic flow control, similar to struts-logic, (if, set, choose-when, forEach, catch) Formatting: I18N support for numbers, dates and parameterized message strings (message, formatDate, parseNumber, formatName) XML: parsing, querying, transforming Database: SQL select, insert, update, delete

13

Futures JSP 2.0


Expression Language (from JSTL) based on ECMAScript and XPath. Simple Tag Handlers (created as JSPs, no class file with TLD and entry in web.xml) Ease of Use eliminate the need to know Java to create a server-side dynamic web application.

14

Futures Java Server Faces


Kinda-Sorta like struts-html functionality A set of APIs for: representing UI components and managing their state, handling events and input validation, defining page navigation, and supporting internationalization and accessibility. A JavaServer Pages (JSP) custom tag library for expressing a JavaServer Faces interface within a JSP page.

http://java.sun.com/j2ee/javaserverfaces/
http://www.javaworld.com/javaworld/jw-11-2002/jw-1129-jsf.html
15

Basic Systems Architecture

Host-Based
Terminal Host/Server

Client/Server
Workstation Database Server

Web-Based
Browser

Request Response

SQL Results Database Server

16

Web Application Server

Conceptual N-Tier Architecture I


Users & Interfaces Presentation Tier Business Logic Data Access Integration Data Sources

browser html mobile J2ME/WAP email

rdbms

Xml, EDI, Web Services

workstation swing/.net winforms pda/handheld J2ME / Compact Framework spreadsheet EDI external systems

Legacy In-house ChUI OS/390 AS/400 Vax

Legacy COTS SAP Peoplesoft

firewall vendor/supplier 17 distributor/retailer business partner firewall

vendor/supplier distributor/retailer business partner

Conceptual N-Tier Architecture II


Users & Interfaces Presentation Tier
Servlets/JSP Struts Portals XML Parser XSLT Processor
workstation swing/.net winforms pda/handheld J2ME / Compact Framework spreadsheet EDI external systems

Business Logic

Data Access Integration


EJB Entity Bean Java Data Objects (JDO) DAO/DTO JDBC JCA or Proprietary Adapters/ Connectors

Data Sources

browser html mobile J2ME/WAP email

EJB Session Bean POJO Dynamic Workflow & Rules Components

rdbms

Xml, EDI, Web Services

Legacy In-house ChUI OS/390 AS/400 Vax

SOAP producers

Integration XML Parser


XSLT Processor

SOAP consumers

Legacy COTS SAP Peoplesoft

vendor/supplier 18 distributor/retailer business partner

firewall

Application Server

firewall

vendor/supplier distributor/retailer business partner

J2EE Development Environment


What are the possible components of a J2EE development environment? IDEs/Editors: Eclipse, NetBeans, IntelliJ, JBuilder, JDeveloper, Emacs, VI Modeling Tools+IDEs: Rational (now IBM), Together (now Borland) Source Code Repository Automated Testing Tools Build Management Coding Standards (verified by code reviews)

19

Portals
A Web application with:
Personalization

determined by the end-surfer Customization driven by the group webmaster and developer Layout Management on screen widgets change location Content Management Content Search Declarative & Dynamic Rules engine Declarative & Dynamic Workflow engine
20

Integration
What does an integration engine provide?
Web

Services design and deployment engines TTY Integration 3270/5250/CICS Integration XML and EDI transformation Work-flow management Gateways/drivers/enablers into various COTS products PeopleSoft, SAP, etc.

21

Architects ToolBox
Common free tools for the J2EE/Web architect: Ant (http://ant.apache.org/) JUnit (http://www.junit.org/) Log4J (http://jakarta.apache.org/log4j/) Struts (http://jakarta.apache.org/struts/) CVS (http://www.cvshome.org/) XDoclet (http://xdoclet.sourceforge.net/) FOP (http://xml.apache.org/fop/) Commons (http://jakarta.apache.org/commons/) Tomcat (http://jakarta.apache.org/tomcat/) JBoss (http://www.jboss.org/) Design Patterns (faade, command pattern, singleton, DAO/DTO, factory) (http://www.theserverside.com/patterns/)
22

What is Ant?
What is Ant? Apache Ant is a Java-based build tool. In theory, it is kind of like Make, but without Make's wrinkles.
Free Build files are XML-based Completely Platform/OS independent Easily extensible using Java classes Build Code (run javac,jikes, etc.), run javadoc, create directories, move files, build JARs/WARs, deploy to various containers, run unit tests, XDoclet, PMD, do basically anything

23

Ant Build File


Sample build.xml
<project name="MyProject" default="dist" basedir="."> <description> simple example build file </description> <!-- set global properties for this build --> <property name="src" location="src"/> <property name="build" location="build"/> <property name="dist" location="dist"/> <target name="init"> <!-- Create the time stamp --> <tstamp/> <!-- Create the build directory structure used by compile --> <mkdir dir="${build}"/> </target> <target name="compile" depends="init" description="compile the source " > <!-- Compile the java code from ${src} into ${build} --> <javac srcdir="${src}" destdir="${build}"/> </target> <target name="dist" depends="compile" description="generate the distribution" > <!-- Create the distribution directory --> <mkdir dir="${dist}/lib"/> <!-- Put everything in ${build} into the --> <!-- MyProject-${DSTAMP}.jar file --> <jar jarfile="${dist}/lib/MyProject-${DSTAMP}.jar" basedir="${build}"/> </target> <target name="clean" description="clean up" > <!-- Delete the ${build} and ${dist} directory trees --> <delete dir="${build}"/> <delete dir="${dist}"/> </target> </project>

Continued
24

What is JUnit?
What is JUnit?
JUnit is a regression testing framework written by Erich Gamma and Kent Beck. It is used by the developer who implements unit tests in Java. Primarily used on POJOs and EJBs. Extensions for the GUI tier: Cactus or HTTPUnit for HTML and Abbott for Swing http://jakarta.apache.org/cactus/ http://httpunit.sourceforge.net/ http://sourceforge.net/projects/abbot/

25

JUnit Example Code


public class CacheAdminTest extends TestCase implements CacheAgent { /** * Try and get something from the cache that doesn't exist. */ public void testGetCachedObjectNotFound() { CacheAdmin cacheAdmin = CacheAdmin.getInstance(); cacheAdmin.clear(); try { Object o = cacheAdmin.get("BOGUSKEY"); } catch (CachedObjectNotFoundException e) { // Expected behaviour return; } catch (CacheCowException e) {} fail("Expected CachedObjectNotFoundException"); }

... }

26

What is Log4J?

System.out.println(I am here!);

See Commons Logging


27

UI Architect
Skills for the UI Architect: HTML, XHTML CSS JavaScript Understanding of common and reusable navigation, look & feel, device considerations and overall usability OR SWING, SWT, .NET WinForms Client to Server communications Event-driven concepts Shared client libraries: caches, middle-tier access logic, common UI features such as hotkeys, toolbars, message infrastructure, I18N, formatting and edit masks via regular expression libraries
28

UI Tier Best Practice No Scriplets


<%@ page import="java.sql.*,javax.sql.*,javax.naming.*" %> <HTML> <HEAD> <TITLE>Customer Listing</TITLE> </HEAD> <BODY> <H1 ALIGN="center">Customer Listing</H1> <TABLE WIDTH="75%" BORDER="1" ALIGN="CENTER"> <TR> <TD><B>First Name</B></TD><TD><B>Last Name</B></TD><TD><B>Email</B></TD> </TR> <% InitialContext ic = new InitialContext(); DataSource ds = (DataSource) ic.lookup("java:comp/env/jdbc/myJDBC"); Connection conn = ds.getConnection(); Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery( "select firstName, lastName, eMailAddress from customers"); while (rs.next()) { %> <TR><TD><%= rs.getString(1) %></TD><TD><%= rs.getString(2) %></TD> <TD><%= rs.getString(3) %></TD></TR> <% } stmt.close(); conn.close(); %> </TABLE> </BODY> </HTML>

29

UI Tier Best Practices Beans


<%@ page import="java.sql.*" errorPage="error.jsp" %> <jsp:useBean id="customer" class="beans.CustNameBean" scope="page" /> <HTML> <HEAD> <TITLE>Customer Listing 2 with Bean</TITLE> </HEAD> <BODY> <H1 ALIGN="center">Customer Listing with Bean</H1> <TABLE WIDTH="75%" BORDER="1" ALIGN="CENTER"> <TR> <TD><B>First Name</B></TD><TD><B>Last Name</B></TD><TD><B>Email</B></TD> </TR> <% out.println("\n\n1"); customer.query(); while (customer.next()) { %> <TR> <TD><jsp:getProperty name="customer" property="firstName"/></TD> <TD><%= customer.getLastName() %></TD> <TD><jsp:getProperty name="customer" property="email"/></TD> </TR> <% } %> </TABLE></BODY></HTML>

30

UI Tier Best Practices - Custom Tags


<HTML> <HEAD> <TITLE>Product Listing 3 with TagLib</TITLE> </HEAD> <BODY> <H1 ALIGN="center">Product Listing with taglib</H1> <TABLE WIDTH="75%" BORDER="1" ALIGN="CENTER"> <TR> <TD><B>ProductId</B></TD> <TD><B>Name</B></TD> <TD><B>Category</B></TD> <TD><B>Description</B></TD> </TR> <%@ taglib uri="/web-inf/product.tld" prefix="prod" %> <prod:prodInfo> <TR> <TD BGCOLOR=YELLOW><B><FONT COLOR=BLUE><%= ProductId %> </FONT></B></TD> <TD><%= Name %></TD> <TD><%= Category %></TD> <TD><%= Descn %></TD> </TR> </prod:prodInfo> </TABLE> </BODY> </HTML>

Buy vs Build

31

UI Best Practices - Struts


<%@ taglib uri="struts-logic.tld" prefix="logic" %> <html> <body> <table border="1"> <logic:iterate id="eachRow" name="DATASET" scope="request"> <tr> <logic:iterate id="eachCol" name="eachRow"> <td> <%= eachCol %> </td> </logic:iterate> </tr> </logic:iterate> </table> </body> </html>

32

What is a framework?
Provides "the invisible underpinnings" that complex J2EE applications need to survive. It provides some basic structure to apply to your coding efforts; makes available pre-built Java code and classes to speed development; offers tools and an overall environment that encourages code and object reuse; and delivers tools to ease the testing and deployment of finished applications.

33

What is MVC
The Model View Controller design pattern is a technique used to separate Business logic/state (the Model) from User Interface (the View) and program progression/flow (the Control). This pattern is very useful when it comes to modern web development: The majority of modern, high usage websites are dynamically driven. People well skilled at presentation (HTML writers) seldom know how to develop back-end solutions and visa versa. Separating business rules from presentation is good no matter what environment you develop in be it web or desktop.
34

What is MVC (cont)


The View The view is how data is represented to the user. For instance the view in a web application may be an HTML page, an image or other media The Model The model represents the data in the system. For instance, a model might represent the properties associated with a users profile The Controller The controller is the glue between the model and the view. It is responsible for controlling the flow of the program as well as processing updates from the model to the view and visa versa
35

MVC Examples
Shopping Cart Catalog Cart Order Billing Shipping Thanks

Insurance Application Login Contact Health History Hang Glide Benefits Thanks

Tax Return (dynamic workflow) Check if married filing jointly


36

Fundamental Architecture
Old Multi-form Web Architecture
HTML Browser URL Request Initial Get
Label: Label: Label: Label: Label: Label:

Thanks!

Next Get Post Get

Next Post Get

Complete Post

Validation Fail

Success

A
Server
Move to next

Java

Uses a sendRedirect()

Multi-Form Chaining
37

Fundamental Arch. Pros & Cons


Pros:
Easy

to understand and develop

Cons: Hard to maintain, static navigation, lots of potentially faulty communication. Each page has to know who its next and previous page are. Each page has hard coded navigational elements built into each one. Coordinating a transaction across all pages is tricky. Most of the state is preserved in the Session. If Page A is a login page, the pages B, C and D have to redirect to the login page, again adding more code and complexity to each page.
38

MVC Architecture
URL Request Initial Get
Label: Label: Label: Label:

Next Post

Next Post Network

Controller
A.jsp View A.java Model Bean B.jsp View B.java Model Bean

Model preserves the state (posted form fields) and holds validation logic, if invalid, the controller is alerted to redisplay the same View/JSP. The Controller knows who is next in the chain, not the JSP
39

MVC Model View Controller


The Traffic Cop centralized, dynamic navigation Pros: Promotes modularity Abstraction Removes error-prone navigational presentation-related logic from each page. Allows for a dynamic navigational system. Answers to questions on page 1 have an impact on what pages appear next. Assumes a wizard-like multipage transaction. Easier to change the work-flow of the application. Cons: Slightly harder to code Harder to comprehend
40

MVC and Java


Called Model 2 architecture A hybrid approach for serving dynamic content Combines the use of both servlets and JSP

It takes advantage of the predominant strengths of both technologies


JSPs generate the presentation layer Servlets perform process-intensive tasks responsible for retrieving any objects or beans from the servlet extracts the dynamic content from the servlet Inserts into static templates In charge of request processing creation of beans and objects used by the JSP deciding which JSP page to forward the request to

JSP is the view


The servlet acts as the controller

The more complex the application, the more beneficial MVC architecture

41

Struts Introduction
An open source framework subproject of Jakarta which is sponsored by the Apache Software Foundation. Based on MVC (or Model 2, servlet-centric) In order to take advantage of the MVC design pattern in your applications a considerable framework must be in place. Struts does, however, takes the grunt work out of developing an MVC based web app. The Struts framework provides a plethora of canned objects which can facilitate fundamental aspects of MVC, while allowing you to extend further as need arises Struts allows you to configure a lot of the default framework objects through xml configuration files.
42

The Struts Framework


The struts framework has three main components The struts taglibs

A set of stand alone tag libraries, separate from the Jakarta taglibs, that can interact with the Struts controller servlet

Struts

Actions, ActionForms, Action Servlet

The controller servlet which sends requests to mapped Action classes that you code. The linking of a particular action is based upon a mapping in the struts-config.xml file

XML

utilities
Classes that support XML parsing, internationalization and other functionality such as JavaBeans population via the Java reflection APIs.

43

Struts Pros & Cons


Pros:

Provides the ability to design using the MVC pattern Provides a pre-built set of code for the MVC architecture Shelters your web designer from learning how to program Provides support for I18N Has some cool and productive taglibs Popular, and seems to be well supported by the email list Requires more work up front Overrides the majority of HTML tags with JSP custom tags has an impact on HTML tools like Dreamweaver and has a learning curve associated with it. Can be overkill if you dont have lots of multi-form transactions and/or the need for I18N Debugging can be really, really difficult.

Cons:

44

Struts Architecture
Action Form Class aForm.java
2. Call setThis(), setThat() 3. validate() 4. return ActionErrors

Posting JSP Form a.jsp

1. Post to a.do

Action Servlet
0. Load on startup

5. call execute() 6. return an ActionForward

Action Class aAction.java

7. Forward to the JSP ActionMapping

b.jsp
8. Next page B is displayed to user
45

Strutsconfig.xml

Struts Alternatives

WebWork (http://www.opensymphony.com/webwork/) Cocoon (http://xml.apache.org/cocoon/) Barracuda (http://www.barracudamvc.org/) Kona (http://www.aki.com/kona/) Tapestry (http://jakarta.apache.org/proposals/tapestry/) Velocity (http://jakarta.apache.org/velocity/) More (http://www.waferproject.org/index.html)

46

Payware Frameworks
Any J2EE vendors portal Cysive Cymbio AltoWeb New Visual Studio-like tools have simple frameworks for page navigation and component management: BEA Workshop, IBM WSAD, M7 (http://www.m7.com/)

47

What is CVS?
CVS - Concurrent Versions System
The dominant open-source version control system Lets developers access the latest code from anywhere there's an Internet connection. Unreserved check-out model avoids artificial conflicts Client tools are available on most platforms

48

What is XDoclet?
XDoclet is a code generation engine
Add more significance to code by adding meta data (attributes) to java sources. Uses special JavaDoc tags Parses your source files and generates many artifacts such as XML descriptors and/or source code Currently can only be used as part of the build process utilizing Apache Ant Originated as a tool for creating EJBs, it has evolved into a general-purpose code generation engine

49

What is FOP?
FOP - Formatting Objects Processor
print formatter driven by XSL formatting objects (XSL-FO) Output formats currently supported include PDF, PCL, PS, SVG, AWT, MIF and TXT The primary output target is PDF

50

What is cool in Commons?


Pools - A generic object pool interface that can be used to easily provide interchangeable pooling implementations. Logging Simple, lightweight wrapper to allow transparent switching between log4j, JDK 1.4 or any other logging framework. Validator Validation framework used by Struts but could just as easily be utilized by a Swing client
51

Commons Logging Sample


Foo.java: import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; ... private static Log LOG = LogFactory.getLog(Foo.class); ... someMethod() { LOG.info("This is an info"); LOG.error("This is an error"); }
52

What is Tomcat?
Tomcat is a J2EE servlet container that is used as the official Reference Implementation for the Java Servlet and JavaServer Pages technologies
Tomcat

5.x is the upcoming major release, and will implement the Servlet 2.4 and JSP 2.0 specifications The current Tomcat 4.1.x has a new servlet container (called Catalina) and implements the Servlet 2.3 and JSP 1.2 specifications. Part of the Java Web Services Developer Pack
http://java.sun.com/webservices/webservicespack.html
53

What is JBoss?
JBoss is the leading open source EJB container.
Built on a very modular JMX (Mbeans) microkernel Bundles available with either Jetty or Tomcat web containers. Supports the full EJB 2.0 specification. Easy setup and deployment for EJB jars, WARs, and EARs Ships with Tomcat or Jetty as the servlet container

Free
54

Dont Suck

Design Patterns
Most common and/or useful design patterns:
MVC Faade Command Singleton Factory DAO

Why is this important? Common nomenclature allows for better communication amongst development team members.
55

Faade
To provide a unified interface to a set of interfaces in a subsystem. Facade defines a higher-level interface that makes the subsystem easier to use. In the case of J2EE, we often will see a session EJB serve as the gate-way to numerous POJOs that provide business logic and perhaps entity beans to be used for persistence.

56

Command

Lets an application framework make requests of application-specific objects, without the framework knowing the objects' exact type or the applicationspecific behavior they implement

57

From: http://bellsouthpwp.net/t/o/tooger/commando_project/Commando_overview.html

Singleton

The Singleton pattern ensures that only one instance of a class is created. Great for JVM-wide caches.
public class TheOne { private static TheOne theone = null; private String aInstance1 = "The one and only"; private StringBuffer aInstance2 = new StringBuffer("The one and only"); private TheOne() { // Private means only I can new myself } public static TheOne getInstance() { if (theone == null) { theone = new TheOne(); } return theone; } public StringBuffer getSomething() { return aInstance2; } }

58

Factory
public interface IHello { public String sayHello(); } public class HelloFactory { public static final int LANG_EN = 0; public static final int LANG_JP = 1; private HelloFactory() {} public static IHello createHello(int type) { if (type == 0) return new EnglishHello(); else return new NihonHello(); } }

public class EnglishHello implements IHello { public String sayHello() { return "Hello"; } } public class NihonHello implements IHello { public String sayHello() { return "Konnichi wa"; } }

Hides the complexity of instantiation (new)

59

DAO/DTO
Data Access Object - basically implements Select, Insert, Update and Delete SQL commands via JDBC. http://java.sun.com/blueprints/patterns/DAO.html

60

Middle-tier Architect
Skills for the middle-tier architect:
EJB

or not EJB: remote access, security, distributed transactions SOAP RMI Sockets HTTP Asynchronous via JMS Persistence (OJB, EJB Entity, JDO, DAO) Design Patterns that reduce network noise. Dont build chatty or fatty software.
61

Middle-Tier Design Considerations


Requirements of the middle-tier components:
Remotely

accessible by multiple UIs Portable across vendor containers Is it possible that components of the middle-tier need to float to the client machine? Does it require declarative security and transaction support? Or distributed component transaction controls? Can the task/transaction happen asynchronously? What about database inquiry performance? What about database concurrency?
62

The N-Tier Fallacy


Must the business logic be remotely accessible?

Client

Java Web Server

Java Application Server

Database Server

63

Enter the POJO


import java.rmi.*; import javax.ejb.*; import java.util.*; public class LoanEJB implements SessionBean { double loanAmount; double apr; int numYears; public double getPayment() { System.out.println("in getPayment()"); double tmp = apr/12.0; return loanAmount*(tmp)/(1.0-Math.pow(1+tmp,-numYears*12.0)); } public LoanEJB() { System.out.println("in LoanEJB()"); } public void ejbCreate(double a, double i, int y) { System.out.println("in ejbCreate()"); loanAmount = a; apr = i; numYears = y; } public public public public } void void void void ejbRemove() { } ejbActivate() { } ejbPassivate() { } setSessionContext(SessionContext sc) { } public class LoanCalc { double loanAmount; double apr; int numYears; public double getPayment() { System.out.println("in getPayment()"); double tmp = apr/12.0; return loanAmount*(tmp)/(1.0-Math.pow(1+tmp,-numYears*12.0)); }

Plain Old Java Object

OR
}

public LoanCalc(double a, double i, int y) { System.out.println("in ejbCreate()"); loanAmount = a; apr = i; numYears = y; }

EJB Session Bean + 4 interfaces + 2 XML files = 7 items to manage


64

POJO Ease of Use


Plain Old Java Object
import java.util.*; import javax.naming.*; import javax.rmi.PortableRemoteObject; public class LoanClient { public static void main(String[] args) { try { String url = "sssw://localhost"; Hashtable h = new Hashtable(); h.put(Context.INITIAL_CONTEXT_FACTORY, "com.sssw.rt.jndi.AgInitCtxFactory"); h.put(Context.PROVIDER_URL, url); Context initial = new InitialContext(h); Object objref = initial.lookup("Loan"); LoanHome home = (LoanHome) PortableRemoteObject.narrow(objref, LoanHome.class); Loan loan = home.create(100000.00,.07,5); double payment = loan.getPayment(); System.out.println("Payment: " + payment); loan.remove(); } catch (Exception e) { e.printStackTrace(); } } }

OR

public class LoadClient { public static void main(String[] args) { LoanCalc myLoan = new LoanCalc(100000.00,.07,5); double payment = loan.getPayment(); System.out.println("Payment: " + payment); } }

65

Protocol Considerations
When to SOAP?
Interoperability

with non-Java-based software You need to move easily through firewalls

When to EJB (RMI/IIOP)?


Java

on the client and server You need declarative and distributed transaction capabilities You need declarative security

When to RMI?
No

declarative, distributed transactions and security No load-balancing, session fail-over


66

Basic EJB Architecture


* Send a serializable data object or collection (aka DTO data transfer object) from a session faade or send XML between the tiers

Web/Servlet Container IE WAP


JSP
Servlet
Struts Action

EJB Container

Session Bean

Entity Bean Entity Bean

*
VB
SOAP Service

Java Client

Entity Bean

67

What about Web Services?


For Distributed Computing!
Client/Browser COM/DCOM CORBA/IIOP RMI Proprietary OR Win2K Unix or Netware Web/AppServer Web Services Legacy AS/400 OS/390 Vax Another Web/App Server .NET Java Perl ColdFusion

Mobile Phone PDA


68

A challenge for Corp. IT


Screen Scrape Message Queue Sockets Download File Transaction File

Screen Scrape Screen Scrape

Transaction File

Download File

CICS Gateway

Sockets RPC APPC ORB

ORB

Message Message Queue Transaction File CICS Gateway

Message Queue

Transaction File

Screen Scrape

Message

Download File

APPC

RPC

69

Simple Object Access Protocol


Call a method

myApplication

Remote Object

Return response

70

SOAP Request
POST /BraveAxis/HelloWorldService.jws HTTP/1.0 Content-Length: 472 Host: localhost Content-Type: text/xml; charset=utf-8 SOAPAction: "" <?xml version="1.0" encoding="UTF-8"?> <SOAP-ENV:Envelope SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:SOAPENC="http://schemas.xmlsoap.org/soap/encoding/"> <SOAP-ENV:Body> <sayHelloTo> <arg0 xsi:type="xsd:string">Burr</arg0> </sayHelloTo> </SOAP-ENV:Body> </SOAP-ENV:Envelope>
71

SOAP Response
HTTP/1.1 200 OK Content-Type: text/xml; charset=utf-8 Content-Length: 479 Date: Thu, 20 Feb 2003 20:39:17 GMT Server: Apache Tomcat/4.0.1 (HTTP/1.1 Connector) <?xml version="1.0" encoding="UTF-8"?> <SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <SOAP-ENV:Body> <sayHelloToResponse SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"> <sayHelloToResult xsi:type="xsd:string"> Hello Burr, How are you doing? </sayHelloToResult> </sayHelloToResponse> </SOAP-ENV:Body> </SOAP-ENV:Envelope>
72

To Async Or Not To Async


When to JMS?
When the load is huge and the back-end resource is over-taxed. Dont make users/requestors wait. A message can be sent back as a response or the requestor can poll for a result. When the requestor doesnt really care when a task is done as long as it is done eventually.

73

Recommended Reading

Effective Java - Joshua Bloch Refactoring - Martin Fowler Mastering EJB - Ed Roman Design Patterns GoF (Gamma, Helm, Johnson, Vlissides) Ant Developer's Handbook - Gibson, et al Programming Jakarta Struts - Cavaness

74

Conclusion
In conclusion:
Learn from others, avoid costly mistakes While some new technical thingy seems cool, dont gold-plate the project. Prefer leading edge to the bleeding edge Test the performance and maintainability of your software. Build time into the schedule for prototyping, testing and code reviews. Maintain a handle on your technology footprint Invest in your development environment e.g. plan CVS repositories, branching strategies, IDEs, build scripts, developer application server instances etc. - this will pay significant dividends. Maintain hygiene in your production environment - don't use it as a test lab. Keep things like XML, Struts, JDBC, EJB, JDO, Servlets etc. at the far edges of your application don't let them penetrate your business logic (tier-spillage).

75

You might also like