This document was uploaded by user and they confirmed that they have the permission to share
it. If you are author or own the copyright of this book, please report to us by using this DMCA
report form. Report DMCA
Overview
Download & View Agile Java Dev With Spring Hibernate Eclipse as PDF for free.
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!
2
Some Material Taken From My Recent Book
Agile Java Development
With Spring, Hibernate and Eclipse Forewords by Scott W. Ambler and Rod Johnson
available on amazon.com
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 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)
3
Book Related Talks
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
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.
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
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 9
Agile Processes Requirements change. Design evolves. Documents are seldom current.
Some Stats by The Standish Group (standishgroup.com)
The Solution
CHAOS Ten – Success Factors source: standishgroup.com
In 2001, seventeen software pundits came together to unify their methodologies under one umbrella; they jointly defined the term, Agile! Read story at: martinfowler.com/articles/agileStory.html 12
AgileManifesto.org
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… 14
“Agility” - All About Smaller Chunks (Shorter/Frequent Cycles) Release 2
Release 1 Iteration 0
Iteration 1
...Iteration n
Iteration 0
Iteration 1
...Iteration n
...
Incrementally Build Software - Highest Priority Features First!
software
software
software
software
software
software
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
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
17
Presentation Outline
Introduction to Agile Processes
Agile Java Development
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
18
Agile Modeling “...your goal is to build a shared understanding, it isn’t to write detailed documentation.” - Scott W. Ambler
Quick Poll
Have you ever been on a project where documentation was kept up-to-date through end of project?
Communic ation, simplicity, feedback, courage and humility. Practices
Principles
Core Practices: Active Stakeholder Participation Model with Others Apply the Right Artifact(s) Iterate to Another Artifact Prove I t with Code Use the Simplest Tools Model in Small Incr ements Single Source Information Collective Ownership Create Several Models in Parallel Create Simple Content Depict Models Simply Displa y Models Publicly
Core Principles: Model with a Purpose Maximize Stakeholder Investment Travel Light Multiple Models Rapid Feedback Assum e Simplicity Embrace Cha nge Incremental Change Quality Work Software Is Your Primary Goal Enabli ng the Next Effort Is Your Secondary Goal
Supplementary Practices: Apply Modeling Standards Apply Patterns Gently Discar d Temporary Models Formalize Contract Models Update Only When It Hurts Really Good Ideas: Refactoring Test-First Design
Supplementary Principles: Content Is More I mportant Than Representation Open and Honest Comm unicat ion
Definition Of Word “Model” (freedictionary.com)
"A preliminary work or construction that serves as a plan from which a final product is to be made ... used in testing or perfecting Word “model” used ato final describe diagrams and other artifacts, product." in this presentation.
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 Requirements Architecture
Requirements modeling
Usage models Domain models UI models
Architecture modeling
Free-form diagrams Change cases
Let’s apply this to a sample application , next ...
23
Initiating A New Software Application Project
24
Problem Statement
Our employees currently submit their weekly hours worked using a paper-based timesheet system that is manually intensive and errorprone. We require an automated solution for submitting employee hours worked, in the form of an electronic timesheet, approving them, and paying for the time worked. In addition, we would like to have automatic notifications of timesheet status changes and a weekly reminder to submit and
25
Project Kickoff Meeting
26
Choices Of Release (High) Level Models
Release Level Models
scope table, glossary, etc.
domain model
user stories
UI prototype & flow map
architecture
Iteration Level Models
acceptance tests
CRC cards
application flow map
UML diagrams
database model
Model with a purpose -- shared understanding!
27
Sample Scope Table
Scope Include
Functionality 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 understanding: what's in and what's out 28
Domain Model
Shared understanding: business concepts > key domain objects 29
User Stories Or Use Cases 3 Use Case: Login Author Anil Hemrajani Description This process allows User to log into the System
Success/B asic Flow 1. The System displaysthe Login panel prompting User forlogin detailsas specified in the 2. Usercompletes allrequired fields and performs a Submit action. Failure/A lternative Flow InvalidUser ID and/or Password- The systemnotifies FM traderwith the message“InvalidUser ID and/or Password ”. The systemdisplaysthe Login panelto User with the contents of all fields empty.
Use Case - Casual, Brief or Fully Dressed
Shared understanding: features required of software
30
User Interface (UI) Prototype
Shared understanding: functionality, look-and-feel, etc.
31
UI Flow Map (Storyboard)
Shared understanding: user interface navigation/flow
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 understanding: common terminology
34
Choices Of Iteration Level (Detailed) Models
Release Level Models
scope table, glossary, etc.
domain model
user stories
UI prototype & flow map
architecture
Iteration Level Models
acceptance tests
CRC cards
application flow map
UML diagrams
database model
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.
Employees can only view and edit their own timesheets. 36
Exploring Classes Using CRC Cards First, let's reflect on what we know, domain model, UI and architecture
Second, let's explore classes on CRC cards using both as Cinput l a s s N a m emodels (N o un) R e s p o n s ib ilit ie s ( o b lig a t io n s o f t h is c la s s , s u c h a s b u s in e s s m e t h o d s , e x c e p t io n h a n d lin g , s e c u r it y m e t h o d s , a t t r ib u t e s / v a r ia b le s ) .
Timesheet List screen
C o lla b o r a t o r s ( o t h e r c la s s e s r e q u ir e d t o p r o v id e a c o m p le t e s o lu t io n t o a h ig h - le v e l r e q u ir e m e n t )
T im e s h e e t L is tC o n tr o lle r C o n t r o lle r ( in M V C ) fo r d is p la y in g a lis t o f t im e s h e e t s .
T im e s h e e t M a n a g e r
T im e s h e e t M a n a g e r free-form architecture
F e t c h e s t im e s h e e t ( s ) fr o m d a ta b a s e
T im e s h e e t
S a v e s t im e s h e e t t o d a t a b a s e T im e s h e e t K n o w s o f p e r io d e n d in g d a t e domain model
K n o w s o f t im e K n o w s o f d e p a rtm e n t c o d e 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
Timesheet List
timesheetlist
TimeSheetListController
TimesheetManager
Tables Impacted Timesheet
Enter Hours
enterhours
EnterHoursController
TimesheetManager
Timesheet Department
38
UML Class and Package Diagrams
39
Focus Is On Working Software vs. Comprehensive Documentation Conceptual Models
problem statement
scope table
domain model user stories UI prototypes
glossary
Model in Small Increments
architecture
Depict Models Simply
Physical Models
acceptance tests
application flow map
Implementation
Data Base
CRC cards
database model
UML diagrams
Discard temporary models Prove it with code - agilemodeling.com
THE FINAL AND LASTING ARTIFACTS!
UI prototype Code Base & flow map
40
Shifting Some Upfront Design to Refactoring
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
42
Agile Draw - Elegantly Simple Modeling Technique
High-Level Architecture UI Flow Map
Visit AgileDraw.org Conceptual Class Diagram 43
Presentation Outline
Introduction to Agile Processes Agile Modeling
Agile Java Development
Agile Development
Environment Setup: Directory Structure, JDK, Ant and JUnit
How many of you are using Ant, JUnit, Maven, Cruise Control, etc?
46
Personal Opinion: Early Environment Setup Is Essential Involves more than people expect/plan Cycle 0 Get minimal environment setup (scripts, directory, version control, etc.) Get end-to-end demo working Helps team
47
Directory Structure, Naming Conventions, Version Control, etc.
Erich Gamma (Gang of Four, Design Patterns) Kent Beck (author of Extreme Programming and Test Driven Development)
Simple framework – various assert methods
assertEquals
assertFalse
public class SimpleTest extends junit.framework.TestCase { int value1 = 2, value2 = 3, expectedResult = 5;
assertNotNull
assertNotSame
assertNull
assertSame
assertTrue }
public static void main(String args[]) { junit.textui.TestRunner.run(suite()); } public static Test suite() { return new TestSuite(SimpleTest.class); } public void testAddSuccess() { assertTrue(value1 + value2 == expectedResult); }
50
JUnit GUI Based Testing
Console Runner
Eclipse Plug-in 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
More unit test code
More actual code
More unit test code
More actual code
Several benefits to this approach:
Minimal code written to satisfy requirements (nothing more, nothing less!)
If code passes the unit tests, it is done!
Can help design classes better (from a client/interface perspective)
Refactor with confidence
52
Presentation Outline
Introduction to Agile Processes Agile Modeling
Agile Java Development
Agile Development
Environment JUnit
Setup: Directory Structure, JDK, Ant and
Using Hibernate For Persistent Objects
The Spring Framework
The Eclipse Phenomenon!
Logging, Debugging, Monitoring, and Profiling
Beyond The Basics
53
Agile Java Development: Using Hibernate For Persistent Objects
Quick Poll
What persistence solution does your project use (e.g. JDBC, ORM, entity bean)?
55
Where Hibernate Fits Into Our Architecture
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…
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 58
From Domain Model To A (Denormalized) Physical Data Model
59
Working With Hibernate - Simple Example Using Department
Department.hbm.xml – Mapping file for our Department table <property name="name" column="name"/>
•
Department.java – Bean file with two variables: String departmentCode; String name; // Setter and getter methods 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();
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
IoC Container And Dependency Injection Pattern Normal Way public class A { B myB = new B(); C myC = new C(); }
Using IoC Class C
Class B IOC Container
Class A
public class A { public setB(B myB) 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… 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)
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)
Management of sessionfactory and session (no close calls) Declarative transaction management in lightweight containers Easier testing (pluggable Sessionfactory via XML file) Less lines of code – focus on business logic!
81
Spring ORM Module: Support for Hibernate (cont’d) Session session = HibernateUtil.getSessionFactory().getCurrentSession(); session.beginTransaction(); try { session.saveOrUpdate(timesheet); session.getTransaction().commit(); } catch (HibernateException e) { session.getTransaction().rollback(); throw e; }
getHibernateTemplate().saveOrUpdate(timesheet);
File DepartmentManager.java EmployeeManager.java TimesheetManager.java TOTAL
JEE support Sub-projects (Acegi, BeanDoc, Spring IDE, etc.) 83
Presentation Outline
Introduction to Agile Processes Agile Modeling
Agile Java Development
Agile Development
Environment JUnit
Setup: Directory Structure, JDK, Ant and
Using Hibernate For Persistent The Spring Framework
Objects
The Eclipse Phenomenon!
Logging, Debugging, Monitoring, and Profiling
Beyond The Basics
84
Agile Java Development: The Eclipse Phenomenon!
Quick Poll
Which IDE do you use?
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 plugins 87
Personal Opinion: The Java versus Microsoft Thing
First exciting IDE Huge community - Plug-ins galore (thousand+) Ward Cunningham and Erich Gamma Battle of IDEs has only now begun! 88
How Eclipse Can Help With Our Application
89
Eclipse Basic Concepts •
Workspace (directory of
• • • • •
Workbench Perspectives Editors and Views Project Wizards (hundreds)
•
projects)
Plug-ins (galore!)
sample workspace
90
Eclipse Plug-in: Java Development Tools (JDT)Java
Browsing
JUnit
Java Compile Errors/Warnings
Ant Assist 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.)
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… 93
Using Hibernate For Persistent The Spring Framework The Eclipse Phenomenon!
Objects
Logging, Debugging, Monitoring, and Profiling
Beyond The Basics
98
Agile Java Development: Logging, Debugging, Monitoring, and Profiling
Quick Poll
Do you use a GUI debugger? Or, a logging framework? Or, use println statements?
100
Logging Basics and Frameworks Types Logging Frameworks 1.Audit log Alternative to println statements 2.Tracing Key benefit - Output control (destination, format, 3.Error Most popular - Apache Log4J and JDK Logging reportingJakarta Commons Logging -- bridge to frameworks Pros No human interventio n (automated) Great for head-less servers Cons Performance hit Can clutter
log le
import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; public class CommonsLoggingTest { private static Log log = LogFactory.getLog(CommonsLoggingTest.class);
}
public static void main(String[] args) { log.fatal("This is a FATAL message."); log.error("This is an ERROR message."); log.warn("This is a WARN message."); log.info("This is an INFO message."); log.debug("This is a DEBUG message."); }
101
Headaches of Finding and Fixing Bugs!
102
Debugging Java Code With Eclipse Debug perspectives
“consolidated debugging”
and views Breakpoints Step through code Variable inspection Hotswap Remote debugging
103
Debugging Web User Interfaces Using Mozilla Firefox JavaScript debugger
Web Developer
Tamper Data
104
Java Monitoring and Profiling Spring MBean Exporter
Monitoring
JSE 5.0 includes
id="exporter” class= "org.springframework.jmx.export.MBeanExporter"> <property name="beans"> <map> and <entry key="Time Expression:name=timex-stats" value-ref="timexJmxBean" />
Class loading garbage collection Management of MBeans and JDK logging level, etc …
Profiling
Memory usage and leaks CPU utilization Trace objects and methods Determine
105
Presentation Outline
Introduction to Agile Agile Processes Agile Modeling Agile Development Environment JUnit
Java Development
Setup: Directory Structure, JDK, Ant and
Using Hibernate For Persistent Objects The Spring Framework The Eclipse Phenomenon! Logging, Debugging, Monitoring, and Profiling Beyond The Basics
106
Beyond The Basics
Security, Reliability and Scalability Considerations