You are on page 1of 119

Agile Java Development

With Spring, Hibernate and Eclipse

Anil Hemrajani
anil@visualpatterns.com

© Visual Patterns, Inc.


About This Presentation
• Not a tutorial on any one technology!

• Road map for building enterprise-class Java applications …


using various “hot” agile methods and simpler Java technologies

Requirements > Design > Code > Monitor

• Downloadable code - Sample “time sheet” application used here

• Note: Working knowledge of Java is expected for this presentation!

© Visual Patterns, Inc. 2


Some Material Taken From My Recent Book

Agile Java Development


With Spring, Hibernate and Eclipse

Forewords by Scott W. Ambler and Rod Johnson

1. Introduction to Agile Java Development


2. The Sample Application: An Online Timesheet System
3. XP and AMDD-Based Architecture and Design Modeling
4. Environment Setup: JDK, Ant, and JUnit
5. Using Hibernate For Persistent Objects
6. Overview of the Spring Framework
7. The Spring Web MVC Framework
available on amazon.com 8. The Eclipse Phenomenon
9. Logging, Debugging, Monitoring and Profiling
10. Beyond the Basics
11. What Next?
12. Parting Thoughts

Appendices (with lots of goodies)

© Visual Patterns, Inc. 3


Book Related Talks

© Visual Patterns, Inc. 4


My Background (details at VisualPatterns.com)
• 20 years of experience in the IT
 Working with Java Technology since late 1995 as a developer, entrepreneur,
author, and trainer.
 Helped several U.S. based Fortune 100 companies (some smaller organizations)
 Published a book and 30 articles
 Presented at conferences and seminars around the world
 Awards:
 "Outstanding Contribution to the Growth of the Java Community"
 "Best Java Client" for BackOnline (a Java-based online backup product)
 Nominated for a Computerworld-Smithsonian award by Scott McNealy

• Founder of:
 Isavix Corporation – successful IT solutions company (now InScope Solutions)
 Isavix Community (now DeveloperHub.com) - award-winning online developer
community (grew to over 100,000 registered members)

• These days: Consultant/Author; details at VisualPatterns.com

© Visual Patterns, Inc. 5


Practical Stuff, Not Fluff!
• Recently completed project for U.S. Fortune 50 company

• Application
 Financial application process billions of $ every week

 Clustered application (99.9% uptime required)

 Technologies: Spring, Hibernate, JUnit, Ant, Eclipse, etc.

© Visual Patterns, Inc. 6


Agenda
1. Introduction to Agile Java Development
2. Agile Processes
3. Agile Modeling
4. Agile Development
 Environment Setup: Directory Structure, JDK, Ant and JUnit
 Using Hibernate For Persistent Objects
 The Spring Framework
 The Eclipse Phenomenon!
 Logging, Debugging, Monitoring, and Profiling
5. Beyond The Basics

© Visual Patterns, Inc. 7


Introduction to Agile Java Development

Assume
Assumesimplicity.
simplicity.
Travel
Travellight.
light.

- -Agile
AgileModeling
Modelingprinciples:
principles:agilemodeling.com
agilemodeling.com

© Visual Patterns, Inc.


What Is Agile Java Development? It Could Include…
1. Agile Software Processes
 Iterative Development
 Use an Agile method - Scrum, XP, etc.

2. Agile Architecture/Design Modeling


 Incremental design with “good enough” models
 Use an agile method - Agile Model Driven Development (AMDD)

3. Agile Java Design/Development


 Simple design and coding!
 Test-driven development (TDD)
 Efficient frameworks and tools (Ant, JUnit, Hibernate, Spring, Eclipse…)
 Plain Old Java Objects (POJOs), whenever possible

© Visual Patterns, Inc. 9


Agile Processes

Requirements
Requirementschange.
change.
Design
Designevolves.
evolves.
Documents
Documentsare
areseldom
seldomcurrent.
current.

© Visual Patterns, Inc.


Some Stats by The Standish Group (standishgroup.com)

© Visual Patterns, Inc.


The Solution

CHAOS Ten – Success Factors


source: standishgroup.com

InIn2001,
2001,seventeen
seventeensoftware
softwarepundits
punditscame
cametogether
togethertotounify
unify
their
theirmethodologies
methodologiesunder
underone
oneumbrella;
umbrella;they
theyjointly
jointlydefined
defined
the term, Agile!
the term, Agile!

Read
Readstory at:martinfowler.com/articles/agileStory.html
storyat: martinfowler.com/articles/agileStory.html

© Visual Patterns, Inc. 12


AgileManifesto.org

© Visual Patterns, Inc. 13


Term “Agile” Incorporates a Wide Range of Methods
• AM - Agile Modeling
• ASD - Adaptive Software Development
• AUP - Agile Unified Process
• Crystal
• FDD - Feature Driven Development
• DSDM - Dynamic Systems Development Method
• Lean Software Development
• Scrum
• Xbreed
• XP - eXtreme Programming

• Others…

© Visual Patterns, Inc. 14


“Agility” - All About Smaller Chunks (Shorter/Frequent Cycles)

Release 1 Release 2

Iteration
0
Iteration
1
... Iteration
n
Iteration
0
Iteration
1
... Iteration
n
...

Incrementally
IncrementallyBuild
BuildSoftware
Software--Highest
HighestPriority
PriorityFeatures
FeaturesFirst!
First!

software
software
software
software software
software software
software software
software software
software

© Visual Patterns, Inc.


Agile Method: Scrum
• Simple process for product/project management
• Product Backlog - List of known features/changes for product
• Sprint - 1-month iterations (develop highest priority items)
• Meetings
 Sprint Planning Meeting – Done at beginning of each sprint
(after planning, features moved from product backlog to sprint backlog)
 Daily scrum meeting (short: 15 minutes)
 Sprint review meeting

© Visual Patterns, Inc. 16


