Professional Documents
Culture Documents
Road map for building enterprise-class Java applications using various hot agile methods and simpler Java technologies
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)
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)
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)
Financial application process billions of $ every week Clustered application (99.9% uptime required)
Technologies: Spring, Hibernate, JUnit, Ant, Eclipse, etc.
Agenda
1. 2. 3. 4.
Agile Development
Environment Setup: Directory Structure, JDK, Ant and JUnit Using Hibernate For Persistent Objects The Spring Framework
Incremental design with good enough models Use an agile method - Agile Model Driven Development (AMDD)
Simple design and coding! Test-driven development (TDD) Efficient frameworks and tools (Ant, JUnit, Hibernate, Spring, Eclipse) Plain Old Java Objects (POJOs), whenever possible
Agile Processes
The Solution
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
Visual Patterns, Inc.
12
AgileManifesto.org
13
AM - Agile Modeling
ASD - Adaptive Software Development AUP - Agile Unified Process
Crystal
FDD - Feature Driven Development DSDM - Dynamic Systems Development Method
Scrum
Xbreed
XP - eXtreme Programming
Others
Visual Patterns, Inc.
14
Release 1
Iteration 0 Iteration 1
Release 2
...
Iteration n
Iteration 0
Iteration 1
...
Iteration n
...
software
software
software
software
software
software
Simple process for product/project management Product Backlog - List of known features/changes for product Sprint - 1-month iterations (develop highest priority items)
Meetings
16
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
17
Presentation Outline
Environment Setup: Directory Structure, JDK, Ant and JUnit Using Hibernate For Persistent Objects The Spring Framework
18
Agile Modeling
...your goal is to build a shared understanding, it isnt 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?
20
Practices
Core Practices: Active Stakeholder Participat ion Model with Others Apply the Right Artifact(s) Iterate to Another Artifact Prove It with Code Use the Simplest Tools Model in Small Incr ements Single Source Informatio n Colle ctive Ownership Create Several Models in Paral lel Create Sim ple Content Depict Models Simply Displa y Models Public ly Supplementary Practices: Apply Modeling Standards Apply Patterns Gently Discar d Temporary Models Formali ze Contract Models Update Only When It Hurts Really Good Ideas: Refactoring Test-Fir st Design
Principles
Core Princip les: Model with a Purpose Maximize Stakeholder Investment Travel Light Mult iple Models Rapid Feedback Assume Simplicity Embrace Change Incremental Change Quality Work Software Is Your Primary Goal Enabling the Next Effort Is Your Secondary Goal Supplementary Principles: Content Is More Important Than Representation Open and Honest Communication
"A preliminary work or construction that serves as a plan from which a final product is to be made ... used in testing or perfecting a final product."
Word model used to describe diagrams and other artifacts, in this presentation.
Subset of Agile Modeling (agilemodeling.com) Agile version of Model Driven Development (MDD) Instead of extensive models, barely good enough Initial modeling activity
1. 2.
Requirements Architecture
Requirements modeling
Architecture modeling
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 approve employee timesheets.
25
26
domain model
user stories
architecture
acceptance tests
CRC cards
UML diagrams
database model
27
Scope Functionality Include Time Expression will provide the capability to enter, approve, and pay for hours worked by employees. Defer Defer Time Expression will not calculate deductions from paychecks, such as federal/state taxes and medical expenses. Time Expression will not track vacation or sick leave.
28
Domain Model
29
Actors/Interfaces
FM Trader The System
Success/Basic Flow 1. The System displays the Login panel p rompting User for login details as specified in the 2. User completes all required fields and performs a Submit action. Failure/Alternative Fl ow
Invalid User ID and/or Password - The system notifies FM trader with the message Invalid User ID and/or Password . The system displays the Login panel to User with the contents of all fields empty.
30
31
32
Web Browser
HTTP
Controller
Spring
Model
Business objects,
Hibernate beans
JDBC
RDBMS
(Oracle)
DispatcherServlet
View
JSP/HTML
Spring Scheduler
33
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
Visual Patterns, Inc.
34
user stories
architecture
acceptance tests
UML diagrams
database model
35
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. Only a user's personal timesheets can be accessed. 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.
Timesheet List
Enter Hours
36
TimesheetManager
Timesheet
37
Complementary to class diagrams and CRC cards Can be extended using CRUD columns
38
39
problem statement
scope table
glossary
Physical Models
acceptance tests
CRC cards
database model
UML diagrams
- agilemodeling.com
Implementation
Data Base
40
41
Refactoring is a disciplined technique for restructuring an existing body of code, altering its internal structure without changing its external behavior.
- Martin Fowler
42
Visit AgileDraw.org
Conceptual Class Diagram
43
Presentation Outline
Environment Setup: Directory Structure, JDK, Ant and JUnit Using Hibernate For Persistent Objects The Spring Framework
44
Agile Java Development: Environment Setup (Directory Structure, JDK, Ant, and JUnit)
Quick Poll
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
48
Ant (ant.apache.org)
Compile tasks (that is, javac) Deployment tasks File tasks such as copy, delete, move, and others. Property tasks for setting internal variables Audit/coverage tasks Database tasks Documentation tasks Execution tasks Mail tasks Preprocess tasks Property tasks
<ftp server="mirrors.kernel.org" action="get" remotedir="/gnu/chess" userid="anonymous" password="guest@guest.com" verbose="yes" binary="yes"> <fileset file="README.gnuchess"/> </ftp>
Remote tasks
Miscellaneous tasks (e.g. echo)
49
JUnit (junit.org)
Originally written by
Erich Gamma (Gang of Four, Design Patterns) Kent Beck (author of Extreme Programming and Test Driven Development)
public class SimpleTest extends junit.framework.TestCase { int value1 = 2, value2 = 3, expectedResult = 5; 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
Console Runner
Eclipse Plug-in
Visual Patterns, Inc.
51
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
53
Quick Poll
What persistence solution does your project use (e.g. JDBC, ORM, entity bean)?
55
56
Relationships
One-to-one
one-to-many many-to-one and many-to-many
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
59
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
Deleting records
List timesheetList = session.createCriteria(Timesheet.class) .add(Restrictions.eq("employeeId", employeeId)) .list(); Related classes: Restrictions, Order, Junction, Distinct, and others
62
Presentation Outline
Environment Setup: Directory Structure, JDK, Ant and JUnit Using Hibernate For Persistent Objects
63
Spring Modules
65
66
Quick Poll
Using IoC
Class B
IOC Container
Class C
Class A
68
Light weight Inversion of Control (IoC) container Excellent support for POJOs (e.g. declarative transaction
management)
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
70
Quick Poll
71
Easier testing mock classes, dependency injection Bind directly to business objects
Simple but powerful tag libraries Support for various view technologies and web frameworks (e.g. Struts,
webwork, tapestry, JSF)
72
1. Controller 2. ModelAndView 3. Command (Form Backing) Object 4. Validator 5. Spring Tag Library (spring:bind)
73
web.xml
timex-servlet.xml
<bean id="urlMapAuthenticate class= "org.springframework.web.servlet.handler.SimpleUrlHandlerMapping"> <prop key="/enterhours.htm">enterHoursController</prop> ... <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver" > <property name="viewClass"> <value>org.springframework.web.servlet.view.JstlView</value> </property> <property name="prefix"> <value>/WEB-INF/jsp/</value> </property> <property name="suffix"> <value>.jsp</value> </property> </bean> 74 Visual Patterns, Inc.
75
public class TimesheetListController implements Controller { ... public ModelAndView handleRequest( HttpServletRequest request, HttpServletResponse response)
mockHttpServletRequest = new MockHttpServletRequest("GET", "/timesheetlist.htm"); ModelAndView modelAndView = timesheetListController.handleRequest( mockHttpServletRequest, null); assertNotNull(modelAndView); assertNotNull(modelAndView.getModel());
Visual Patterns, Inc.
76
77
Special (Spring) variable named status status.value status.expression status.error status.errorMessage status.errorMessages status.displayValue
78
public class HttpRequestInterceptor extends HandlerInterceptorAdapter { public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) { if (!signedIn) { response.sendRedirect(this.signInPage); return false; }
79
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
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!
81
getHibernateTemplate().saveOrUpdate(timesheet);
Declarative 22 36 87 145
82
More Spring
83
Presentation Outline
Environment Setup: Directory Structure, JDK, Ant and JUnit Using Hibernate For Persistent Objects The Spring Framework
84
Quick Poll
86
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.
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 Huge community - Plug-ins galore (thousand+) Ward Cunningham and Erich Gamma Battle of IDEs has only now begun!
88
89
7. Plug-ins (galore!)
sample workspace
90
Java Browsing
JUnit
Ant Assist
Visual Patterns, Inc.
91
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
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
JSP Assist
Database
Web Services
Visual Patterns, Inc.
94
95
Hibernate
Spring IDE
Visual Patterns, Inc.
96
NetBeans - 42 seconds.
Eclipse with JDT, WTP, Hibernate, Eclipse... 19 seconds!
97
Presentation Outline
Environment Setup: Directory Structure, JDK, Ant and JUnit Using Hibernate For Persistent Objects The Spring Framework The Eclipse Phenomenon!
98
Quick Poll
Do you use a GUI debugger? Or, a logging framework? Or, use println statements?
100
101
102
perspectives and views Breakpoints Step through code Variable inspection Hotswap Remote debugging
consolidated debugging
103
Web Developer
Tamper Data
104
Monitoring
Profiling
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
106
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; }
108
109
Authentication (user and application levels) Authorization (roles, groups, etc.) Encryption (wire protocol, configuration files)
User-level authentication & authorization
Application-level authentication
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)
AJaX Google Web Toolkit (GWT) - http://code.google.com/webtoolkit/ Direct Web Remoting (DWR) - http://getahead.ltd.uk/dwr/
111
More
112
Wrap Up!
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
A generalizing specialist is someone with a good grasp of how everything fits together.
- agilemodeling.com
115
RON
STEVE
Visual Patterns, Inc.
RAJ
SUSAN
116
visualpatterns.com/resources.jsp
Web Browser
HTTP
Controller
Spring
Model
Business objects,
Hibernate beans Spring Scheduler JDBC
RDBMS
(Oracle)
DispatcherServlet
View
JSP/HTML
Coding
The customer is always available. Code must be written to agreed standards. Code the unit test first. All production code is pair programmed. Only one pair integrates code at a time. Integrate often. Use collective code ownership. Leave optimization till last. No overtime.
Designing
Testing
All code must have unit tests. All code must pass all unit tests before it can be released. When a bug is found tests are created. Acceptance tests are run often and the score is published.
Comics
Cheat Sheets
R&D Concepts
Visual Patterns, Inc.
118
THE END!
extremeprogramming.org
hibernate.org springframework.org eclipse.org
Anil@VisualPatterns.com
119