You are on page 1of 489
Le document was created by an unregistered ChmMagic, please go to http:s/wmw.bisente.com to register it. Thanks| Agile Java Development with Spring, Hibernate and Eclipse By Anil Hemrajani Publisher: Sams Pub Date: May 09, 2006 Print ISBN-10:0-672-32896-8 Print ISBN-13:978-0-672-32896-1 Pages: 360 Overview Agile Java™ Development With Spring, Hibernate and Eclipses a book about robust technologies and effective methods which help bring simplicity back into the world of enterprise Java development. The three key technologies covered in his book, the Spring Framework, Hibernate and Ectpse, help reduce the complexity of enterprise Java development significant. Furthermore, these technologies enable plain old Java objects (POOs) to be deployed in light-weight containers versus heavy-handed remote objects that require heavy EJB containers. This book also extensively covers technologies such as Ant, JUnit, JSP tag lbraries and touches upon ther areas such as such logging, GUI based debugging, monitoring using JMX, job scheduling, emailing, and more. Also, Extreme Programing (XP), Agile Model Driven Development (AMDD) and refactoring are methods that can expecite the software development projec by reducing the amount of upfront requitements and design; hence these methods are embedded throughout the book but with Just enough details and examples to nt sidetrack the focus of this book. In adltion, tis book contains well separated, subjective material (pinion sidebars), comic ilusrations, tips and tricks, al of which provide real-world and practical perspectives on relevant topics. Last but not least, his book demonstrates the complete Iifecycle by building and following a sample apalication, Cchapter-by-chapter, stating from conceptualization to production using the technology and processes covered inthis book. In summary, ‘by using the technologies and methods covered in this book, the reader wil be able to effectively develop enterprise-class Java applications, in an agile manne hs document was created by an unregistered ChmMagic, please go to http:s/wmw.bisente.com to register it. Thanks| Agile Jv By Anil Hemrajani Development with Spring, Hibemate and Eclipse Publisher: Sams Pub Date: May 09, 2006 Print ISBN-10:0-672-32896-8 Print ISBN-13:978-0-672-32896-1 Pages: 360 [mead pyri ‘rewards bout the Author cknowledgment Pretac funman Recommended Resourced hcarnana oad Part il: Building the Sample Applicatior nats Covered in This Chapter fom User Stories to Desig xploring Classes Using CRG C: ara] ML Class Diag bampe Fie Named End-to-End Development Step: icceptance Test her Consideration funmay Pscommensed Resourced hapter 4. Environment Setup: JDK, Ant, and JUni hs document was created by an unregistered ChmMagic, please go to http:s/wmw.bisente.com to register it. Thanks| at's Covered in This Chapter lava Platform Standard Esition Development Kit (JDK Pirecioy structure] fal un ni To Mang he Tals Wak Top st Fis Design and ett] fiomay fsnnemamocomced ane 5. Vang penal or Peon Oi ats Govern Tis Chal Ove of Cet Relational apang OR] sg of Ou SamgeDalabas ere HSOLOS and Herts Fina Ou Ger cing vin Her ther Herat Feature fumnan fresnnenaea Recon agle 6_Oveniew he Sp Fanened nats Covered in This Chapte Jat is Sorina = Packaging ior Developmen] pring Packaging for Deploymen| werview of the Spring Module here Spring Framework Fis ino Our Arcitectur Fecommended Resourced hapler 7 The Spring Web MVG Framewor Jiat’s Covered in This Chapt Eoring Setup for Time Expression] Developing Tine Exression User irnes wih Sp aszaing Se Shet O55] imesee! List Ser: ANe Fam onal Bang Fite: ous Seer A Form Cooter Exam [ews win io Conte ring Hane 4 Sanpl Appicatein Aon ot Ta brain ing Frama fates a rane Fieconneniod Resouced apie 8 The Ease Phenomenal ats Govre in Tis Chal ne Eigse Fouad ne cipse Pom apd POS Feiss 0 once hs document was created by an unregistered ChmMagic, please go to http:s/wmw.bisente.com to register it. Thanks| [aamaeaed [etn U ipso Tie Epes ava Deveopen Tos JOT, Fea siaing he cise Web Tots Ptr (WTP Papin clgse Team Supper Fetes tee syste is and Ta rinsing cis folie Consent ai Pecommended Resourced Pasi, Advanced Feature apter 9. Loggng, Debugging Mion and Poin) whats Covered in This Chapte [ssing ve ska Commons Log ih Land and JDK Lena] Psouning Java Asleatons Us Eins ging Web User haces Using Feta ebvacing TimesheetManagerTest Endo End (Browser to Database IMX Management and Monitoring ava Prof Bebugging Tp fsoonena oul Sep 10-SeyrseBaih Tiss coves Tis Cup Fico Aces Jo enue fata ual fise re Sein Fan re Seg ars Herts amen) ISP Tag Ubraie etactrng ther Consaon ssid utvead jt About ve GUT THlk Glen Appleton ontgton Managemen CM Evtonnen VemctvonoisJevaSeitan XL ausx javadoc and Conmen faissesnos ua FissmenazaRosouan aot hatte ats Covered in Tis Crag pats th Tne Exreson Aa and AMDD-Based Software Developmen java Pato] bal hs document was created by an unregistered ChmMagic, please go to http:s/wmw.bisente.com to register it. Thanks| fused iverat he Spring Framewo cipee SD) cogging, Debugging, Monitoring, and Profi ating Hel P.Louick Note About Gode “Quality” Took Becommended Resourced hapler 12, Parting Thoughts Near Fue Pa ne Fue Agle Mts, lve Teco] ee Bar st: Rppendiced pendix A, Downloadable Code for This Boo ird-Party Libraries Shared Directory sample Application Directory (rapigavatimex) cfactored Sample Aopication Directory (rapidiavaltinex2) Boring Hibernate integration Demo Directory (rapdiava'sringhibernate) ndix B. Refactaring Dane to Sample Applicator SignlnContole java: JMX Monitoring imesheetl st Controle java: JMX Monitoring anager Classes: Sprng-Hibemate Inlegrato mesheetist jsp: Switch o Include File and Display nlerhours sp: Swith o Include File and Timex Tag Libra rest Classes and TimexTestCast ateuit java: New Method Jimexoss: New sive Jimexhsaldb xnt 82d Data Detect Fi pendix C. Java Code Convention pendix D._ Securing Web Applicaton pendix E. Sample Development Process Cheat Shee] eciec tat poration Pi pendix F, Agile Modeling Values, Practices, and Princinles Cheat Shee| pendix G. Extreme Programming (XP) Cheat Shee veri] pendix H_ Cool Took oss Platform Took crosott Windows-Based Took ac OS X-Ba5ed Took inux-8ased Tools (KDE] pendix L_ Visual Pattems Resear] he Probien| he Past: How We Have Been Kidding Oursel he Future: Agile Methos Perspective jin the Community’ fl This document was created by an unregistered ChmMagle, please go to hitp:/Awww.bisenter.com to register it. Thanks ra Copyright {Agile Java Development with Spring, Hibernate and Eclipse Copyright © 2006 by Sams Publishing All rights reserved. No part ofthis book shal be reproduced, sored in a fetrieval system, or transmitted by any means, electronic, ‘mechanical, photocopying, recording, or otherwise, without wtten permission from the publisher. No patent liabilly is assumed with respect othe use ofthe information contained herein, Although every precaution has been taken in the preparation of ths book, the publisher and author assume no responsiality for erors or omissions. Nor is any lablity assumed far damages resulting from the use of the information contained herein Library of Congress Catalog Card Number: 2005937888 Printed in the United States of America First Printing: May 2006 090807054321 Trademarks All terms mentioned inthis book that are known tobe trademarks or service marks have been appropriately capitalized, Sams Publishing cannot attest tothe accuracy ofthis information. Use ofa term inthis book should nat be regarded as affecting the valty of any trademark or sevice mark. Warning and Disclaimer Every effort has been made to make this book as complete and as accurate as possible, but no warranty or finess is implied. The information provided is on an ‘as is" basis. The author and the publisher shall have nether ialty nor responsibilty to any person or entity with respect to any loss or damages arising from the information contained inthis book. Bulk Sales ‘Sams Publishing ofers excellent discounts on this book when ordered in quantiy for buk purchases or special sales. For more information, please contact U.S. Corporate and Government Sales rpsales @pearsontechgroup.con| For sales outside ofthe U.S., please contact nternational@pearsoned.cor ‘Acquisitions Editor Jenny Watson [This document was created by an unregistered ChmMagic, please goto hitp:/www.bisente.com to register. Thanks] Development Editors Scott Meyers Songlin Qiu Managing Editor Patrick Kanouse Project Editor Mandie Frank Copy Editor Barbara Hacta Indexer Cheryl Lenser Proofreader Kathy Bidwell Technical Editor Bors Mirkin Publishing Coordinator Vanessa Evans Book Designer Gary Adair Page Layout Nonie Ratcit Agile Java Development wth Spring, Hibernate, and Eclipse is a welLunitten guide that covers numerous significant technologies, weaving them together using practical and proven methods that wil surely provide value to practitioners of every level Dan Malks, VP Solutions & Strategic Development, JackBe Inc; Author Core J2EE Patloms Anis relentiess dedication fo high qualty really shows. This isa very wel-witen Book! ost Sango, Conutent asiucon) ‘Ani has an uncanny abity fo cut tothe chase and ell you what you want to know. This book is one of those Jewels that appears only intrequenty. Instead of voluminous explanations of APIs, nil provides insightful Interpretation i highly visual terms, with a simple example that threads al the way through the book. Its 2 ‘masterwork of usability, as computer books go. Ci Berg founder of Assured by Design, co-founder of Digital Focus, author and consultant Dedication This is deaicated to my ioving and caring wife who has aways patiently supported me (and my odd ways). Thank you for taking care of ‘everyting during the times I was consumed by projects such as this book. This book would not be possible without you! And, of course, ‘to my dearest kids who brighten my every day r= This document was created by an unregistered ChmMagle, please go to hitp:/Aww.bisenter.com to register it. Thanks ra Forewords The true goal ofa foreword isto convince people to purchase the book. So, | guess you have three choices right now. First, you can save yoursel some time, stop reading this foreword right now, and simply take my word fort that buying this book's a good way to invest your hard-earned money. Second, you could not rust me, which franky isa smat thing to do because Im a consultant, and continue reading this foreword on the chance | might actualy say something that resonates with you and thereby motivate you to buy the book Third, you could decide to not purchase the book, which is kel a realy bad idea because the vast majoiy of Java programmers that | have met could really benef fom tis material |nmy opinion, the last hing thatthe Java community needs is another book describing some “really cool” Java technologies; there are hundreds of books out there already, thousands of magazine articles, and tens of thousands of web pages ateady covering realy cool Java technologies. Luckly, that's not wat this book is about. Agile Java Developments one of those rare books that teaches skis that you willuse throughout your career. Yes, it does cover the fundamentals of Spring, Hisemate, Ant, and a bunch of other stuff that you ‘need to succeed today. But, more important, it goes beyond the technology to describe agile techniques, adopted from Extreme Programming (XP) and Agile Modeling (AM), which enable you to succeed at modern software development. Most Java developers have heard about XP and many have adopted some ofits techniques, such as test-ven design (TDD), refactoring, and even air programming. This is @ ood start, but i's not enough. In this book, Anil brings his years of experience tothe table, describing wnat actually works in practice. This is diferent rom other books that often share a vision of what the author thinks will workin theory; but as we all know, theory and practice are often two ciferent things. \When Ani fist approached me tobe a technical reviewer ofthis book, the thing that most impressed me was his simple, yet effective, ‘approach to modeling on Java projects. n fact, you might want ofp through the book right now and take a quick look at some of the ‘madels. | think that youll notice that his diagrams are very similar to what you develop yoursel on actual projetsa rereshing change trom the advice presented in many of the modeling books available today. Youll also notice how Anil describes how to mave fom those simple models to the often-complex code that you wrte on a daily bass. This | think represents the greatest strength of this book: it Presents real-world advice that reflects what top-notch developers actually do in practice. The book also shows how many ofthe common tasks that we perform, such as acceptance testing, unit testing, objectelational ‘mapping, system integration, and refactoring, it into the sotware development picture. The book stats withthe "5,000 foot" process point of view, but dives down to ground level and describes how to use the tools n practice. Most baoks focus on ane view but not the other, but Agile Java Development pulls it off nicely and covers both views well Take afew minutes and browse the rest ofthis book. | think yout see what 'm talking about Scott W. Ambler Practice Leader, Agile Modeling This book isnot easly categorized. Let me explain why its unusual, and why it deserves your attention, Easily calegorizable books abound in our industry. They afe often books about a particular product or API. Some are good; some are bad. You can choose by the cover, the font, the publisher, the credibility ofthe authorbut you have already made a far more important choice: You know what book you are looking for. A good such commodity book may make you more efficent in a particular area, butts Unlikely to change the way you work. Books that are not easily categorzable are much rarer. They relate much more closely to ther author, and potentially to you ‘The present book shows how valuable such a book can be. Anil Hemrajani has dstiled his extensive experience as an architect and Ceveloper into a book that abounds inthe practical insights of a successful practioner. Like all the best books, its an effective communication between author and reader. As with all effective communication, the topic is nat limited tothe predictable, and ifs enjoyable: Anil has a natural wing style thats a pleasure to read This book has a remarkably broad scope. I tackles topics that are rarely tackled together, but shouldbe. The process we use to develop Le document was created by an unregistered ChmMagic, please goto http: bisenter.com to register it. Thanks software is inextricably linked to the way in which we structure our code and the tools we use to write that code. No effective developer works in 2 compartmentalized fashionthe many decisions to be made are intertwinedbut most books make ite attempt to paint te big Picture thats essential to geting results To develop Java software productively today, you need to understand key concepts such as O/R mapping and Dependency Injection you need to understand how and why to use techniques such as unit testing and automated builds; andequalysigifcantyou need to know the best tools forthe job, such as rameworks and IDEs. You also need to understand some of the pitfals to avoid, and how sometimes soft skils are as critical as technology. Anil has done a remarkable job of bringing these things together info a book that provides clarity n an area that many find confusing. It covers @ lot of ground, but never loses sight o its almto help readers complete successful projects see this book as a good map. It clearly shows you the path on your journey o successful enterprise Java development. Along the way, you may supplement it with mare detailed maps of particular areas. But you wll aways benef rom the direction it provides. | tecommend his book to anyone seting out to become an enterprise Java practioner today. It may well change the way you work, for the better. Rod Johnson CEO, inertaceat Founder, Spring Framework ra Le document was created by an unregistered ChmMagic, please go to http:s/wmw.bisente.com to register it. Thanks| ra About the Author ‘Anil Hemrajani has been working with Java Technology since late 1995 as a developer, entrepreneur, author, and trainer. He is the founder of Isavx Corporation, a successful IT service company (now Inscope Solutions), and isavix.net (now DeveloperHub.com), an award-winning online developer community that grew to more than 100,000 registered members. He has 20 years of experience inthe information technology community working with several Fortune 100 companies and also smaller organizations. He has published ‘humerous articles in well-known trade journals, presented at conferences and seminars around the world, and received the "Outstanding Contribution to the Growth ofthe Java Community” award trom Sun Microsystems, the "Best Java Client” award at JavaOne for BackOnlne, a Java-based online backup client/server product, 3 Computerworld-Smithsonian award fora tree online file storage service website, His more recent project isthe fanpater can webste ra This document was created by an unregistered ChmMagle, please go to hitp:/Awww.bisenter.com to register it. Thanks ra Acknowledgments wrote this book but it wouldnt have been possible without the help of mary brillant people | have the distinct pleasure of knowing | truly want to thank everyone listed here, from the bottom of my heart! © itt Berg First and foremost, | want to thank Ct, a long-time trend and colleague, for inspting me to write this book and ving me the confidence by validating and supporting my ideas. © Scott W. Ambler For agreeing to co-write the foreword for this book and reviewing every single element init, chapter by chapter. Scott has become one of my idols in ths fel, given his work on Agile Modeling and Agile Data, som stil amazed that he agreed to get involve fumuianscpr how enormously busy he is. | also want to thank Scot for the ovr. agi [iw agilemodeting. cor] and\wnw.agiledata or websites; these have been invaluable for me, Scott, thank you (© Rod Johnson When | frst met Rod, Ihad no idea | would be writing this book or asking him fora foreword! just knew we shared similar views and I respected his work alot. Given the Spring Framework’s populaiy these days, Im surprised that Fd even finds time to sleep s fiting inthe foreword for my book was especially meaningful to me (thank youl) also want to thank Rod fr putting together the Spring Framework, something Ive enjoyed working wit, © Anil Singh I cannot even begin to thank (the other) Anil for his help; the long hours, the invaluable feedback, the late nights ‘over the phone discussing the contents of my chapters (3 am. altimes)thanks fr everything! I particularly appreciate Ani's availabilty almost any and everytime, to discuss my book. Yet, all can offer in return isa heartwarming thank you! © Dan Shetiman For his rapid but detailed and hones feedback, which helped make this book so much better. Thanks for tolerating the 100 or so emails I sent over the course of tis book. I particularly appreciate your feedback and telephone conversations on weekends and even on family vacations! Dan has been a long-time coleague and friend and | hope this remains the case for along time to come. (© Haresh Lala For his constant feedback on anything and everyting! Thanks for testing all my code (twice!) and reading my chapters in their eartes, very rough, drat form. Most of all, thank you for helping me during a ime when you were super busy with new things in your ite (© Hernando Vera What would do without Hemando's astute thinking, clear presentation of ideas, and well-thought-out interpretation of technologies? Hemando has been one of my "go to” guys for almost a decade now. When I'm in doubt, know I can tur to him for answers from development to design to architecture to process and more. | have yet to meet anyone else that has the full package: bilan, innovative, cutent, and most of all one of the nicest people | know. (© Martin Remmelzwaal Martin and | met relatively recently but | aeady consider him a close fiend. Thanks for reviewing my earlier chapters. However, | particulary want to thank you for responding to my neverending emails about your perspective (on various technology, and methodology, related matters. | hope to collaborate wih Martin on various projects in the futur. © The Spring Framework te I, you guys are simply awesome! Now, for specific names. | want to thank Alef Aeron rhe eve. atta dana exsitarcengoreral ih anying an eveything png As evew significantly improved Chapters land | also want to thank Juergen Hoel fr his help on declarative transaction ‘management and late discussions about interfaces. Given the spring team's day jobs (helping clients), right obs (working on the framework}, and juggling multiple releases atthe same tmewel, what can I say but thanks, uys! © Machu Siddalingaiah dance in crating up the outine ofthis book (and other publishing matters), and also for his valuable feedback on Chapter © Dave Berman Dave's in-depth review off2hapter J and various discussions about Agile methods helped make the Agile.XP aspects of ths book more sald and thorough, © Jett Nilsen For his timely feedback on my diagrams irfhapter and 3 and the XP+AMOD comic series used inthis book: | was able to fix some malor errors inthe rick of ime, thanks to Jeff This document was created by an unregistered ChmMagle, please go to hitp:/Awww.bisenter.com to register it. Thanks © Ramanand Singh For our intial ciscussions about Spring and feedback ofshapter (© Pearson staff | want to thank the staff at Pearson (Songlin, Mandie, Kim, Mark, Barbara, and several others behind the scenes) for producing this book; a special thanks to Jenny for her involvement from beginning to end; her being there helped ‘me during normal and frustrating times. | alsa want to thank Baris for hs in-depth, ect, and valuable review ofthis bookthis book wouldn't be what itis without his help. © Tomy riend Peter, thanks for the intellectual stimulus from time to time, which helped me approach the book from unique perspectives. Also, combined with Andy and Missy thanks for al the laughs, which helped me lt loose a bit when | needed it ‘mast (particularly during the weeks of continuous 14- to 15- hour days writing this book). © To the Greenberr's cottes and tea shop stat for providing @ comfortable environment, high-speed intemet, and great coffee and food: ll ofthese alowed me to work there for houts ata time on ths book, © Last but not least, this books based on the innovative work of many people in our industy who have become my idols, so to speak. I would ike to thank these people, because they helped me indirectly by contributing some invaluable and amazing concepts. Some of these people include Martin Fowler, Kent Beck, Eric Gamma, Ward Cunningham, and others. We Want to Hear from You! As the reader of this book, you are our mast important cic and commentator. We value your opinion and want to know what we're ling right, what we could do better, what areas youd lke to see us publish in, and any other words of wisdom you" willing o pass our way. You can email or write me ctectly to let me know what you did or didn ke about this bookas well as what we can do to make our books stronger. Please note that I cannot help you with technical problems related tothe topic of his book, and that due fo the high volume of mail receive, might not be able to reply to every message. \When you write, please be sure to include this book's tile and author as well as your name and phone or email address. | will carefully review your comments and share them with the author and editors who worked on the book E-mail jensource@samspubishing con] Mai Mark Taber Associate Publisher Pearson Education 800 East 96th Street Indianapolis, IN 46240 USA Reader Services Visit our website and register this book at aww samspublishing.comiegiste for convenient access to any updates, downloads, or errata that might be avalabe for this book. This document was created by an unregistered ChmMagic, please goto http:s/wmw.bisenter.com to register it. Thanks ra Preface BEGAN WORKING WITH JAVA TECHNOLOGY in late 1995, shorty before the Java Development Kit (JDK) 1.0 was formally released. Prior to tha, | was programming in C and C++ for many years. | was truly excited about the features that Java offered, such as cross-platform portabilly, simpler syntax (simpler than C++, for example), abjectoriented, secure, ich API, and mare. (ver my 20-year career, Ihave leamed afew things. Among these, my favre is simplicity; anytime see complexity, | begin doubting whether the solution is correct. This is how had begun to fee! about Java right around 2000, when the Java 2 Enterprise Ealton (J2EE) started becoming mainstream. Note that from this point on, | will reer to J2EE as JEE because the "2" was recently dropped from the name by Sun Microsystems. [My growing lack of interest in Java was a result of what | saw as unnecessary complexiy in JEE introduced by ayers of abstraction. | began to believe that Sun Microsystems (inventor of Java) was focusing Java and JEE on solving the most complex enterprise applications, but somewhat ignoring the relatively less complex, smal-to medium-sized applications. Furthermore, | saw the hype take ‘over people's common sense because I ran across projects in which Enterprise JavaBeans (EJB) were used for nondistibuted pocessing_such as local looging_ felt strongly enough about this sublect to write a shot article for JavaWorld.com in 2000 tip iw javaworid.com/avaworldjv-10-2000}-1006-soanbox.him) itted, “Do You Really Need Enterprise JavaBeans?" (About fve years later, we saw EJB 3.0 specticatons being rewritten to become more simpfied, to ease the development, This brings us to this book and the reason | wrate it {was recently hired as a consultant for a Fortune 100 company to build an enterprise web application running in a clustered environment. While reviewing altematives to the standard JEE/EJB model by researching online and having discussions with some smart people, | decided ona solution, which included the Spring MVC web framework, Hibernate object-telational (OR) persistence framework, the Eclipse IDE, JUnit testing framework, Ant build uty, several tag libraries, anda few other products. (Al these products are covered in deal lterin this book, along with my rationale for choosing these technologies) "have enjoyed working with Spring and Hibemate, mainly because they allow me to work wit plain-ald Java objects (POJOs) and avoid some ofthe hassles of working with EuBs. Also, working withthe Eclipse IDE has been a nice experience. | continue to be amazed at how wel this product works, ad thats the reason | dedicate a whole chapter in this book to it. In my opinion, products such as the ones ‘mentioned here are breathing new ite into Java ata time when Java isa risk of losing its popularity to alternatives such as Micrasots INET, LAMP (Linux, Apache, MySQL, and PHP or PythoniPERL), and Ruby on Ral In this book, although Spring, Hibemate, and Eclipse ae highlighted a key goal fr me is to provide you witha complete solution trom technical and process perspectives. From a techrical perspective, | provide an end-to-end solution (using a vaiety of oo) for implementing a complete sample web application with transaction management inthe backend and suitable fora clustered environment From a process perspective, | recently switched trom nied Process (RUP) o a proces Provided by Agjle Model Driven Development (AMDD: llemodeing.con} and Extreme Programming (XP memeber cp ‘As aresul inthis book you wil ind concepts and artacis suchas user stories, release plans, CRC cards, and more. The dea is 10 provide you with a comprehensive solution for rapidly developing and deploying enterprise Java application. (One addtional note about my background. | have been a developer fr almost 20 years, primary working with core technologies such as C/C++, Java, enterprise relational databases, application servers, Unix, Microsoft Windows, and so on. However, I took a detour for ‘approximately fve years around 1998 to build the company had founded in 1996 (1 was doing minimal programming during tis time). later sold this company to get back into development. However, even though | was the CEO of this company and had several people working for me, | gol the opportunity to meet and interview literally hundreds of developers over a seven-year period and discuss technology with them. Apart from this company, | also founded an online community for Java developers, grew it to over 100,000 ‘members, and won several awards fr ths. I hope my experience rom these ventures ads a unique perspective t this book In summary, I ruly hope you wll ind this book useful and will enjoy reading it This document was created by an unregistered ChmMagle, please go to hitp:/Aww.bisenter.com to register it. Thanks Who This Book Is For This book assumes that you have some working knowledge of Java and relational databases (including SOL) as well as experience working on the command ine. Aside trom prerequisites mentioned here, the following types of people can use it © Software Developers/Architects Developers and architects can gain value from tis book because it includes a high evel software development process, application design, and an in-depth and complete inspection of the Java and related files of 2 tuly functional, sample enterprise web application. © Technical Leads/Managers Technica leads and managers with a programming background, preferably in Java or similar language, can get an in-depth look at how applications are bil using a variety of Java technologies. This knowledge might help during project planning or with stat troubleshooting technical problems (perhaps js! for moral support during frustrating times) Alternatively, technical managers can dive into a specific chapter for example, Phapter J "Using Hibernate for Persistent Objects" to understand how that specific technology works and fits into the big picture. In adition, as a reader, you might gain some insight from this book on atematives to JEE that you can use for bulding a robust enterprise-class application. Furthermore, if you are not familar with Agile Modeling or Extreme Programming or are looking fora nimble software development process, this book might have just enough to get you going with a complete process for developing sofware applications iteratively and incrementally Goals of This Book The goals ofthis book are a follows: © Agile development The frst and foremost goal of this book is to show you how todo rapid enterprise Java development. This Is achieved by combining multiple facets: a nimble/minimal software development process, a simple design (moderate use ot design pattems or layers of abstraction), convenience technologies (such as Spring and Hibernate), working with POJOs versus remote objects, and in general, leveraging stable open source technologies whenever possible. In shot, the idea isto ‘make Java simpler and faster to work wit for developing enterprise-ready applications. (© Complete solution A close second goal ofthis bookis to provide you with a complete solution, trom a technical and process perspective. After reading this book, you should be able to build an entire application, not just technically, but also using the process outlined in this book. In addtion, when | cannot cover a given technology in depth, | provide references to resources: (websites) fo turther investigation ofthe technology. The cool thing about the technologies covered inthis book s that you can have a complete system, from the user interface to an embedded database along withthe capability to schedule jobs (thanks tothe Spring Framework), al sel-contaned ina single web application archive (war) file! However, you can always, replace the technologies mentioned in here with some other technology of your chaioe (Tor example, using an Oracle database instead of HSQLDB). In summary, you wil have the complete solution to do thispracess and technologies! © Using an open source only solution isnot a goal ofthis book Although | have based this book entirely on open source frameworks, tools, and products, preaching an open source ony solution isn a goal ofthis book. For instance, you can leverage Java's vendor portabily and replace one of the products covered in here with a commercial product. However, open source has come a very long way, and Im thoroughly impressed by how robust these technologies are and how well documented they are. For example, technologies such as the Eclipse SDK and Hibemate are arguably better than some ot their commercial counterparts. You could just as well use all he technologies mention in this book for an enterprise solution and rest assured that they wil perform as advertised. Infact, | recent implemented an enterprise solution fora large company using the Spring Framework, Hibernate, Eclipse, JUnit, Ant, and other tools mentioned in tis book! However, we also used commercial products such as BEA's WebLogic Server and an Oracle database server. The same company (and several thers | know of) are basing their enterprise solutions onthe open source technologies | mentioned, © Quick read This book is intentionally smaller than the typical 600+ page books you find on Java. This was done to enable you to get through the book quickly and begin using the solutions in the real world In ight of this, | have tied to keep the content in this book streamlined and more to the point. The one downside of nat wring an extremely thick book is that had to make some tough decisions about which material to forego; however, lave tried hard to include all the important process- and This document was created by an unregistered ChmMagle, please go to hitp:/Aww.bisenter.com to register it. Thanks technology-related material you wll need for agile Java development (as explained inthe previous goal o providing a complete solution). © Simpicity Whenever possible, | ake the simpler approach to accomplishing the same objective over a complex solution. For ‘example, the sample application covered inthis book uses minimal layers of abstraction to accomplish our objective. By layers of abstraction, | am referring to the excessive use of design pattems, interfaces, and application partoning, Each of these makes enormous sense, but using everything in moderation is a good practice and one Ike to folow when | am working with a software development process and atitacts produced from such a process. Furthermore, | believe simplicity should also extend to designing, n that | tend to use UML when appropriate, but lean toward simpler, free-form diagrams. Using tools such as OpenOffice.org, PowerPoint, or Visio versus something heavy ke Rational Rose, (© Tips and ticks As you might already know, when working with tools and technologies, tips and tricks not only make the product work more effectively for you, but also make it more fun to use. I provide tips and ticks for same ofthe technologies covered inthis book. However, the appendixes also contain some goodies such as useful cheat sheets and alist af cool toass. (© Altematives Throughout this book (although notin deta), | try to provide alternatives tothe solution | am proposing. | realize that one solution does not ft everyone's need. For example, you might be using Sun Microsystems's NetBeans or JetBrains’ Intel as your IDE and do not want to switch to Eclipse. Tis type of scenario isto be expected and is completely Understandable, The organization of this book takes this into consideration; you shoud stil be able to gain value from the remainder ofthe book and replace a technology covered inthis book withthe technology of your choice (fr example, JDO versus Hibernate) What Is Not Covered This book assumes that you have warking knowledge of Java and a relatively good understanding of JEE. Italo largely assumes that you have a reasonable understanding of software development processes, relational databases, ner architectures, and so on. Given this assumption, I deve righ into the species required to build our sample application. Furthermore | refer yau tothe respective websites for setup (and advance features) instructions instead of duplicating this information inthis book and risk having it become out-of-date. (On te flipside, this book assumes that you have no working knowledge ofthe key technolagies covered here, such as the Spring Framework, Hibernate, Eclipse, and so on. Given ths view, tis book provides the basics on these technologies to get them to work together; this book also goes one step futher to provide you with a brit introduction to some ofthe advanced features offered by these technologies. Anything beyond what is mentioned here is beyond the scope of this book because there ate Iiterally entire books Cecicated to many ofthe technologies mentioned inthis book What Is Covered (Technologies and Process) The focus of this book is more on development and less on infrastructure. In other words, Ive focused more onthe application evelopment technologies such as Spring, Hivemate, and Eclipse than on products such as an application server (for example, JBoss) or database (for example, MySQL). When in doubt, | went withthe one easiest to set up. Also, ma big believer in getting the functionality implemented in an application frst and then optimizing later inthe form of refactoring and optimization techniques. What | have presented inthis book has been tried in real-world applications that are running successtuly n production (some ina clustered application server environment), so | dorit want to give you the impression that we are ignoring infrastructure altogether. One of the (goals of this book was to keep it short and tothe point, s0 | have chosen to focus almost entirely on a well-designed application that scales well Given the operating system (OS) and vendor portability benefits of Java, in theory, when your application is ready o be deployed, you can deply itto amore robust web application server and database combination. For instance, you could use the low-end products used in this book (Apache's Tomcat and HSQLDB), upgrade to @ JBoss Application Server and a MySQL database combination, or further Uungrade to a BEA WebLogic Server and Oracle's database server combination fr example. This isthe beauty of Java; itis nat only OS portable, but also vendor portable This document was created by an unregistered ChmMagle, please go to hitp:/Awww.bisenter.com to register it. Thanks (One more note about the core technologies cavered in his booknamely, Spring, Hibernate, and Eclipse. Although these are the technologies 've worked with recently and use inthis book, | have provided alternative and competitive technologies in the industy, which l encourage you to look at. For example, if you choose to use JDO rather than Hibernate, you can sill gain and apply the knowledge from all chapters, except pernaps the one on Hibernate, How This Book Is Organized ‘The chapters inthis book are organized so that each chapter but previous one. Furthermore, because the chapters are logically segregated, you could jump into a chapter rectly (for example, ise “Overview ofthe Spring Framework’) and learn about ust that chapter's content. Also, you might want o skp a chapter if you rested in using that technology (for example, you might wat owe NetBeans instead of Ele, here you woul kip haplr “Te Ecipse Phenomenon? apie itraduction to Agile Java Development. gives you an overview and a preview ofthe technologies and process we will use in this book Phapter J "The Sample Apaicaion: An Online Timesheet System,” is primary dedicated to detining the requirements for our sample application; however, it alsa provides nice overview of AMDD ang coties phate "X° and AMDD-Based Architecture and Design Modeling,” covers the design of our sample appication. Chapter 4 "Environment Setup: JDK, Ant, and JUnit,” cavers the env} 1up_ From bere, we enter the world of Java coding at a rap nace. when we look at programming wit inkohaoterd bnapters dandl.are dedicated to the Spring Framework Prapter “The Spring Web MVC Framework,” and|ohapter are what I call the wow!” chapters, because everything converges in these chapters and you will see and ‘appreciate why we went through the earlier chapters in the way we did. You will Know what happens undemeath the covers and hence havea solid foundation ofthe technologies such as Spring, Hibemate, Ant, and JUnit. From there, we will cover some advanced concepts and wrap up the book with some goodies inthe appendixes. (One other note is in regard to commanctline development versus GUI (for example, using the Eclipse SDK). The eatlier chapters intentionally use the command line so that you can get some fundamental understanding of how these Java tools work. Then, when you Use these tools (for example, Ant and JUnit) in an IDE such 2s Ecipse, you wil know exactly whats going on behind the scenes. This becomes particulary important the IDE does not meet your needs. About the Code For This Book This book is about Java coding and there is a lot of code related tothe sample application we will bull inthis book. This completely functional sample application wth all the source code and related files can be downloaded tram the publisher's website. Having the code in electronic form versus printed inthe book enables you to browse and test-crive the codelappication for yourselt ‘The code itself is referenced and explained throughout the book using notable snippets/excerpts trom the complete code. Furthermore, there are two conventions used fr ths cade: © In certain places, long single line of code (hats, more than 82 characters) have been spit into two lines for readability inthis book (© The code itsetf appears in monospace font. Note All the book's code is available for download at the publisher's website. For convenient access to this book’s example ossible updates or corrections be sure to register your book at This document was created by an unregistered ChmMagic, please goto http:s/wmw.bisenter.com to register it. Thanks About The Figures For This Book Apicture truly says a thousand words, so you wl ind many diagrams and screenshots inthis book. While have provided some UML. cagrams in this book, tend to lean towards quick tree-form diagrams and instead generate UML diagrams by reverse engineering an application. | dn't spend a lt of ime on formal diagrams because many ofthese are throw-away diagrams after they have served their purpose and most projects arent able to keep these diagrams up-to-date anyways. Ima big believer thatthe code and database are the final and most important arttacts. In summary, | believe clagrams should do the folowing: © Be developed only wnen they willbe effective, © Be sel-explanatory (for example, use words versus confusing notations, use legends). © Be simple, tothe point, and realy get across the intended message. © Conform to a standard notation (fr example, UML) ether if required by your organization fr a handover of a system to ‘another person or group, for code generation, or because you prefer to use a standard notation (One additional note about the figures in this book. In afew chapters, | have repeatedireused figures om previous chapters. This was ne forthe folowing reasons: © To set context forthe chapter or section that is about to be discussed © 1 id not want to inconvenience you by requing you to fp back toa previous chapter wire the figure was first introduced Personal Opinion Sidebars Throughout this book, you wil notice sidebars labeled "Personal Opinion," which is exacty what the content in these sidebar i. | have tried hard to separate this subjective material trom the objective material in the book. However, | hope you wil ind the viewpoints expressed in these sections usetl, a they are litle nuggets of my experience trom various perspectives: as a software engineer, consultant, trainer, author, community builder, and even CEO of an IT services company. XP and AMDD-Based Comics ‘You wil see an illustration at the top of each chapter that makes up a fictional story throughout the book about an eight-week project Using AMDD. The four main characters in this story also fictional, include a customer (Susan), a Project Manager (Ron), and two programmers (Steve and Raj). The idea behind these ilustrations is simple: to add bit of humor to this book while teaching you about AMDD and XP along the way. Also, the relaxed syle ofthese illustration is based on my interest in wing books for children (early readers). must warn you, these get abit corny, but | hope you wl find some humor and knowledge in them, It you Ike the style ofthese ilustrations and want to see more of these, please vist isualpatiems.con] Le document was created by an unregistered ChmMagic, please go to http:s/wmw.bisente.com to register it. Thanks| Recommended Resources This book covers many technologies, and given the nature of this book, it proves just enough information on the technology to complete our sample application. However, each technology warrants a book itself; indeed, there are books decicated to many ofthe technologies covered here. Meanuhile, the folowing are websites forthe key technologies covered in this book. Each provides addtional documentation (and in some cases, discussion forums) for their respective technology: © Agile Modetinghttosiwwn aailemadeting con} © Antfiipzvantapache org] © Ealinse SOx fitpsTesipse.ord © Extreme Programming itp /exremepregramming © Hibernate Framework ip: ihibemate org © HSOLDB database engine itp insalab og © unit fipjunitog © Spring Framework tp:isprngirameworkord Visual Patterns fitpzivsualpatters.com] | will provide chapter spectc resources atthe end of each chapter, so you wil have plenty of resouroes for futher reading by the end of this book! ra Le document was created by an unregistered ChmMagic, please go to http:s/wmw.bisente.com to register it. Thanks| cInay : Overview introduction to Agile Java Development hm sane Apt: nnn Tees Sym cy This document was created by an unregistered ChmMagle, please go to hitp:/Awww.bisenter.com to register it. Thanks cInay 1. Introduction to Agile Java Development Release 1, Week 1, Iteration 0 eS Susan: I have approval from upper management to move forward with release 1 of this application. Ron: Sounds good; I'll have my programmers, Steve and Raj, begin looking at this starting next week; they like programming software, as a pair. (¢) Views Pattern, oc. WHEN JAVA DEVELOPMENT KIT (JDK) v1.0 was released in January 1996, it was a fail straightforward application programming interface (API). Over the years, Java has matured into a ful-biown platform. From JDK 1.0 to JDK 1.5, we have been introduced. to many ‘ew features, such as the Java Collections Framework, lagging API, auto-boxing, generics, and more. Although most ofthese are useful, Java has also become more complex, especially after the advent ofthe Java Platform Enterprise Edition (JEE). JEE introduced such concepts as Enterprise JavaBeans (EJB), which sought to simply vendor-portable, enterprise-level cstributed computing, but instead, it introduced unnecessary complexities for 80% ofthe applications out there. Nowadays, itis not uncommon far many people to think of JavalJEE as being abig and heavy technology. Well for starter, his couldnt be further from the truth, and second, les see it we can change ths perspective in this book. In the past few years, many open source frameworks have sprung up to solve some of the problems created by JEE. This book covers some ofthese open source frameworks (or example, Spring and Hibernate) as well as open source tools (such as Ant and Eclipse), which provide a comprehensive, effective, and elegant solution that can either be viewed as complementary or as a complete altemative to JEE, Le document was created by an unregistered ChmMagic, please go to http:s/wmw.bisente.com to register it. Thanks| ‘depending on how you apply these technologies for your specific needs. In adltion, nimble software development processes such as. Extreme Programming (XP) and Agile Model Dven Development (AMDD) can assist in accelerating the project devery. Software development is about people, processes, and technology (and probably in that order of priori. The people are the stakeholders, the customer we buld software for. In this book, | will cover the process and technology pats. You wil learn how to leverage these tools and technologies to rapidly develop end-to-end applications using Java, trom the cent tie tothe dala tier, and more. Along the way, you should see many of the benefisresuling fom using these tools and technolagiesfor example, simplicity and speed of evelopment. Before we begin, i you have not read the preface, | would recommend at least glancing through it ecause it provides some foundation for the goals ofthis book and the way iis organized, and includes some reasons why | wrote this book. cay Le document was created by an unregistered ChmMagic, please go to http:/wm.bisente.com to register it. Thanks| ra What's Covered in This Chapter This chapter provides a preview ofthe key technologies and software development process we willuse inthis book. In ths chapter, you will get an overview ofthe folowing (© The runtime technologies and development tools used in this book to build the sample application (© The software development process used to buld the sample application © How this book is organized ra This document was created by an unregistered ChmMagle, please go to hitp:/Awww.bisenter.com to register it. Thanks cInay Technologies Used in This Book This book combines various open source technologies, shown in[fable +. which were chosen to provde a comprehensive solution for building enterprise applications based on Java. | have also provided altemative open source technologies, and in some cases, commercial technologies, in case you dor't want ta implement an end-to-end system using the technologies covered inthis book. AS | ‘mentioned inthe preface, this book is organized so that you can ether read it end to end, go to specific chapters only, or skip a chapter it the technology being covered init doesnt apply to you (Hiberate, for example). Table 4.1. Technologies Covered in This Book FreeiOpen Source Chosen Technology category Alternatives Commercial Alternatives Inversion of Control loG) «HiveMind and Pcofor oC Not applicable ringtramenor. or Container, Web Framework container, Sts, JavaServer Faces, Tapestry and others or Web Framework Hibernate Persistence Framework £48, JDO, Bats (Oracles TopLink Ecipse SOx fsipse on) IDE NetBeans, jE and several JetBrains Ine, M's others Websphere Studio Applicaton Developer Ant fntapache o Configuration Management make, gnumake, nmake, jam, Microsoft make, MKS make cise contol, maven sunt (unito) Testing TesiNG, Ft Mercury LoadPunner save fsadb.on) 100% Java Database MySQL, PostgreSQL, OneSDB Oracle, Microsoft, Sybase, and HTTP ServeriServet Container Jety and several others BEA WebLog, IBM Websphere, Caucho Resin and others MozilaFretox frozitacon) Web Browser Miceosot Intemet Explorer, Not applicable Opera Openortce ore Bpenatice og} Ofice Suite used for tree frm Kofice (or Linux KDE) Microsot Otis, StarOfic, cliagrams in tis book) EasyOitice Ahough, this book focuses on open source technologies, ths isnt because 'm an open source fanatic. n fact, on my consulting engagements, | ork extensively with commercial products such as BEA's WebLogic server, Oracle's database serve, and other Products. However, these technologies can be considered robust enough to deploy an enterprise-ready Java application and they cost you thing! ‘As I mentoned inthe preface, the focus of this book is more on development and less on infrastructure, so Ive used the server products that wee the easiest o set up and that were, coincidentally, smaller in size. However, as you undoubtedly know, Java isnot only This document was created by an unregistered ChmMaglc, please go to http:/www.bisenter.com to register It. Thanks ‘operating-system neutral, itis also vendor-product neutral for example, you could swap out Tomcat with something lke IBM WebSphere by deploying our sample application to it. Athough this might not be as simple as it sounds, tis certainly possible and something ve done ‘mutiple times with JDBC-compliant databases and servet containers, or example. End-to-End, Self-Contained Application in a gle WAR File | would lke to emphasize something about the technologies covered inthis book and the interesting possbilties they ‘pen up. Imagine the capabilty to have an enterpise-ready application with an embeded database (HSOLDB, in our ‘case, wth builtin job scheduling (thanks tothe Spring Framework), enterprise-level transaction management, and a few ther enterprise servicesal wihin a single, sel-contained, ready deployable web archive (war fle! The folowing two sections provide a brie description of each technology or tool, the purpose it serves, and my rationale for selecting it Runtime Technologies This section provides a bret description ofthe runtime technologies. Runtime te Ceployed, versus development tools which are used to develop the application. technologies ft together to provide @ complete runtime solution. are used to run the application ater itis re 1 provides a visual representation of how these Figure 1.1. How the runtime technologies covered in this book fit together {View fullsize image] Java Servlet Container (Apache Tomcat) Java Platform, Standard Edition (Java SE) Development Kit (JDK) This document was created by an unregistered ChmMagle, please go to hitp:/Awww.bisenter.com to register it. Thanks Weil use te test verso othe 0K (or exarple, 1.) vais tom tefxasunconl wette Notthat slong as We have JOK 14 or later, the technologies covered in this book (Hibemate and Spring, for example) will work just fine. The Spring Framework ‘The Spring Framework contains a large number of classes and packages, bu itis designed as a modular framework that can be phased gradually into a project by using only the features needed (for example, web framework). Spring complements JavalJEE by providing an Inversion of Control (loC) container (explained later in book), a web framework, a transaction management abstraction layer, JDBC helper classes, jo scheduling APIs, email capabilties, and more. Spring has been around since 2002 and has gained considerable momentum and support from the community, including commercial vendors such as BEA Systems. A of the writing of this book, Spring was a frontrunner inthe loC container space; however, its web framework is surprisingly popular, as well | chose Spring forthe web framework because | also needed mary of its other features, such a loC, transaction management, email scheduling, and more. ‘The Spring web MVC framework is second to none when it comes to robustness, lexibilty, and a well-designed framework. was pleasantly suprised to finda large nu es on this framework, a couple of books decicated to this framework in the making (at the time ofthis writing), lots o indicating Spring MVC was second in use only to Struts Hibernate (uibernate ord Hibernate isan abjec-1o-relational (OR) mapping persistence framework for Java. Hibernate can arguably be credited with ringing OR. technology tothe foreront for average Java developers and net just specialized OR experts. Hibernate is perhaps the mast widely used (OR framework current inthe world of Java developers. Hibernate aso serves as a good alternative to Entity Beans, which is perhaps one ofthe reasons EJB 3 has adopted many techniques from Hibernate (and JDO and Topi). Given these reasons, my decision to go with Hibernate was easier than selecting a web framework, HSQLDB HSQLDB isa lightweight but complete relational database management system (RDBMS) writen in 100% Java, It supports a subset of the ANS}-92 SOL standard and has a JDBC driver to interface with the database via Java programs. The popularly of HSQLDB has grown steadily over the past few years | decided to use HSQLDB because itis lightweight, easy to instal, and because the focus ofthis bookis on development, not infrastructure. On a project recent, we used Oracle as our database; however, l used HSQLDB inthe inal stages for development while ‘our Oracle database was being setup (slow, thanks to corporate bureaucracy). Ifyou use 100% ANSI SQL in theory you could switch back and forth between a local and enterprise database during your development Apache Tomeat (omeat apache. “Tomcat is perhaps the most popular Java-based web server and servlet container. It isa relatively ightweight servet container that has grown in popularty over the past few years. | chose this product because many developers are already familiar with, soit seemed lke the obvious choice. Similar to HSQLDB, which can be replaced with a more robust database (such as MySQL or Oracle), Tomeat can Le document was created by an unregistered ChmMagic, please go to http:/wm.bisente.com to register it. Thanks| also be replaced with a more robust web andior application serve, such as BEA's WebLogic. Development Tools ‘The folowing are the development tools we will use to construct our sample application. Eclipse SDK Eclipse is one ofthe bes! things to have happened to Java in recent years. In my opinion it has given Java a longer fe as a dominant technology. n act, phapter "The Ectipse Phenomenon! is dedicated to Eclipse and is loaded with information about the core IDE and the enormous number of plug-ins available fri ‘The Eciipse SDK isan open source integrated development environment (IDE) founded by IBM. Ecipse in tse i a platform; however, the capability to develop plug-ins for this platform s what makes Eclipse such a powertultoolso much so that major product companies are rebuilding or repackaging ther products as an Eclipse plug-in, Given that Eclipse is open source, has las of plugins available fort, and has immense and growing industry support behind in some ways makes Eclipse a clear winner inthe Java IDE space. Eciipse's basic Java tools include source formatting, building, debugging, and integration with Ant. However, there are iteraly hundreds of free and commercial plug-ins availabe fr Eclipse. From UML diagramming to database too ‘a demand for some functionality, you are moyen nin si is covered in detallin later chapters; meanwhile, Figute 1 layovides a preview screenshot of igure 1 the Eclise SDK on Mac OS x shows a screenshot of Eclipse on Windows XP, andigure 1.4 shows Ecipse on Linux. Figure 1.2. The Eclipse SDK 3.1 on Mac OS X. View fullsize image} Le document was created by an unregistered ChmMagic, please goto http: bisenter.com to register it. Thanks Java = EntertfoursController java = /Users/aniljRapidjava Eclipse SK 1 Borejees gut Buiew very ‘mh users ania Souia Gacasses San ou Snprojer ea > soring-macklar~/s iD seringsar~ Users aD sundareer- ¥ Beomusupanems center ued Ics: il Sle OG 1B SS |S Fl] AGI o- >. aie Hoag NE eee Fo eo G/B tPROK% > M toosj-12.An jar = fuser | [~ Eitimex Ja Stmport con.visuotpatterns (apart com.visuelpetterns sport comvisualctierns ‘sport jowa.util Moston; users 7 ‘mport jova.uthl Les pronase Inttp.etpServletRequest; tapers focmcntevis Aig mgsarvtemanpenss ‘sport org.soringfrasework. wal idation.BindExceotion; sport org.springfrosework web. bind. ServietRequest ates sport org.springfrosework. web servlet Mode AndView sport arg.snringfronenork. web. servlet ave, Simple ml (rettems| dec] Declaration |) Censete FE wie el B+ 3-5) usdatecentia: 1 [wna | Smartnaere | 16 “sterminated TeX bald aon Ant Bull] System Library rarewks/}arwVW.frarewark/Versions/ 442i | vier le: QlsaeséonklanidieraCTimetfiutld pe) Ceaee) Copying 2 Fetes to MUsersseniL/Reptdlova/Timer/buiLe/timea/MCE-TNs9 Figure 1.3. The Eclipse SDK 3.1 on Windows XP. {View full size Le document was created by an unregistered ChmMagic, please goto http: bisenter.com to register it. Thanks aioeenn eee ‘Ble Edt Source Refactor Mavgate Sewch Project Run Window Hep i= @\e-Ora~leao- lag ise |s -il-™ B bgtH2A1or-1 © spring-mock ar =: © sprng.jar - C:\ant public static final String EID = "eid"; public static final String TID = "tid"; 17 ‘TODO: Add some comments protected Object formBackingobject (HttpServietRequest request) ( // If timesheetid passed in (edit moder retrieve record from db) Af (request. getParameter (710) != null 66 request. getParaneter (TIO) .trim() length () > 0) return tinesheetManager.getTimesheet { parse Int (request .getParameter (TID}), Figure 1.4. The Eclipse SDK 3.1 on Linux. ew ful size image] This document was created by an unregistered ChmMagic, please goto hitp:/ww.bisente.com to register it. Thanks (a cjava v Entertourst ontrener gave : Ecipse SOx. (25x Ese Gok Source Rateciny Mevigate Senn project Eun eingow Help [rie & |S-O-a-|H a ola 7) 4G [Bre Fle Gr oe rece. SP =) ememoarcomoseriee FE eo @ ba? puntie static tinal Strim 618 "ec; babtie state final String 110 © “tis” 14-1000: 403 sone © peste ce EERE seers j = eset 1/4 eunseee faen An oth terete | |= enetovscenaet 2 imesheeiano} 1 (reqeest.getParaeeter (71D) '~ el = depanmentian| Tegel petParmeter 70) rin) tenet > 0 fetern Eaersheetfanape pet Timesheet #80 Suing Treeger-parsefbt (reavestoetPoronter 7} Ber ue faa: u “neshace imeshect « nae TLaeshest marl ‘meshes etEaplayee CAC TM epetearsedne request 0) (9 ateferencedatay fe See © nensusm tps arnt yaaa) sleamvoneruca | |B Poblems EFS juvacoe) Decaraven xe 5 >5) smbsramaiskrmornenin | b @pus D Geetasces @ The mportjavaubllist is never ure UnteMtourCcUmen/sCharalcornsualy ne T The impart java ubiMachap is nev: Techeetiitimen/src/}aea/cormvisualy line hs The importjavabiList is never ure TemecheetLisumen/rc/}aearcormicuay tne $ (© The import jarautimap if never use TimecheetLi Umenarchasarcomsily line ‘The impor java utl.Date is never us Geparementh mesierejjavaleomuvicual ine 3 Ant fntapache.org) [Anyone working with Java these days has almost certainly heard of or worked with Ant. Ants the most common way to buld (and deploy) Java programs today. Although Antis similar to the Unix make uty, it provides several benefits over the make uty. [Ants covered in detail in later chapters; meanwhile, the folowing is a sample Ant build xmifle: < - However, when we discuss Ant in more detail ifapierd “Environment Setup: JDK, Ant, and Jui” you wil begin to see how powertul Ants and why ithas become the de tact build oo in the Java community. This document was created by an unregistered ChmMagic, please goto http:s/wmw.bisenter.com to register it. Thanks JUnit Units the de facto unittesting framework used by Java developers today. | wasnit always a fan of witing unit tests fst, 1 have come to appreciate unit ests and the notion of test fst. ll expain later inthis book how to wrt elective unittest. Ease 1 rovid screenshot of the JUnit GUI tol to give you an idea of how you can unit test your code. However, by the time we are done with hapter | you wil appreciate how tightly integrated JUnitis withthe Eclipse SDK. Figure 1.5. JUnit Swing runner on Windows XP. View full size image] JUnit JUnit Test class name: comvisualpatterns-timex:test.SimpleTest Reload classes every run a * Errors: 0 * Failures: 1 ‘com visualpatters.timextest SimpieTest w testAddSuccess * testaddF ail | * Failures |_# Test Hierarchy: junit framework Assertion F ailedError at com wisualpatterns timex test SimpleTest testAddF ail(SimpleTest java:28) at sun reflect NativeMethodAccessorlmpl invokeO(Native Method) at sun. reflect NativeMethodAccessorlmpl.invoke(Unknown Source) at sun. reflect DelegatingMethodAccessorlmpl.invoke(Unknown Source) Finished: 0.093 seconds Le document was created by an unregistered ChmMagic, please go to http:s/wmw.bisente.com to register it. Thanks| Firefox (nozilla.cor ‘You might be wondering why a web browsers explicitly Isted here. Trust me, itisnt about a by jon thing. Simply pu, Firefox has, a lat of features that help in web application development, and we will use a couple ofthese in Bhapter J "Logging, Debugging, Monitoring, and Profiing refx isthe large number of useful plugins available fort. Atte time of this writing, the 35addons mozila.or website (also accessible from the Tools, Extensions menu) had 1,091 plugins! Opendffice.org COpenotice.orgis an open sourre suite of office producity tools that competes directly with Microsoft Otfice. A fst, | wasnt sure it listing OpenOffice.org expicityin[table 1 ]was needed, because it isnt a core technolagy Im writin about inthis chapter. Als, | had checked out OpenOifice.org a couple af years ago when itwas stil a maturing product, and | wasn’ that impressed with it. OpenOtfce.or@ has come a long way and is equivalent to Microsoft Oice in almost every respect. In fact, OpenOifice.org can also read and rite natively to Microsoft Office fies, seamlessly | chose OpenOffice.org because | bought @ new laptop and wanted to give tis new (and of course, ree) version of OpenOtice.org a try before investing @ couple of hundred bucks on Microsoft Office. | was so impressed withthe latest version that I did all my freeform agrams in this book using the OpenOffice.org suite o ofce tools, cInay Le document was created by an unregistered ChmMagic, please go to http:s/wmw.bisente.com to register it. Thanks| ra Software Development Methodology Used in This Book To make a project successful, | have always believed that active stakeholder involvement, simplicity (design, tools, documentation), common sense, and a basi/minimal software development process does the trick. Furthermore, | do not lke to reinvent the wheel, so someone out there has assembled a good solution that | can use, I wil. One suc solution | have use combination of best practi ed by the Age Model Driven Development fit/aglemodelin.con) and Extreme Programming htalextremepregramming ord o or shot, AMDD and XP, respectively. Prior othe working with AMDD and XP, was using the Rational Unified Process (AUP. for projects. However, find RUP abit heavier onthe arilact side. ke the combination of AMD and XP because both methods are rimble and complement eachother; XP focuses on the fll fe cycle and AMDD focuses on modeling (user-interface model, for example). You will earn mare about these two ‘methadologies inthe next chapter along with my opinion about why | ike Agile Modeling’ values, principles, and practices. Personal Opinion: A Decade of Java and More to Come | must admit that this section is more about me than Java, so you can skp ths ifyou don lke personal opinions. When I reflect back on the years | have spent with Java feel od. No, but seriously. I started working with Java in late 1995, when the acronym JDK had actualy date back to 1990 (to read more about Java's history, visit In these 10 or so years working with Java, | have met some of the original founders of Java, such as James Gosling, ‘Athut Van Hof, Jonathan Payne, and Sami Shaio (you wll sil tind some of these names in the JDK source code).1 also had the opportunity to be the fith person in WebLogic, nc. (a couple of years before BEA acquired them) but dint want to relocate (yes, | know, | sill kick myself fr this once-in-a-ifetme, missed opportunity. also trained over a thousand students in Java and web technologies forthe Learning Tree and later, my awn courses. | have published ‘more than 26 articles on Java and even founded (and sold) two companies focused on Java-based solutions. At one of these companies, my staf (and ) provided enterprise Java solutions to many companies. Infact, we introduced Java to several large companies. (1m particulary proud of personally ntraducing Java toa fortune 60 company!) In adition, "ve attended fve JavaOne conferences and received two awards at JavaOne fora pure Java backup software | wrote ‘and an online community | uit. Last, |have presented at several user groups and conferences internationally \Why am I teling you all this? Well, frst and foremost, to brag. Second, | hope to bing a unique perspective to tis book. But the thir reason i that even ater a decade, 'm amazed (and pleased) that Javais sill considered a dominant technology n this book, | wil introduce you to new technologies that give Java a whole new iene, and now ''m convinced that Java wil be hot fora least a few more years, In shor, ityou are a Java developer, you should be excited about working with an elegant and robust technology that is sill very much current and thriving! | hope to prove this to you inthis book. Enjoy! ra Le document was created by an unregistered ChmMagic, please go to http:/wm.bisente.com to register it. Thanks| ra Summary Inthis chapter, you got an overview of (© The runtime technologies and development tools used in this book to build the sample application © The software development process used to buld the sample application (© How this book is organized In short, | gave you an overview ofthe tools we will use inthis book to build aur sample application, along with the software development process we wil flow. In the coming chapters, we will ave some fun with these technologies by puting together a real-world applicationa timesheet system, ra Le document was created by an unregistered ChmMagic, please go to http:s/wmw.bisente.com to register it. Thanks| ra Recommended Resources ‘The following websites are relevant to and provide addtional information onthe topics discussed inthis chaper: © Agile Modeling fitosiwwnagiemodeling con © antfipciant apache or © Apache Tomcat fititomeat apache ord © Eclipse SOK iipsiecipse org] © Hibernate fiipstiberate on] © HsaL8 fitp:imsalab or © Java open source products hitpviava-source net] © Juni hitpsjunitor © openottice.orfiipinnw-openotice or © The Spring Framework itio:/sringhamework.o © Visual Paters fitp/visualpatterns con] KIE=a This document was created by an unregistered ChmMagle, please go to hitp:/Aww.bisenter.com to register it. Thanks 2. The Sample Application: An Online Timesheet System few ful size image} Release 1, Week 1, Iteration 0 : We are currently in the exploration phase of this project, which will include some domain modeling, UE sketches, initial user stories, and soon. Then Steve and I will go off and do some light-weight architecture and design, aa ‘us going with iteration 1. The first release we actually depiey te acceptance will include iterations 1 through 2, from there on, we will deploy iterations, every 2 weeks. Note that each iteration will result in production-ready code, so we, can choose. whether ta actually deploy it te production or nat. One of our Is is to Keep things simple and have just good enough Got ow Way des | won't werd ee up front, ne requirements or nailing the architecture down complet Also, our code will serve as the core system documentation because we can reverse engineer, documentation from it. {c] Visual Panerns, ine. INTHE REAL WORLD, A NEW SOFTWAREdevelopment project is typically inated because there is some sort af a customer need, problem, or process optimization. This need can be from an intemal group or an external party (for example, interfacing with an external partner system or consumer demand for a product). Aer a problem or need is identified, there is typically some form ofa project kickot! ‘meeting o beter define the requirements, ‘As | mentioned inthe previous chapter, ths book resto follow a flow similar to how a real-word project might flow. In this book, we wil pretend that we have a requirement trom an internal group (a fictional customer) and use tis requirement to buld a sample application named Time Expression | considered several types of applications to use as an example in his book; inthe end I settled on a rudimentary timesheet system because | believed that itwas an application most readers would be able to relate to. For example, you migi be an employee or Le document was created by an unregistered ChmMagic, please go to http:/wm.bisente.com to register it. Thanks| consultant who works by the hour, and you submit your timesheet onlin (and also get it approved ontine, and so on) (Our sample application, Time Expression, will have a user interface (Ul) 2s well as some background processing. The UI will be web based and will contain screens that provide the capabily to enter hours worked, approve timesheets, run management reports, and more, The background processing wil include a weekly (scheduled) batch job that is automatically run to send out a reminder emai cy Le document was created by an unregistered ChmMagic, please go to http:s/wmw.bisente.com to register it. Thanks| ra What's Covered in This Chapter The focus of this book is more on technology and less on process. However, this chapter provides an overview of an agile software evelopment process that you can easly apply to your project. 'm a big believer in having a bare-minimum process, even iitis a t-page checklist of 10 or so items that serves as a memory jogger fr things that need tobe done as pat ofthe process. (Note: Ihave included such a checklist in the appendixes.) This minimal pracess ensures thatthe project is run efficiently and at the same time is focused on customer satisfaction, In this chapter, we will accomplish the folowing © Gain an understancing of what our sample application will do by looking at some business requirements. © Establish a simple software methodology based on Extreme Programming (XP) and Agile Modeling Driven Development (amon). © Develop some high-level artifacts such as a domain model, Ul prototypes, high-level architecture, and more. © Create a simple release plan based on our user stories. Note Itis important to realize that mary ofthe artifacts shown inthis chapter (release and iteration plans, for example) are ‘more for demonstration purposes. However, his chapter is very relevant to te rest ofthe book because we will implement some of the functonaity described in his chapter (for example, the Enter Houts and Timesheet List screens). In general, you can ignore particulars such as dates and estimates. ‘Also, this chapter assumes that you have a basic understanding of software development processrelated concepts, (use ates, for expe Hawnver Lm exlanctons on the varous concent in tis cape arent stent, recommend visiting jw agilemedeling.conf for dptaled exslanatins ln general, this website is loaded with infomation eleva tis cape Also vst te bxtoneprogranmng er ebste er detaled nian on the XP rmethadology. r=

You might also like