Agile Method: Extreme Programming (XP)
• Shorter and Frequent Cycles (smaller chunks!)
 Release - Quarterly Cycles (set a theme)
 Iteration - Weekly Cycles (e.g. aim for last day of week)

 10-minute builds
 Continuous integration (multiple times per day; manual or automatic)
 Incremental Design and Planning (defer investment till needed)
 Development in small increments using Test-First development

• Communications - Sit Together, Informative Workspace, on-


site customer

• Flow - sustainable pace versus rigid phases; velocity, continuous


integration

• Others… visit extremeprogramming.org


© Visual Patterns, Inc. 17
Presentation Outline
 Introduction to Agile Java Development
 Agile Processes
• Agile Modeling
• Agile Development
 Environment Setup: Directory Structure, JDK, Ant and JUnit
 Using Hibernate For Persistent Objects
 The Spring Framework
 The Eclipse Phenomenon!
 Logging, Debugging, Monitoring, and Profiling
• Beyond The Basics

© Visual Patterns, Inc. 18


Agile Modeling

“...your
“...yourgoal
goalisistotobuild
buildaashared
sharedunderstanding,
understanding,ititisn’t
isn’ttoto
write
writedetailed
detaileddocumentation.”
documentation.”

- -Scott
ScottW.
W.Ambler
Ambler

© Visual Patterns, Inc.


Quick Poll

Have you ever been on a


project where documentation
was kept up-to-date through
end of project?

© Visual Patterns, Inc. 20


Agile Modeling Values, Practices & Principles (agilemodeling.com)
Values

Communication, simplicity, feedback, courage and humility.

Practices Principles

Core Practices: Core Principles:


Active Stakeholder Participation Model with a Purpose
Model with Others Maximize Stakeholder Investment
Apply the Right Artifact(s) Travel Light
Iterate to Another Artifact Multiple Models
Prove It with Code Rapid Feedback
Use the Simplest Tools Assume Simplicity
Model in Small Increments Embrace Change
Single Source Information Incremental Change
Collective Ownership Quality Work
Create Several Models in Parallel Software Is Your Primary Goal
Create Simple Content Enabling the Next Effort Is Your
Depict Models Simply Secondary Goal
Display Models Publicly
Supplementary Principles:
Supplementary Practices: Content Is More Important Than
Apply Modeling Standards Representation
Apply Patterns Gently Open and Honest Communication

Discard Temporary Models


Formalize Contract Models
Update Only When It Hurts
Really Good Ideas:
Refactoring
Test-First Design

© Visual Patterns, Inc.


Definition Of Word “Model” (freedictionary.com)

"A
"A preliminary
preliminary work
work or or construction
construction
that
that serves
serves as
as aa plan
plan from
from which
which aa
final
final product
product isis to
to be
be made
made ...
... used
used
in
in testing
testing or
or perfecting
perfecting aa final
final
product."
product."
Word “model” used to describe diagrams
and other artifacts, in this presentation.

© Visual Patterns, Inc.


Agile Model Driven Development (AMDD)
• Subset of Agile Modeling (agilemodeling.com)
• Agile version of Model Driven Development (MDD)
• Instead of extensive models, “barely good enough”

• Initial modeling activity


1. Requirements
2. Architecture

• Requirements modeling
 Usage models
 Domain models
 UI models
Let’s
Let’s apply
apply this
this
• Architecture modeling to
to aa sample
sample
 Free-form diagrams
application,
application,
 Change cases
next
next ...
...
© Visual Patterns, Inc. 23
Initiating A New Software Application Project

© Visual Patterns, Inc. 24


Problem Statement

Our
Ouremployees
employeescurrently
currentlysubmit
submittheir
theirweekly
weekly
hours
hoursworked
workedusing
usingaapaper-based
paper-basedtimesheet
timesheet
system
systemthat
thatisismanually
manuallyintensive
intensiveand
anderror-
error-
prone.
prone.

We
Werequire
requirean
anautomated
automatedsolution
solutionfor
for
submitting
submittingemployee
employeehours
hoursworked,
worked,ininthe
theform
form
of
ofan
anelectronic
electronictimesheet,
timesheet,approving
approvingthem,
them,
and
andpaying
payingfor
forthe
thetime
timeworked.
worked.

In
Inaddition,
addition,we
wewould
wouldlike
liketo
tohave
haveautomatic
automatic
notifications
notificationsof
oftimesheet
timesheetstatus
statuschanges
changesand
andaa
weekly
weeklyreminder
reminderto tosubmit
submitand
andapprove
approve
employee
employeetimesheets.
timesheets.

© Visual Patterns, Inc. 25


Project Kickoff Meeting

© Visual Patterns, Inc. 26


Choices Of Release (High) Level Models

Release
scope
scopetable,
table, UI
UIprototype
prototype
Level domain
domainmodel
model user
userstories
stories architecture
architecture
Models glossary,
glossary,etc.
etc. &&flow
flowmap
map

Iteration
acceptance
acceptance application
application UML
UML database
database
Level CRC
CRCcards
cards
Models tests
tests flow
flowmap
map diagrams
diagrams model
model

Model with a purpose -- shared understanding!

© Visual Patterns, Inc. 27


Sample Scope Table

Scope Functionality
Include Time Expression will provide the capability to enter, approve, and
pay for hours worked by employees.
Defer Time Expression will not calculate deductions from paychecks, such
as federal/state taxes and medical expenses.
Defer Time Expression will not track vacation or sick leave.

Shared
Sharedunderstanding:
understanding:what's
what'sininand
andwhat's
what'sout
out

© Visual Patterns, Inc. 28


Domain Model

Shared
Sharedunderstanding:
understanding:business
businessconcepts
concepts>>key
keydomain
domainobjects
objects

© Visual Patterns, Inc. 29


User Stories Or Use Cases

Use Case: Login


Author
Anil Hemrajani

Description
This process allows User to log into the System

Actors/Interfaces
XP Style User Story Card • FM Trader
• The System

Trigger
Userperforms a Login acti
on

Preconditions
• N/A

Success/BasicFlow
1. The System displaysthe Loginpanel rop mpting User forlogindetails
as speci
fi
ed in
the
2. Usercom pletes all lds and performs a Submit action.
required fie

Failure/Alternative Flow
InvalidUserID and/ orPassword- The systemnoti
fiesFM trader
with themessage“ Invalid
User
ID and/ or Password
”. The systemdisplaystheLoginpaneltoUserwith thecontentsofallfield
s
empty.

Use Case - Casual, Brief or Fully Dressed

Shared
Sharedunderstanding:
understanding:features
featuresrequired
requiredofofsoftware
software
© Visual Patterns, Inc. 30
User Interface (UI) Prototype

Shared
Sharedunderstanding:
understanding:functionality,
functionality,look-and-feel,
look-and-feel,etc.
etc.
© Visual Patterns, Inc. 31
UI Flow Map (Storyboard)

Shared
Sharedunderstanding:
understanding:user
userinterface
interfacenavigation/flow
navigation/flow
© Visual Patterns, Inc. 32
High-Level Architecture Diagram

Web HTTP
Controller Model JDBC
Spring Business objects,
RDBMS
Browser DispatcherServlet Hibernate beans (Oracle)

View Spring
Scheduler
JSP/HTML

Objects managed by Spring IoC Container

BEA WebLogic Server

Shared
Sharedunderstanding:
understanding:technologies,
technologies,scalability,
scalability,security,
security,reliability
reliability
© Visual Patterns, Inc. 33
Glossary - List Of Common Business/Technical Terms
• Accounting
The accounting department/staff.
• Approved
Status of a timesheet when a Manager approves a previously
submitted timesheet.
• Employee
A person who works on an hourly basis and reports to a
manager.
• Paid
Status of a timesheet when the accounting department has
issued a check.
• Etc…

Shared
Sharedunderstanding:
understanding:common
commonterminology
terminology
© Visual Patterns, Inc. 34
Choices Of Iteration Level (Detailed) Models

Release

scope
   
scopetable,
table, domain
UI
UIprototype
prototype
Level
glossary, domainmodel
model user
userstories
stories architecture
architecture
Models glossary,etc.
etc. &&flow
flowmap
map

Iteration
acceptance
acceptance application
application UML
UML database
database
Level CRC
CRCcards
cards
Models tests
tests flow
flowmap
map diagrams
diagrams model
model

© Visual Patterns, Inc. 35


Iteration Level Details - Acceptance Tests & Active Stakeholders
• Sign In
 The employee id can be up to 6 characters. The password
must be between 8 and 10 characters.
 Only valid users can sign in.
• Timesheet List
 Only a user's personal timesheets can be accessed.
• Enter Hours
 Hours must contain numeric data.
 Daily hours cannot exceed 16 hours. Weekly hours cannot
exceed 96 hours.
 Hours must be billed to a department.
 Hours can be entered as two decimal places.
 Employees can only view and edit their own timesheets.

© Visual Patterns, Inc. 36


Exploring Classes Using CRC Cards
First, let's reflect on what we know, Second, let's explore classes on CRC
domain model, UI and architecture cards using both as input models
Class Name (Noun)

Responsibilities (obligations Collaborators (other


of this class , such as business classes required to
methods, exception handling, provide a complete
security methods, solution to a high -level
attributes/variables). requirement)

Timesheet List screen

TimesheetManager

Fetches timesheet(s) from Timesheet


free-form architecture
database
Saves timesheet to database

Timesheet

Knows of period ending date

domain model Knows of time


Knows of department code

© Visual Patterns, Inc. 37


Application Flow Map (Home Grown Artifact)

• Complementary to class diagrams and CRC cards


• Can be extended using CRUD columns

Story Tag View Controller Class Collaborators Tables


Impacted
Timesheet timesheetlist TimeSheetListController TimesheetManager Timesheet
List
Enter enterhours EnterHoursController TimesheetManager Timesheet
Hours
Department

© Visual Patterns, Inc. 38


UML Class and Package Diagrams

© Visual Patterns, Inc. 39


Focus Is On Working Software vs. Comprehensive Documentation
Conceptual Models
problem
statement
scope


scope
domain table
domainmodel
model table
user
userstories
stories

UIUI glossary
prototypes glossary • •Model in Small Increments
prototypes architecture
architecture
Model in Small Increments
• •Depict Models Simply
Physical Models
Depict Models Simply
• •Discard temporary models
acceptance
acceptance
database
database Discard temporary models


tests model
tests CRC model
CRCcards
cards
• •Prove it with code
Prove it with code
application UML
application UML
flow map diagrams
flow map diagrams
- -agilemodeling.com
agilemodeling.com
Implementation THE FINAL AND LASTING ARTIFACTS!

Data UI prototype
DataBase
Base Code
UI Base
prototype
Code Base
& flow map
& flow map

© Visual Patterns, Inc. 40


Shifting Some Upfront Design to Refactoring

© Visual Patterns, Inc. 41


Shifting Some Upfront Design To Refactoring (Continuous Design)
• Refactoring is not a new concept; the term is relatively new

• refactoring.com
 “Refactoring is a disciplined technique for restructuring an existing body of
code, altering its internal structure without changing its external behavior.”
- Martin Fowler

 Over 100 refactoring techniques; for example:


 Extract superclass
 Extract interface
 Move class
 Move method

© Visual Patterns, Inc. 42


Agile Draw - Elegantly Simple Modeling Technique

High-Level Architecture

UI Flow Map

Visit
Visit AgileDraw.org
AgileDraw.org
Conceptual Class Diagram

© Visual Patterns, Inc. 43


Presentation Outline
 Introduction to Agile Java Development
 Agile Processes
 Agile Modeling
• Agile Development
 Environment Setup: Directory Structure, JDK, Ant and JUnit
 Using Hibernate For Persistent Objects
 The Spring Framework
 The Eclipse Phenomenon!
 Logging, Debugging, Monitoring, and Profiling
• Beyond The Basics

© Visual Patterns, Inc. 44


Agile Java Development:
Environment Setup (Directory Structure, JDK, Ant, and JUnit)

© Visual Patterns, Inc.


Quick Poll

How many of you are using


Ant, JUnit, Maven, Cruise
Control, etc?

© Visual Patterns, Inc. 46


Personal Opinion:
Early Environment
Setup Is Essential

 Involves more than people expect/plan


 Involves more than people expect/plan
 Cycle 0
 Cycle 0
• Get minimal environment setup (scripts,
• Get minimal environment setup (scripts,
directory, version control, etc.)
directory, version control, etc.)
• Get end-to-end demo working
• Get end-to-end demo working
 Helps team
 Helps team

© Visual Patterns, Inc. 47


Directory Structure, Naming Conventions, Version Control, etc.

➔controller/TimesheetListController.java
➔model/Timesheet.java
➔model/TimesheetManager.java
➔test/TimesheetListControllerTest.java
➔test/TimesheetManagerTest.java
➔view/timesheetlist.jsp

© Visual Patterns, Inc. 48


Ant (ant.apache.org)

• Ant task types


<ftp server="mirrors.kernel.org"
 Compile tasks (that is, javac) <ftp server="mirrors.kernel.org"
action="get"
action="get"
 Deployment tasks remotedir="/gnu/chess"
remotedir="/gnu/chess"
userid="anonymous"
 File tasks such as copy, delete, userid="anonymous"
password="guest@guest.com"
move, and others. password="guest@guest.com"
verbose="yes"
verbose="yes"
 Property tasks for setting internal binary="yes">
binary="yes">
variables <fileset file="README.gnuchess"/>
<fileset file="README.gnuchess"/>
</ftp>
 Audit/coverage tasks </ftp>
 Database tasks
 Documentation tasks
 Execution tasks
 Mail tasks
<mail tolist="friend@somehost.com"
 Preprocess tasks <mail tolist="friend@somehost.com"
subject="Hello!"
subject="Hello!"
 Property tasks from="me@myhost.com"
from="me@myhost.com"
mailhost="myhost.com"
 Remote tasks mailhost="myhost.com"
user="myuserid"
user="myuserid"
 Miscellaneous tasks (e.g. echo) password="mypassword"/>
password="mypassword"/>

© Visual Patterns, Inc. 49


JUnit (junit.org)

• Originally written by
 Erich Gamma (Gang of Four, Design Patterns)
 Kent Beck (author of Extreme Programming and Test Driven Development)

• Simple framework – various assert methods


 assertEquals
public class SimpleTest extends junit.framework.TestCase
 assertFalse {public class SimpleTest extends junit.framework.TestCase
{ int value1 = 2, value2 = 3, expectedResult = 5;
int value1 = 2, value2 = 3, expectedResult = 5;
 assertNotNull public static void main(String args[])
{public static void main(String args[])
 assertNotSame { junit.textui.TestRunner.run(suite());
} junit.textui.TestRunner.run(suite());
 assertNull }
public static Test suite()
 assertSame {public static Test suite()
{ return new TestSuite(SimpleTest.class);
} return new TestSuite(SimpleTest.class);
 assertTrue }
public void testAddSuccess()
{public void testAddSuccess()
{ assertTrue(value1 + value2 == expectedResult);
} assertTrue(value1 + value2 == expectedResult);
} }
}

© Visual Patterns, Inc. 50


JUnit GUI Based Testing

Console Runner

Eclipse Plug-in

© Visual Patterns, Inc. 51


Agile Method: Test Driven Development (TDD) w/ JUnit
• A term coined by Kent Beck
• Also, a XP practice (test-first)
• “Red - Green - Refactor”

Write Test First Code, Compile, Test


Write unit test code Write some actual code
• Several benefits to this approach:
 Minimal code written to satisfy requirements (nothing more, nothing less!)


More unit test code
If code passes the unit tests, it is done!
Can help design classes better (from a client/interface perspective)
More actual code
 Refactor with confidence

More unit test code More actual code

© Visual Patterns, Inc. 52


Presentation Outline
 Introduction to Agile Java Development
 Agile Processes
 Agile Modeling
• Agile Development
 Environment Setup: Directory Structure, JDK, Ant and JUnit
 Using Hibernate For Persistent Objects
 The Spring Framework
 The Eclipse Phenomenon!
 Logging, Debugging, Monitoring, and Profiling
• Beyond The Basics

© Visual Patterns, Inc. 53


Agile Java Development:
Using Hibernate For Persistent Objects

© Visual Patterns, Inc.


Quick Poll

What persistence solution


does your project use (e.g.
JDBC, ORM, entity bean)?

© Visual Patterns, Inc. 55


Where Hibernate Fits Into Our Architecture

© Visual Patterns, Inc. 56


An Overview of Object-Relational Mapping (ORM)
• ORM - Java object to database table/record mapping
 Java = objects
 database = relational

• Relationships
 unidirectional and bidirectional
 relations in a relational database are bidirectional by definition
• Cardinality (OO term is multiciplicity)
 One-to-one
 one-to-many
 many-to-one
 and many-to-many
• Object Identity
• Cascade

• Others…
© Visual Patterns, Inc. 57
Hibernate Basics
• Dialect
(DB2, Microsoft SQL Server, MySQL, Oracle, PostgreSQL, SAP DB,
Sybase, TimesTen…)

• SessionFactory, Session, and Transaction

• Work with Database Records (as Java Objects)

• Object States - persistent, detached, and transient

• Data Types – more than you'll likely need!

• Hibernate Query Language (HQL) – powerful SQL-like language

© Visual Patterns, Inc. 58


From Domain Model To A (Denormalized) Physical Data Model

© Visual Patterns, Inc. 59


Working With Hibernate - Simple Example Using Department
1. hibernate.cfg.xml – Hibernate configuration file (DB
configuration)
<property name="connection.url">
jdbc:hsqldb:hsql://localhost:9005/timex</property>
<mapping resource="Department.hbm.xml" />

2. Department.hbm.xml – Mapping file for our Department table


<class name="com.visualpatterns.timex.model.Department"
table="Department">
<id name="departmentCode" column="departmentCode">
<property name="name" column="name"/>

3. Department.java – Bean file with two variables:


String departmentCode;
String name;
// Setter and getter methods

1. HibernateTest.java – Simple test program (on next slide)


© Visual Patterns, Inc. 60
HibernateTest.java
SessionFactory sessionFactory = new Configuration().configure()
.buildSessionFactory();
Session session = sessionFactory.getCurrentSession();

Transaction tx = session.beginTransaction();
Department department = (Department)
session.get(Department.class, "IT");
System.out.println("Name for IT = " + department.getName());
...

List departmentList = session.createQuery("from Department").list();


for (int i = 0; i < departmentList.size(); i++)
{
department = (Department) departmentList.get(i);
System.out.println("Row " + (i + 1) + "> " +
department.getName()
+ " (" + department.getDepartmentCode() + ")");
}

...
sessionFactory.close();

© Visual Patterns, Inc. 61


Other Hibernate Features
• Saving (save, merge, saveOrUpdate)
session.saveOrUpdate(timesheet)

• Deleting records
 session.delete(Object), or
 session.createQuery("DELETE from Timesheet")

• Queries using Criteria interface (more OO and typesafe)


 List timesheetList =
session.createCriteria(Timesheet.class)
.add(Restrictions.eq("employeeId", employeeId))
.list();

 Related classes: Restrictions, Order, Junction, Distinct, and others

• Locking Objects (Concurrency Control)

• Lots More Hibernate (associtions, annotations, filters, interceptors,


scrollable iterations, native SQL, transaction management, etc.)
© Visual Patterns, Inc. 62
Presentation Outline
 Introduction to Agile Java Development
 Agile Processes
 Agile Modeling
• Agile Development
 Environment Setup: Directory Structure, JDK, Ant and JUnit
 Using Hibernate For Persistent Objects
 The Spring Framework
 The Eclipse Phenomenon!
 Logging, Debugging, Monitoring, and Profiling
• Beyond The Basics

© Visual Patterns, Inc. 63


Agile Java Development:
The Spring Framework

© Visual Patterns, Inc.


Spring Modules

© Visual Patterns, Inc. 65


Spring Java Packaging (org.springframework.)

© Visual Patterns, Inc. 66


Quick Poll

Are you familiar with


Inversion of Control (IoC)?

© Visual Patterns, Inc.


IoC Container And Dependency Injection Pattern
Normal Way Using IoC
public class A
{ Class B Class C
B myB = new B(); public class A
IOC
C myC = new C(); Container {
} public setB(B myB)
Class A public setC(C myC)

• Dependency Injection Styles


 Two Supported By Spring:
 Setter/getter based
 Constructor based
 Fowler suggests a 3rd, interface injection,
http://www.martinfowler.com/articles/injection.html

• Spring IoC Concepts: Beans, BeanFactory, ApplicationContext…

© Visual Patterns, Inc. 68


Benefits of Using Spring
• Light weight Inversion of Control (IoC) container

• Excellent support for POJOs (e.g. declarative transaction


management)

• Modular – not an all-or-nothing approach

• Testing – dependency injection and POJOs makes for easier


testing

• Many others
 No Singletons
 Builds on top of existing technologies (e.g. JEE, Hibernate)
 Robust MVC web framework
 Consistent database exception hierarchy (e.g. wrap SQLException)
© Visual Patterns, Inc. 69
Where Spring Framework Fits Into Our Architecture

Optional
Hibernate
integration

© Visual Patterns, Inc. 70


Quick Poll

Which web framework do you


use?

© Visual Patterns, Inc. 71


Spring Web MVC
• Easier testing – mock classes, dependency injection

• Bind directly to business objects

• Clear separation of roles – validators, adaptable controllers, command


(form) object, etc.

• Simple but powerful tag libraries

• Support for various view technologies and web frameworks (e.g. Struts,
webwork, tapestry, JSF)

© Visual Patterns, Inc. 72


Spring MVC Java Concepts

1. Controller

2. ModelAndView

3. Command (Form
Backing) Object

4. Validator

5. Spring Tag
Library
(spring:bind)

© Visual Patterns, Inc. 73


Spring MVC Configuration
<servlet>
<servlet>
<servlet-name>timex</servlet-name>
<servlet-name>timex</servlet-name>
<servlet-class>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
</servlet-class>
<load-on-startup>1</load-on-startup>
<load-on-startup>1</load-on-startup>
</servlet>
</servlet>
<servlet-mapping>
<servlet-mapping>
<servlet-name>timex</servlet-name>
<servlet-name>timex</servlet-name>
<url-pattern>*.htm</url-pattern>
<url-pattern>*.htm</url-pattern>
</servlet-mapping>
</servlet-mapping>
web.xml timex-servlet.xml
<bean id="urlMapAuthenticate”
<bean id="urlMapAuthenticate”
class=
class=
"org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
"org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<prop key="/enterhours.htm">enterHoursController</prop>
<prop key="/enterhours.htm">enterHoursController</prop>
...
...
<bean id="viewResolver"
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver"
>class="org.springframework.web.servlet.view.InternalResourceViewResolver"
> <property name="viewClass">
<property name="viewClass">
<value>org.springframework.web.servlet.view.JstlView</value>
<value>org.springframework.web.servlet.view.JstlView</value>
</property>
</property>
<property name="prefix">
<property name="prefix">
<value>/WEB-INF/jsp/</value>
<value>/WEB-INF/jsp/</value>
</property>
</property>
<property name="suffix">
<property name="suffix">
<value>.jsp</value>
<value>.jsp</value>
</property>
</property>
</bean> © Visual Patterns, Inc. 74
</bean>
Sample End-To-End Flow Using Spring and Hibernate

© Visual Patterns, Inc. 75


Timesheet List: A No-Form Controller Example

public class TimesheetListController


implements Controller
{
...
public ModelAndView handleRequest(
HttpServletRequest request,
HttpServletResponse response)

mockHttpServletRequest =
mockHttpServletRequest =
new MockHttpServletRequest("GET",
new MockHttpServletRequest("GET",
"/timesheetlist.htm");
"/timesheetlist.htm");
ModelAndView modelAndView =
ModelAndView modelAndView =
timesheetListController.handleRequest(
timesheetListController.handleRequest(
mockHttpServletRequest, null);
mockHttpServletRequest, null);
assertNotNull(modelAndView);
assertNotNull(modelAndView);
assertNotNull(modelAndView.getModel());
assertNotNull(modelAndView.getModel());

© Visual Patterns, Inc. 76


Enter Hours: A Form Screen

1. EnterHoursController.java
2. EnterHoursValidator.java
3. enterhours.jsp

public class EnterHoursController extends SimpleFormController


public class EnterHoursController extends SimpleFormController

© Visual Patterns, Inc. 77


View/JSP Code – Spring and JSTL Tag Libraries

<spring:bind
<spring:bind path="command.employeeId">
path="command.employeeId">
<input
<input name='<c:out value="${status.expression}"/>'
name='<c:out value="${status.expression}"/>'
value='<c:out
value='<c:out value="${status.value}"/>'
value="${status.value}"/>'
type="text"
type="text" size="6"
size="6" maxlength="6">
maxlength="6">
</spring:bind>
</spring:bind>

Special (Spring) variable named status


• status.value
• status.expression
• status.error
• status.errorMessage
• status.errorMessages
• status.displayValue

© Visual Patterns, Inc. 78


Sign In (Authentication) - Spring HandlerInterceptor

public class HttpRequestInterceptor extends HandlerInterceptorAdapter


{public class HttpRequestInterceptor extends HandlerInterceptorAdapter
{ public boolean preHandle(HttpServletRequest request,
public boolean preHandle(HttpServletRequest request,
HttpServletResponse response,
HttpServletResponse
Object handler) response,
{ Object handler)
{ if (!signedIn)
{if (!signedIn)
{ response.sendRedirect(this.signInPage);
response.sendRedirect(this.signInPage);
return false;
} return false;
}

© Visual Patterns, Inc. 79


Other Spring Web Stuff
• View with no controllers (e.g. only JSP files)
<bean id="urlFilenameController"
class="org.springframework.web.servlet.mvc.UrlFilenameViewController"/>
<prop key="/help.htm">urlFilenameController</prop>

• Spring 2.0 – new tag libraries


 form:form - org.springframework.web.servlet.tags.form.FormTag
 form:input- org.springframework.web.servlet.tags.form.InputTag
 form:password - org.springframework.web.servlet.tags.form.PasswordInputTag
 form:hidden - org.springframework.web.servlet.tags.form.HiddenInputTag
 form:select - org.springframework.web.servlet.tags.form.SelectTag
 form:option - org.springframework.web.servlet.tags.form.OptionTag
 form:radiobutton - org.springframework.web.servlet.tags.form.RadioButtonTag
 Others…

• Other
 Web Flow – gaining a lot of momentum! Wizard-like features.
 Portlet API – based on JSR-168 Portlet Specification (jcp.org).
© Visual Patterns, Inc. 80
Spring ORM Module: Support for Hibernate
• Management of sessionfactory and session (no close calls)

• Declarative transaction management in light-weight containers

• Easier testing (pluggable Sessionfactory via XML file)

• Less lines of code – focus on business logic!

© Visual Patterns, Inc. 81


Spring ORM Module: Support for Hibernate (cont’d)
Session session =
Session session =
HibernateUtil.getSessionFactory().getCurrentSession();
HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
session.beginTransaction();
try
{try
{ session.saveOrUpdate(timesheet);
session.saveOrUpdate(timesheet);
session.getTransaction().commit();
} session.getTransaction().commit();
}
catch (HibernateException e)
{ catch (HibernateException e)
{ session.getTransaction().rollback();
session.getTransaction().rollback();
throw e;
} throw e;
}

getHibernateTemplate().saveOrUpdate(timesheet);
getHibernateTemplate().saveOrUpdate(timesheet);

File Programmatic Declarative


DepartmentManager.java 39 22
EmployeeManager.java 66 36
TimesheetManager.java 166 87
TOTAL 271 145

Less lines of code


© Visual Patterns, Inc. 82
More Spring…
• Scheduling Jobs (with Quartz or JDK timers)
<bean id="reminderEmailJobDetail" class=
<bean id="reminderEmailJobDetail" class=
"org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
"org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
<property name="targetObject" ref="reminderEmail" />
<propertyname="targetMethod"
<property name="targetObject"value="sendMail"
ref="reminderEmail"
/> />
<property name="targetMethod" value="sendMail" />
</bean>
</bean>
<bean id="reminderEmailJobTrigger"
<bean id="reminderEmailJobTrigger"
class="org.springframework.scheduling.quartz.CronTriggerBean">
class="org.springframework.scheduling.quartz.CronTriggerBean">
<property name="jobDetail" ref="reminderEmailJobDetail" />
<propertyname="cronExpression"
<property name="jobDetail" ref="reminderEmailJobDetail"
value="0 0 14 ? * 6" /> />
<property name="cronExpression" value="0 0 14 ? * 6" />
</bean>
</bean>

• Spring email support

• Much more
 JEE support
 Sub-projects (Acegi, BeanDoc, Spring IDE, etc.)

© Visual Patterns, Inc. 83


Presentation Outline
 Introduction to Agile Java Development
 Agile Processes
 Agile Modeling
• Agile Development
 Environment Setup: Directory Structure, JDK, Ant and JUnit
 Using Hibernate For Persistent Objects
 The Spring Framework
 The Eclipse Phenomenon!
 Logging, Debugging, Monitoring, and Profiling
• Beyond The Basics

© Visual Patterns, Inc. 84


Agile Java Development:
The Eclipse Phenomenon!

© Visual Patterns, Inc.


Quick Poll

Which IDE do you use?

© Visual Patterns, Inc. 86


The Eclipse Foundation, Platform and Projects
• Foundation
 Originally developed by Object Technology International (OTI), purchased
by IBM ($40 million) and donated it to open source!
 Recruited various corporations; from eclipse.org: Industry leaders Borland, IBM,
MERANT, QNX Software Systems, Rational Software, Red Hat, SuSE, TogetherSoft
and Webgain formed the initial eclipse.org Board of Stewards in November 2001. By
the end of 2003, this initial consortium had grown to over 80 members.
 My view: Eclipse foundation is similar to Apache foundation for GUI tools

• Platform objectives
 robust platform for highly integrated dev tools
 enable view and/or editing of any content type
 attract a large community of developers to develop plug-ins

• Projects
Application Development, editors, modeling, performance, testing, reporting,
and many more
© Visual Patterns, Inc. 87
Personal Opinion:
The Java versus
Microsoft Thing

 First exciting IDE


 First exciting IDE
 Huge community - Plug-ins galore (thousand+)
 Huge community - Plug-ins galore (thousand+)
 Ward Cunningham and Erich Gamma
 Ward Cunningham and Erich Gamma
 Battle of IDEs has only now begun!
 Battle of IDEs has only now begun!

© Visual Patterns, Inc. 88


How Eclipse Can Help With Our Application

© Visual Patterns, Inc. 89


Eclipse Basic Concepts

1. Workspace (directory of projects)


2. Workbench
3. Perspectives
4. Editors and Views
5. Project
6. Wizards (hundreds)

7. Plug-ins (galore!)

sample workspace

© Visual Patterns, Inc. 90


Eclipse Plug-in: Java Development Tools (JDT) Java Browsing

JUnit

Ant Assist
Java Compile Errors/Warnings © Visual Patterns, Inc. 91
JDT: Other Notable Features
• Compile during save (within the blink of an eye)

• Formatting options

• Scrapbook

• TODO lists

• Others
 Powerful search
 Code refactoring (some based on Fowler's refactoring.com)
 Export feature (create zip files, etc.)

© Visual Patterns, Inc. 92


Eclipse Plug-In: Web Tools Platform (WTP; eclipse.org)
• Tools for developing JEE Web applications

• Editors
 Source - HTML, JavaScript, CSS, JSP, SQL, XML, DTD, XSD, and WSDL
 Graphical - XSD and WSDL

• Database access and query tools and models

• Web service wizards

• Other JEE features (EJB, JSP, Servlet…)

• Much more…

© Visual Patterns, Inc. 93


WTP: Notable Features
Servers
JSP Assist

Database
Web Services
© Visual Patterns, Inc. 94
CVS (Eclipse Team Sharing)

© Visual Patterns, Inc. 95


Hibernate and Spring Plug-Ins

Hibernate

Spring IDE
© Visual Patterns, Inc. 96
Startup Time Comparison To IntelliJ and NetBeans

IntellIJ - 1 minute, 5 seconds!

NetBeans - 42 seconds.

Eclipse
Eclipsewith
withJDT,
JDT,WTP,
WTP,Hibernate,
Hibernate,Eclipse...
Eclipse...19
19seconds!
seconds!

© Visual Patterns, Inc. 97


Presentation Outline
 Introduction to Agile Java Development
 Agile Processes
 Agile Modeling
• Agile Development
 Environment Setup: Directory Structure, JDK, Ant and JUnit
 Using Hibernate For Persistent Objects
 The Spring Framework
 The Eclipse Phenomenon!
 Logging, Debugging, Monitoring, and Profiling
• Beyond The Basics

© Visual Patterns, Inc. 98


Agile Java Development:
Logging, Debugging, Monitoring, and Profiling

© Visual Patterns, Inc.


Quick Poll

Do you use a GUI debugger?


Or, a logging framework?
Or, use println statements?

© Visual Patterns, Inc. 100


Logging Basics and Frameworks
• Types Logging Frameworks
1.Audit log • Alternative to println statements
2.Tracing • Key benefit - Output control (destination, format, log level)
3.Error reporting • Most popular - Apache Log4J and JDK Logging
• Jakarta Commons Logging -- bridge to frameworks
• Pros
• No human import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
intervention
(automated) public class CommonsLoggingTest
• Great for {
private static Log log =
head-less LogFactory.getLog(CommonsLoggingTest.class);
servers public static void main(String[] args)
{
log.fatal("This is a FATAL message.");
• Cons log.error("This is an ERROR message.");
• Performance log.warn("This is a WARN message.");
log.info("This is an INFO message.");
hit log.debug("This is a DEBUG message.");
}
• Can clutter }
code
© Visual Patterns, Inc. 101
Headaches of Finding and Fixing Bugs!

© Visual Patterns, Inc. 102


Debugging Java Code With Eclipse
• Debug
perspectives “consolidated debugging”
and views

• Breakpoints

• Step through
code

• Variable
inspection

• Hotswap

• Remote
debugging

© Visual Patterns, Inc. 103


Debugging Web User Interfaces Using Mozilla Firefox
JavaScript debugger

Web Developer

Tamper Data © Visual Patterns, Inc. 104


Java Monitoring and Profiling
Spring MBean Exporter
• Monitoring <bean id="timexJmxBean” class=
<bean id="timexJmxBean” class=
"com.visualpatterns.timex.util.TimexJmxBean" />
 JSE 5.0 includes "com.visualpatterns.timex.util.TimexJmxBean" />
JConsole <bean id="exporter” class=
<bean id="exporter” class=
"org.springframework.jmx.export.MBeanExporter">
 Memory issues "org.springframework.jmx.export.MBeanExporter">
<property name="beans">
<property
<map> name="beans">
 Class loading and <map>
<entry key="Time Expression:name=timex-stats"
<entry key="Time Expression:name=timex-stats"
garbage collection value-ref="timexJmxBean" />
value-ref="timexJmxBean" />
 Management of
MBeans and JDK
logging level, etc …
• Profiling
 Memory usage and
leaks
 CPU utilization
 Trace objects and
methods
 Determine performance
bottlenecks
© Visual Patterns, Inc. 105
Presentation Outline
 Introduction to Agile Java Development
 Agile Processes
 Agile Modeling
 Agile Development
 Environment Setup: Directory Structure, JDK, Ant and JUnit
 Using Hibernate For Persistent Objects
 The Spring Framework
 The Eclipse Phenomenon!
 Logging, Debugging, Monitoring, and Profiling
• Beyond The Basics

© Visual Patterns, Inc. 106


Beyond The Basics

© Visual Patterns, Inc.


Custom Tag Libraries

<timex:periodcheck
<timex:periodcheck
checkDate="${command.periodEndingDate}">
checkDate="${command.periodEndingDate}">
<input
<input name="save"
name="save" type="submit"
type="submit" value="Save">
value="Save">
</timex:periodcheck>
</timex:periodcheck>

public class PayPeriodCheckTag extends TagSupport


{
public int doStartTag()
throws JspException
{
boolean includeText = ; // do something
if (includeText)
return TagSupport.EVAL_BODY_INCLUDE;

return TagSupport.SKIP_BODY;
}

© Visual Patterns, Inc. 108


Security, Reliability and Scalability Considerations

© Visual Patterns, Inc. 109


Application Security Considerations
• Authentication (user and application levels)
• Authorization (roles, groups, etc.)
• Encryption (wire protocol, configuration files)

User-level
authentication
& authorization

Wire protocol
(HTTP/S) Application-level
authentication

© Visual Patterns, Inc. 110


Other Considerations
• Exception Handling
1. Checked exceptions (e.g. IOException) – required catch or throw
2. Unchecked exceptions (e.g. NullPointerException) - no catch/throw needed
3. Errors (e.g. OutOfMemoryError)

• Clustering (serialize, no static variables, simplicity…)

• Multi-threading (JDK 1.5 concurrent API)

• Rich Internet Applications (RIA)


 AJaX -
 Google Web Toolkit (GWT) - http://code.google.com/webtoolkit/
 Direct Web Remoting (DWR) - http://getahead.ltd.uk/dwr/
 Adobe Flex
 Java Swing and Web Start

© Visual Patterns, Inc. 111


Cool Concept For Smaller Apps - Entire System In A WAR File!
• Code (source, binary)
• Relational database (e.g. HSQLDB)
• Job Scheduling
• More…

© Visual Patterns, Inc. 112


Wrap Up!

© Visual Patterns, Inc.


Presentation Outline

Introduction to Agile Java Development


Agile Processes
Agile Modeling
Agile Development
Environment Setup: Directory Structure, JDK, Ant and JUnit
Using Hibernate For Persistent Objects
The Spring Framework
The Eclipse Phenomenon!
Logging, Debugging, Monitoring, and Profiling
Beyond The Basics

© Visual Patterns, Inc.


Constant Learning – Be a “Generalizing Specialist”

“A
“A generalizing
generalizing
specialist
specialist isis
someone
someone with with aa
good
good grasp
grasp ofof
how
how everything
everything
fits
fits together.”
together.”

--agilemodeling.com
agilemodeling.com

© Visual Patterns, Inc. 115


Most Important… Don’t Forget To Have Fun! :-)

RON
RON STEVE
STEVE RAJ
RAJ SUSAN
SUSAN
© Visual Patterns, Inc. 116
VisualPatterns.com - Downloadable Application & Presentation

visualpatterns.com/resources.jsp
visualpatterns.com/resources.jsp
••Spring
Spring
••Hibernate
Hibernate
••Ant
Ant
••JUnit
JUnit
••DisplayTag
DisplayTag
••HSQLDB
HSQLDB

Model
Web Controller Model
Web HTTP
HTTP
Controller Business JDBC RDBMS
Spring Business JDBC RDBMS
Browser Spring objects,
Browser DispatcherServlet
DispatcherServlet
objects, (Oracle)
(Oracle)
Hibernate beans
Hibernate beans

View Spring
View Spring
Scheduler
JSP/HTML Scheduler
JSP/HTML
Objects managed by Spring IoC Container
Objects managed by Spring IoC Container

BEA WebLogic Server


BEA WebLogic Server
© Visual Patterns, Inc.
VisualPatterns.com - Other Stuff

Planning Coding
• User stories are written. • The customer is always available.
• Release planning creates the • Code must be written to agreed
schedule. standards.
• Make frequent small releases. • Code the unit test first.
• The Proje ct Velocity is measured. • All production code is pair programmed.
• The project is divided into iterations. • Only one pair integrates code at a time.
• Iteration planning starts each • Integrate often.
iteration. • Use collective code ownership.
• Move people around. • Leave optimization till last.
• A stand -up meeting starts each day. • No overtime.
• Fix XP when it breaks.
Designing Testing
• Simplicity. • All code must have unit tests.
• Choose a system meta phor. • All code must pass all unit tests before it
• Use CRC cards for design sessions. can be released.
• Create spike solutions to reduce risk. • When a bug is found tests are created.
• No functionality is added early. • Acceptance tests are run often and the
• Refactor whenever and wherever score is published.
possible.

Comics
Cheat Sheets

R&D Concepts
© Visual Patterns, Inc. 118
THE END!
• agilemodeling.com
• agiledata.org Stay
Stayinintouch!
touch!
• agilemanifesto.org
• extremeprogramming.org Anil@VisualPatterns.com
Anil@VisualPatterns.com
• hibernate.org
• springframework.org
• eclipse.org

• code.google.com/webtoolkit/
• getahead.ltd.uk/dwr/

• VisualPatterns.com (links, comics, code, cheat sheets…)

© Visual Patterns, Inc. 119

You might also like