Professional Java JDK 6 Edition
Professional
Java® JDK
®
6 Edition
W. Clay Richardson, Donald Avondolio, Scot Schrager,
Mark W. Mitchell, and Jeff Scanlon
® ® Professional Java, JDK
6 Edition
Published by Wiley Publishing, Inc. 10475 Crosspoint Boulevard Indianapolis, IN 46256
Published simultaneously in Canada
ISBN-13: 978-0-471-77710-6
ISBN-10: 0-471-77710-2 Manufactured in the United States of America 10 9 8 7 6 5 4 3 2 1
1O/RU/RS/QW/IN No part of this publication may be reproduced, stored in a retrieval system or transmitted in any form or by any means, electronic, mechanical, photocopying, recording, scanning or otherwise, except as permitted under Sections 107 or 108 of the 1976 United States Copyright Act, without either the prior written permission of the Publisher, or authorization through payment of the appropriate per-copy fee to the Copyright Clearance Center, 222 Rosewood Drive, Danvers, MA 01923, (978) 750-8400, fax (978) 646-8600. Requests to the Publisher for permission should be addressed to the Legal Department, Wiley Publishing, Inc., 10475 Crosspoint Blvd., Indianapolis, IN 46256, (317)
http://www.wiley.com/go/permissions 572-3447, fax (317) 572-4355, or online at .
LIMIT OF LIABILITY/DISCLAIMER OF WARRANTY:
THE PUBLISHER AND THE AUTHOR MAKE NO REP- RESENTATIONS OR WARRANTIES WITH RESPECT TO THE ACCURACY OR COMPLETENESS OF THE CON- TENTS OF THIS WORK AND SPECIFICALLY DISCLAIM ALL WARRANTIES, INCLUDING WITHOUT LIMITATION WARRANTIES OF FITNESS FOR A PARTICULAR PURPOSE. NO WARRANTY MAY BE CREATED OR EXTENDED BY SALES OR PROMOTIONAL MATERIALS. THE ADVICE AND STRATEGIES CONTAINED HEREIN MAY NOT BE SUITABLE FOR EVERY SITUATION. THIS WORK IS SOLD WITH THE UNDERSTAND-
ING THAT THE PUBLISHER IS NOT ENGAGED IN RENDERING LEGAL, ACCOUNTING, OR OTHER PRO- FESSIONAL SERVICES. IF PROFESSIONAL ASSISTANCE IS REQUIRED, THE SERVICES OF A COMPETENT PROFESSIONAL PERSON SHOULD BE SOUGHT. NEITHER THE PUBLISHER NOR THE AUTHOR SHALL BE LIABLE FOR DAMAGES ARISING HEREFROM. THE FACT THAT AN ORGANIZATION OR WEBSITE IS REFERRED TO IN THIS WORK AS A CITATION AND/OR A POTENTIAL SOURCE OF FURTHER INFORMA- TION DOES NOT MEAN THAT THE AUTHOR OR THE PUBLISHER ENDORSES THE INFORMATION THE ORGANIZATION OR WEBSITE MAY PROVIDE OR RECOMMENDATIONS IT MAY MAKE. FURTHER, READ- ERS SHOULD BE AWARE THAT INTERNET WEBSITES LISTED IN THIS WORK MAY HAVE CHANGED OR DISAPPEARED BETWEEN WHEN THIS WORK WAS WRITTEN AND WHEN IT IS READ.
For general information on our other products and services or to obtain technical support, please contact our Cus- tomer Care Department within the U.S. at (800) 762-2974, outside the U.S. at (317) 572-3993 or fax (317) 572-4002.
Library of Congress Cataloging-in-Publication Data Professional Java JDK, 6 Edition / W. Clay Richardson ... [et al.].
p. cm. Includes index.
ISBN-13: 978-0-471-77710-6 (paper/website)
ISBN-10: 0-471-77710-2 (paper/website)
1. Java (Computer program language) I. Richardson, W. Clay, 1976- QA76.73.J38P7623 2007 005.13’3—dc22
2006032740
Trademarks:
Wiley and related trade dress are registered trademarks of Wiley Publishing, Inc., in the United States and other countries, and may not be used without written permission. All other trademarks are the property of their respective owners. Wiley Publishing, Inc., is not associated with any product or vendor mentioned in this book. Wiley also publishes its books in a variety of electronic formats. Some content that appears in print may not be available in electronic books.
This book is dedicated to all those who make the daily sacrifices,
especially those who have made the ultimate sacrifice, to ensure our
freedom and security. About the Authors
W. Clay Richardson is a software consultant concentrating on agile Java solutions for highly specialized
business processes. He has fielded many Java solutions, serving in roles including senior architect, development lead, and program manager. He is a co-author of More Java Pitfalls and Professional PortalDevelopment with Open Source Tools (Wiley), and Professional Java, JDK 5 Edition. As an adjunct professor
of computer science for Virginia Tech, Richardson teaches graduate-level coursework in object-oriented
development with Java. He holds degrees from Virginia Tech and the Virginia Military Institute.
Donald Avondolio currently serves in a lead position as an architect/developer on an enterprise devel-
opment project. In his spare time, Donald loves fly-fishing, watching baseball and lacrosse, running triathlons (not very well), and sitting around his house complaining about things.
Scot Schrager has consulted extensively in the domains of pharmaceuticals, supply chain management,
and the national security market. He has led and participated in various project teams using Java andObject Oriented Analysis & Design techniques. Most recently, Schrager has been focused on distributed
application architecture using J2EE technology.Mark W. Mitchell has extensive experience in enterprise application integration, particularly Web
Services integration between Java and the Microsoft platform. He has developed and deployed several
mission-critical web applications. Mitchell holds a degree in computer science from the University of Virginia.
Jeff Scanlon is a software development consultant from Virginia. He holds both the Sun Certified Java
Developer and Microsoft Certified Solutions Developer certifications, and has been published in Software
Development magazine.Credits
Acquisitions Editor Vice President and Executive Publisher
Robert Elliott Joseph B. Wikert Development Editor Project Coordinator Brian Herrmann Kristie Rees Technical Editor Graphics and Production Specialists David Parks Carrie A. FosterBrooke Gracyzk Production Editor Denny Hager Kathryn Duggan Joyce Haughey Barbara Moore Copy Editor Barry Offringa Kim Cofer Alicia B. South Ronald Terry Editorial Manager Quality Control Technicians Mary Beth Wakefield John Greenough Production Manager Charles Spencer Tim Tate Brian H. Walls
Vice President and Executive Group Publisher Proofreading and Indexing Richard Swadley Techbooks and Stephen Ingle Anniversary Logo Design Richard Pacifico
Contents Acknowledgments xv Introduction xvii
34 Java Logging
83 Think of Code as a Design, not a Product
82 Don’t Be Afraid to Write Code
82 Trace Your Actions to Need
81 Be Disciplined
81 Be Agile
81 Model
81 Communicate
80 Habits of Effective Software Development
79 Principles of Quality Software Development
77 Chapter 2: Tools and Techniques for Developing Java Solutions
70 Summary
35 Java Preferences
26 Important Java Utility Libraries
Part I: Thinking Like a Java Developer
24 Metadata
21 Enumerations
19 Static Imports
18 Boxing and Unboxing Conversions
17 Variable Arguments
16 Additions to the Java Class Library
7 Enhanced for Loop
7 Generics
4 Language Features Added in Java 5
3 Using Derby
3 Introducing Derby
1 Chapter 1: Key Java Language Features and Libraries
83 Contents Read a Lot
84 Build Your Process from the Ground Up
84 Manage Your Configuration
84 Unit Test Your Code
85 Continuously Integrate
85 Maintaining Short Iterations
86 Measure What You Accomplished — Indirectly
87 Track Your Issues
87 Development Methodology
88 Waterfall Methodology
88 Unified Process
90 Extreme Programming
91 Observations on Methodology
92 Practical Development Scenarios
93 Ant
93 Maven 2 101 TestNG 106
XDoclet 110 JMeter 117
Summary 120
Chapter 3: Exploiting Patterns in Java
123 Why Patterns Are Important
124 Keys to Understanding the Java Programming Language 124 Keys to Understanding Tools Used in Java Development 125 Keys to Developing Effective Java Solutions
126 Building Patterns with Design Principles
127 Designing a Single Class
127 Creating an Association between Classes 128 Creating an Interface 129 Creating an Inheritance Loop 129
Important Java Patterns 131
Adapter 131 Model-View-Controller 134 Command 142 Strategy 146 Composite 150
Summary 154 viii ix Contents
Part II: A Broad Understanding of Java APIs, Tools, and Techniques 155
Chapter 4: Developing Effective User Interfaces with JFC 157
Layout Managers 158BorderLayout 158 BoxLayout 164 FlowLayout 173 GridLayout 177 GridBagLayout 189 SpringLayout 194 CardLayout 202 GroupLayout 208
Mustang Release Desktop Enhancements 214 Managing Navigation Flows in Swing Applications 225 Summary
235
Chapter 5: Persisting Your Application Using Files 237
Application Data 237Saving Application Data 239 Sample Configuration Data Model for an Application 239
Java Serialization: Persisting Object Graphs 241 Key Classes
242 Serializing Your Objects 243 Extending and Customizing Serialization 257 When to Use Java Serialization 261
JavaBeans Long-Term Serialization: XMLEncoder/Decoder 262 Design Differences
262 Serializing Your JavaBeans 265 When to Use XMLEncoder/Decoder 269
Flexible XML Serialization: Java API for XML Binding (JAXB) 270 Sample XML Document for the Configuration Object 271 Defining Your XML Format with an XML Schema 273 JAXB API Key Classes
280 Marshalling and Unmarshalling XML Data 281 Creating New XML Content with JAXB-Generated Classes 283
Using JAXB-Generated Classes in Your Application 283 x Contents
Annotating Existing Java Classes for Use with JAXB 290 When to Use JAXB 307 Where JAXB Fits in the JDK 308
Summary 308
Chapter 6: Persisting Your Application Using Databases 311
JDBC API Overview 312 Setting Up Your Environment 313 JDBC API Usage in the Real World 313Understanding the Two-Tier Model 313 Understanding the Three-Tier Model 314
Effectively Using JDBC 4.0 315
Overview 315 Managing Connections 316 Understanding Statements 318 Utilizing Result Sets 328 Advanced Concepts 333
Hibernate 335
Hibernate Components 336 Hibernate Example 341
Summary 354
Chapter 7: Developing Web Applications Using the Model 1 Architecture 355
What Is Model 1? Why Use It? 356JSP 2.0 Overview 357 Integrated Expression Language (EL) 365 JSTL 1.1 Overview 366 Developing Your Web Application Visualizations with JSTL 1.1 370
Developing Your Web Application Visualizations with JSP 2.0 376 AJAX 381
Summary 391
Chapter 8: Developing Web Applications Using the Model 2 Architecture 393
The Problem 393 What Is Model 2? 393 Why Use Model 2? 395 Developing an Application with WebWork 396What Is Inversion of Control and Why Is it Useful? 397 Architecture 399 xi Contents
Extending the Framework to Support Hibernate 402 Preventing the Hanging Session 403 Defining Your Domain Model 405 Implementing Your Use Cases with Actions 412 Developing Your Views 415 Configuring Your Application 422 Adapting to Changes 424
Summary 426
Chapter 9: Interacting with C/C++ Using Java Native Interface 427
A First Look at Java Native Interface 427Creating the Java Code 428 Creating the Native Code and Library 429 Executing the Code 431
Java Native Interface 432
Data Types 432 Strings in JNI 432 Arrays in JNI 436 Working with Java Objects in C/C++ 442 Handling Java Exceptions in Native Code 449 Working with Object References in Native Code 451
Advanced Programming Using JNI 455
Developing an Email Client 460
System Design 460 User Interface 461
Summary 471
Chapter 10: EJB 3 and the Java Persistence API 473
New Features 474 Java Persistence API (JPA) 475Entities 475 Query Language 475 EntityManager 476 What Are Session Beans? The Demise of Entity Beans? 480
Interceptors 481 EJB 3 and Java Persistence API Web Component Examples 485
Summary 517 xii Contents
Chapter 11: Communicating between Java Components and Components of Other Platforms 519
564 Platform-Independent RPC 566
Processing Chain 619 Request-Reply 619 Split-Aggregate 621
System Integration Patterns 619
Why Is JMS Important? 610 Endpoints: Queues and Topics 610 Sending and Receiving Messages 611
Java Messaging Service 610
Why Is JMX Important? 601 The JMX Architecture 601 Creating and Managing a Standard MBean 602 JMX Management 606
Chapter 12: Service Oriented Integration 599
Service Oriented Architecture 599 Enabling Technology 600 Java Management Extensions 600Summary 597
563 Random-Weather.org
Component Communication Scenarios 520
553 Distributed File System Notifications: An Example CORBA System 554 Web Services
547 RMI-IIOP: Making RMI Compatible with CORBA 551 How to Turn an RMI Object into an RMI-IIOP Object 551 When to Use CORBA
Common Object Request Broker Architecture 547 CORBA Basics
Core RPC/RMI Principles 542
Remote Method Invocation 542
The Java Socket API 523 Implementing a Protocol 530
Overview of Interprocess Communication and Basic Network Architecture 521 Sockets 522
News Reader: Automated Web Browsing 520 A Bank Application: An EJB/Java EE Client 520 A Portal: Integrating Heterogeneous Data Sources and Services 521
Summary 623 xiii Contents
Chapter 13: Java Security 625
Exploring Web Applications 694
Installing Ant 709 Building Projects with Ant 710
Using Ant with Web Archives 709
Examining the TicTacToe Example 702 Summarizing Java Web Start 709
Jumping into Java Web Start 702
The EAR Descriptor File 700 Deployment Scenario 700
Packaging Enterprise JavaBeans 698 Inspecting Enterprise Archives 699
Examining the WAR Directory Structure 695 Understanding the WAR Deployment Descriptor 696
Basic Anatomy of an Applet 692 Packaging an Applet for Execution 693 Examining Applet Security 694
Java Cryptography Architecture and Java Cryptography Extension (JCA/JCE) 625 JCA Design and Architecture
Analyzing Applets 691
Examining the Basic Manifest File 684 Examining Applets and JARs 685 Signing JAR Files 686 Examining the JAR Index Option 690 Creating an Executable JAR 691
Chapter 14: Packaging and Deploying Your Java Applications 675
Examining Java Classpaths 675 Investigating the Endorsed Directory 680 Exploring Java Archives 681 Manipulating JAR Files 681Summary 673
User Identification 667 Executing Code with Security Checks 668 Authorization 672
Program Security Using JAAS 666
626 Java Cryptography Extension 656
Summary 713 Index 715
Acknowledgments First, I could not have had any chance of actually getting this book done without the support of my
wonderful wife, Alicia. She and my daughter Jennifer, who has far less sophisticated expectations of my
literary skills, are the joy in my life and I look forward to spending more time with them. I love both of
you more than words can describe. Stephanie, we love you and will never forget you. I would like to thank our technical editor, David Parks for the outstanding job he did on this project—you had NOIDEA what you were agreeing to do when I recruited you into this job! My fellow authors—Donnie,
Mark, Scot, and Jeff—have been terrific with their hard work on a demanding project. I appreciate each
of your contributions to this book. I would like to thank Bob Elliott and Brian Herrmann for all of their
hard work and perseverance while working with us on this project. I would like to acknowledge my leadership, Joe Duffy, Bruce Feldman, Jim Moorhead, Don Heginbotham, Jon Grasmeder, and AugieDunheimer, for their dedication to the simple concept of doing the right thing for the right people. It is
very refreshing to work at a company that exercises the inverse of the cynical “zero sum game.” I would
like to thank my parents, Bill and Kay, my in-laws, Stephen and Elaine Mellman, my sister Kari, my brother-in-law Grayson, my brother Morgan, and my stepfather Dave for always being there. I would like to acknowledge my grandmothers, Vivian and Sophie, for being what grandmothers should be.
I would also like to acknowledge my team members for the great things they do every day to make the
world a better place: Jon Simasek, Rob Brown, Keith Berman, Mauro Marcellino, Terry Trepel (welcome
back from Iraq!), Marshall Sayen, Joe Sayen, Hanchol Do, Scot Schrager, Don Avondolio, Brian Stearns, Cliff Toma, Mike Clarke, Brad Phillips, Jeff Lane, Nhon Pham, Julia Lee, Vic Fraenckel (welcome back
from the dead!), Morgan Ruther, Lonnie Haaland, George Burgin, and Mark (Mojo) Mitchell. Matt Tyrrell, I was going to write something witty or amusing, but I think Jennifer put it best, “What time is Uncle Matt coming over?”—WCR First, I’d like to thank these people for inspiring me in the workplace: Swati Gupta, Chi Louong, Bill Hickey, and Chiming Huang. Thanks to all of the great professors at the Virginia Tech Computer
Science/Information Technology Departments: Shawn Bohner, Tarun Sen, Stephen Edwards, and John
Viega. I am indebted to all of my students who taught me so much through their dedication, hard work, and insight, which has allowed me to incorporate their development wisdom for instruction in this
book. Appreciation goes out to the sponsors, volunteers, and organizers of The Great Cow Harbor Run (Northport, NY) and The Columbia Triathlon (Columbia, MD) for organizing world-class events I like to participate in, but more importantly for inspiring me to be a more disciplined and focused person. Special thanks to my friends, the Wieczoreks, Devaneys, Keanes, O’Donohoes, Howards, and Pujols. Lastly, I wish to thank all of the co-authors, who are fun guys to work with and be around: Jeff, Mark,
Scot, and Clay and my co-workers: Mauro Marcellino, Joe and Marshall Sayen, Jon Simasek, Terry Trepel and his wonder-dog Ontio, Hanchol Do, Keith Berman, Rob Brown, Dave Parks, Brian Stearns, Mike Clarke, Morgan Ruther, Cliff Toma, Matt Tyrrell, the Thoman family (Brettie-boy, Cindy, and baby
Zoe),Vic Fraenckel, Nhon Pham, Julia Lee, and to my fishing buddy George Burgin. To all of my family:
Mom, Dad, Michael, John, Patricia, Keil, Jim, Sue, Reenie, Donna, Kelly, Stephen, Emily, Jack, and Gillian,
Matt and Danielle, you guys are great. To my wife Van, whom I love more than anything for her continual support during the writing of this book.—DJA Acknowledgments
The first person I would like to thank is Heather. Seven years together and a wonderful eleven-month-
old son, you have made me the luckiest guy on earth. Thanks for saying, “I do.” I also need to thank myparents. First I’d like to thank my mom, because she has always been on my side, in support of me and
my decisions. And my dad, because he’s the kind of dad I’d like to one day become. I would also like
to thank my family who supported me; my sister and her family; Fern, Gary, and Isabel. In addition,
I would thank my extended family, Joe, Sabina, Robin, Peter, Brandon, Abby, Christiana, Joe Jr., Chris,
Ann, Paige, and Liam. I also need to thank my co-workers who make every day an experience. Clay,
thanks for providing the vision and drive to keep this work interesting. We are not in the one’s and
zero’s business, we solve problems. Don, thanks for putting up with me. Dave, thanks for putting up
with Don and me. Cliff, thanks for doing all the hard work, and please tell Gerry thanks too. I’d also like to thank Marty, Melinda, Brett, Mike, Mark, Terry, Mauro, Marshall, and Keith.—SRSI would like to first thank my wife, Elisa, for supporting me through this book. Projects like this always
seem like they will take less time than they actually do, and I thank her for supporting me through my
optimistic time estimates. I’d like to thank Clay for giving me the opportunity to write with him, and
Don for guiding me through it. I’d also like to thank our technical and development editors, Dave and
Brian, for helping me with my chapters. I would like to thank the people I have worked closely with
recently: Keith, Jeff, Jon, Terry, Nhon, Matt, Marshall, Joe, Brad, Carlton, Todd, Bryan, Hanchol, Vic, andeveryone I have worked with in the past. I have learned a lot simply through watching and listening.
There is no greater work atmosphere than the one where you are the least experienced—there is some-
thing to be learned from everyone every day. I’d like to thank my parents; my dad for sparking my inter-est in computer science, and my mom for helping me learn to write. Most of all I would like to thank
God, as writing this book has been an exercise in faith and trust. Last but not least I would like to thank
all of my family and friends for supporting me around book deadlines and understanding where all my time was going.—MWMThe following deserve acknowledgment: Dave Nelson for introducing me to programming and for
being the main reason I am where I am; my parents and family; our editors at Wiley, Brian Herrmann
and Robert Elliott; and Dave Parks, our technical reviewer. To my most important teachers: AlfredMartin and Paul D’Andrea. And finally, to Phil Bickel, Eric Anderton, John Tarcza, Keith Obenschain,
Robert Burtt, Joseph Kapp, Randy Nguyen, Leo Pak, Mark Orletsky, Randy Shine, David Hu, Min Soo Yi, and Corey Chang for their support.—JS xviIntroduction
Professional Java Programming provides a bridge from the “how to” language books that dominate the Java
space (Teach Yourself Hello World in Java in 24 Hours) and the more detailed, but technologically stove-pipedbooks on topics such as EJB, J2EE, JMX, JMS, and so on. Most development solutions involve using a mix
of technologies, and the books for all of these technologies would stand several feet tall. Furthermore, the
reader needs but a fraction of the overall content in these books to solve their specific problems. ProfessionalJava Programming provides background information on the technology, practical examples of using the
technology, and an explanation of where the reader could find more detailed information. It strives to be a
professional reference for the Java developer.Who This Book Is For This book serves three types of readers: The newly introduced reader who has graduated from Beginning Java, by covering more
❑ advanced Java solutions and language features.
The Java developer who needs a good all-purpose reference and a first source when tackling ❑ new Java problems that may be outside their technological experience.
The developer who has already had experience with certain solutions, but may not, for example, ❑ think it worthwhile to read 500 pages on JMS alone to see if JMS could fit into their solution space. This book can provide reduced barriers to technological entry for these developers.
What This Book Covers
Professional Java JDK 6 Edition builds upon Ivor Horton’s Beginning Java 2, to provide the reader with an
understanding of how professionals use Java to develop software solutions. It starts with a discussion of
the tools and techniques of the Java developer, continues with a discussion of the more sophisticated and nuanced parts of the Java SDK, and concludes with several examples of building real Java solutions using Java APIs and open source tools. Professional Java JDK 6 Edition leaves the reader with a well-rounded sur-
vey of the professional Java development landscape, without losing focus in exhaustive coverage of indi-
vidual APIs. This book is the bridge between Java language texts, methodology books, and specialized Java API books. For example, once you have mastered the basics of the Java language, you will invariably
encounter a problem, like building a database-driven web site, which requires you to use a collection of
technologies like JSP, and tools like Hibernate; this book provides a concrete solution that integrates both of them. The following figure provides a context to this book’s coverage in relation to other Java books. As you start with the beginning Java books, you would use this book as a solution primer to introduce you to more in-depth books on a particular subject, such as patterns, Web Services, or JDBC. Introduction Methodology, Patterns, and API Books
Professional Java
Development
Beginning Java Books Figure Intro-1 How This Book Is Str uctured
Working as an effective professional Java developer requires two major skills: thinking like a Java devel-
oper and having a broad understanding of Java APIs, tools, and techniques to solve a wide variety of
Java problems. Reviewing the structure of the book, you can see how the chapters help you realize the
goal of improving these skills.Part I: Thinking Like a Java Developer Experienced Java developers recognize that there is a particular mindset among effective Java developers. The first three chapters provide you with strong coverage of topics that will help you achieve that mindset. Chapter 1: Key Java Language Features and Libraries Any introductory Java book will cover the features of the Java programming language. This chapter
picks up where those books leave off by focusing on a number of the key sophisticated Java language
features such as regular expressions, preferences, and Java logging. Most importantly, this chapter intro-duces Derby, a lightweight database new to Java 6, and reviews language features that were introduced
in Java 2 Standard Edition 5.0. These features include generics, metadata, autoboxing, and more.Chapter 2: Tools and Techniques for Developing Java Solutions Making the jump from someone who knows the Java language to a Java developer is an interesting tran- sition. Typically, developers find books that teach the language and books that teach the methodologies.
xviii
Introduction Furthermore, methodology books are often written defensively, as if they are defending a dissertation or
prescribing a diet. These books often prescribe ritualistic adherence to their methodology, lest you risk
failure. New developers can find this approach quite exhausting, because rarely do you start in a posi-
tion where you can dictate a team’s process. In this book, you will find a developer’s focused view on
methodology and tools with practical insights into how to allow tools to make your work easier and
more productive.Chapter 3: Exploiting Patterns in Java Patterns provide an invaluable resource to developers in trying to communicate solutions to common problems. However, as software problems are generally very abstract, understanding common solutions to them—or even the value of the approach—can be a very overwhelming experience.
However, as you might imagine, there are some key problems that recur throughout the Java solution
space, and therefore, frameworks and APIs are built upon patterns. As such, having a utilitarian under-
standing of patterns is invaluable, and arguably unavoidable in becoming an effective Java developer.
This chapter explains the critical importance of patterns, provides a practical understanding of patterns,
and demonstrates examples of common patterns found in the Java world.Part II: A Broad Understanding of Java APIs, Tools, and Techniques
The Java platform has extended beyond being a simple applet development language at its inception to
three distinct editions targeted at three different platforms. Not only has the platform evolved into a
huge undertaking, but the open source movement and the Java community have also added features
and tools that provide even more options to the Java developer. Therefore, you can find yourself easily overwhelmed. This part of the book provides a series of commonproblems across the Java development space. In each area, you will be introduced to a problem, and a
focused solution to that problem. These solutions do not attempt to provide comprehensive coverage of
all of the involved APIs, but rather a primer needed to solve that problem. From there, you could bridgeinto a book with more specialized coverage. The primary intent is to not require a three-foot tall stack of
books to address a simple end-to-end solution to a common development problem.Chapter 4: Developing Effective User Interfaces with JFC Commonly referred to simply as Swing, the Java Foundation Classes provide the functionality to build
user interfaces and desktop applications. As these classes frequently make up most of the logical exam-
ples within introductory Java books, it makes logical sense to start with a Swing example. However, this chapter covers the intricacies of Swing in more detail, including some advanced topics like Layout Managers and Java 2D.Chapter 5: Persisting Your Application Using Files One of the more important things for any application to be able to do is persist (that is, save) its state. In
this chapter, you will discover techniques to implement save and restore functionality, using two differ- ent methods, Java object serialization and the Java API for XML Binding (JAXB). xix Introduction
Chapter 6: Persisting Your Application Using Databases Files are traditionally used to share data in a single-threaded mode—one user at a time. When data must
be shared throughout the enterprise, you use a database. In this chapter, you learn the more advanced
features of the Java Database Connectivity API (JDBC) 4.0. Furthermore, this chapter addresses one of
the more popular object persistence frameworks (and the foundation for the development of the new
EJB 3.0 specification)—Hibernate.Chapter 7: Developing Web Applications Using the Model 1 Architecture Those who have been developing web applications for a long time recognize that the page-centric paradigm,
also known as the Model 1 Architecture, has been used across many technology platforms (ASP, Cold
Fusion, Perl, and so on) to develop web applications. Java supports this paradigm through its Java Server
Pages and Java Standard Tag Library specifications. In this chapter, you learn about these frameworks as
well as other best practices in developing web applications within the Model 1 Architecture.Chapter 8: Developing Web Applications Using the Model 2 Architecture As web applications have evolved, there has been recognition of some weaknesses in the page-centric
approach of the Model 1 Architecture. In this chapter, you learn about these weaknesses and how they
gave rise to the Model 2 Architecture, which is component-centric. You will see how using a component
framework like WebWork allows for easy integration of other components like Hibernate.Chapter 9: Interacting with C/C++ Using Java Native Interface Frequently, you have application components that are regrettably not written in the Java programming
language, often not alleviating the need for those components to be accessible by your application. The
solution to this problem is the Java Native Interface. This chapter explains the intricacies of JNI, as well
as a number of the potential pitfalls.Chapter 10: EJB 3 and the Java Persistence API Enterprise JavaBeans (EJB) is Java’s distributed component technology and the cornerstone of the Java 2
Enterprise Edition platform. EJB 3.0 represents a significant improvement in the Java language by lever-
aging the Plain Old Java Object (POJO) paradigm with the Java Persistence API to provide reliable,
robust, and transparent object persistence. This chapter explains the EJB 3 specification and the Java
Persistence API and demonstrates their utility to developing enterprise Java solutions.Chapter 11: Communicating between Java Components and Components of Other Platforms
While RMI has proven to be a good solution for Java-to-Java communication, there are still a tremen-
dous number of needs to access (or provide access to) components of other platforms. This is particu-
larly true of the Microsoft .NET platform. This chapter explains the basics of interprocesscommunication, discusses several techniques for interprocess communication, and culminates in an
example using Web Services. xxIntroduction
Chapter 12: Service Oriented Integration When performing enterprise application integration of components distributed across many machines
and platforms, it is often necessary for you to be able to spread the workload across many different
steps. There are two APIs that are particularly useful in this regard, the Java Message Service (JMS) and
the Java Management Extensions (JMX). In this chapter, you see the core of these two APIs tied together
to provide a highly useful architecture.Chapter 13: Java Security Information security is tremendously important to Java development. In this chapter, you see how your
application can be secured using the Java Authorization and Authentication Service (JAAS) and your
data can be secured using the Java Cryptography Extensions (JCE). Also detailed in this chapter is the
new XML digital signature support introduced in Java 6, useful in building security for Web Services.
Chapter 14: Packaging and Deploying Your Java Applications One of the trickiest and most painful things about developing Java applications, whether they are enterprise or desktop applications, is packaging and deploying your application. There are a multitude of deployment
descriptors and packaging rules that exist in many of the Java APIs. There are JARs, WARs, EARs, and
more on the way. Often you get cursory understanding of these formats and specifications within each of
the stovepipe books. In this chapter, you learn about a number of the packaging mechanisms that exist in
Java, as well as descriptions of the deployment descriptors for each of those mechanisms.What You Need to Use This Book This book is based upon Java 2 Standard Edition version 6.0. You might find it helpful to have an Integrated Development Environment (IDE) of your choice—Eclipse is a very good and popular one
( www.eclipse.org ). Furthermore, depending on the chapter, you may need to use an application server
like JBoss ( www.jboss.org ) or Tomcat ( http://jakarta.apache.org/tomcat ). The need to download
an application server, as well as any other downloads (of APIs and so on), is addressed in each chapter.
Conventions To help you get the most from the text and keep track of what’s happening, a number of conventions are used throughout the book.
Boxes like this one hold important, not-to-be forgotten information that is directly relevant to the surrounding text.
Tips, hints, tricks, and asides to the current discussion are offset and placed in italics like this. xxi Introduction As for styles in the text, the following are standard for the book: ❑ Important words are highlighted when they are introduced.
❑ Keyboard strokes are shown like this: Ctrl+A. ❑ File names, URLs, and code within the text are like so: persistence.properties . ❑ Code is presented in two different ways: In code examples, new and important code is highlighted with a gray background.
The gray highlighting is not used for code that’s less important in the present context, or has been shown before.
Source Code As you work through the examples in this book, you may choose either to type in all the code manually or to use the source code files that accompany the book. All of the source code used in this book is avail-
able for download at www.wrox.com . Once at the site, simply locate the book’s title (either by using the
Search box or by using one of the title lists) and click the Download Code link on the book’s detail page
to obtain all the source code for the book.Because many books have similar titles, you may find it easiest to search by ISBN; for this book the ISBN is 978-0-471-77710-6.
Once you download the code, just decompress it with your favorite compression tool. Alternatively, you
can go to the main Wrox code download page at www.wrox.com/dynamic/books/download.aspx to
see the code available for this book and all other Wrox books.Errata We make every effort to ensure that there are no errors in the text or in the code. However, no one is per-
fect, and mistakes do occur. If you find an error in one of our books, like a spelling mistake or faulty
piece of code, we would be very grateful for your feedback. By sending in errata you may save another
reader hours of frustration and at the same time you will be helping us provide even higher quality
information.To find the errata page for this book, go to www.wrox.com and locate the title using the Search box or
one of the title lists. Then, on the book details page, click the Book Errata link. On this page you can view all errata that has been submitted for this book and posted by Wrox editors. A complete book list includ-ing links to each book’s errata is also available at www.wrox.com/misc-pages/booklist.shtml .
If you don’t spot the error you are experiencing on the Book Errata page, go to www.wrox.com/contact/
techsupport.shtml and complete the form there to send us the error you have found. We’ll check the
information and, if appropriate, post a message to the book’s errata page and fix the problem in subse-
quent editions of the book. xxiiIntroduction p2p.wrox.com
For author and peer discussion, join the P2P forums at http://p2p.wrox.com . The forums are a web-
based system for you to post messages relating to Wrox books and related technologies and interact with other readers and technology users. The forums offer a subscription feature to e-mail you topics of inter-est of your choosing when new posts are made to the forums. Wrox authors, editors, other industry
experts, and your fellow readers are present on these forums.At http://p2p.wrox.com you will find a number of different forums that will help you not only as you
read this book, but also as you develop your own applications. To join the forums, just follow these steps:
1. Go to p2p.wrox.com and click the Register link.
Read the terms of use and click Agree.
2.
3. Complete the required information to join as well as any optional information you wish to pro- vide and click Submit.
You will receive an e-mail with information describing how to verify your account and com- 4. plete the registration process.
You can read messages in the forums without joining P2P, but to post your own messages, you must join.
Once you join, you can post new messages and respond to messages other users post. You can read mes-sages at any time on the Web. If you would like to have new messages from a particular forum e-mailed
to you, click the Subscribe to this Forum icon by the forum name in the forum listing. For more information about how to use the Wrox P2P, be sure to read the P2P FAQs for answers to ques- tions about how the forum software works as well as many common questions specific to P2P and Wrox books. To read the FAQs, click the FAQ link on any P2P page. xxiiiPart I: Thinking Like a Java Developer Chapter 1: Key Java Language Features and Libraries Chapter 2: Tools and Techniques for Developing Java Solutions Chapter 3: Exploiting Patterns in Java
Key Java Language Features and Libraries
The past two major releases of the JDK have seen some significant changes. JDK 5 introduced new
features at the language level, something that has not happened since Java was first released.Some of the most significant features added to the language are generics (parameterized types),
enumerations, and metadata. With JDK 6, one of the biggest changes is the inclusion of a lightweight database known as Derby, which is from the Apache Database project.The first half of this chapter introduces Derby and reviews the new language features from JDK 5.
The second half of this chapter details certain key utility packages in the branch of the
java.util class library that are useful for professional programming in Java.
Introducing Derby
New to Java 6 is a lightweight database called Derby, a product of the Apache Database project.
Derby is a transactional, relational database and provides a small footprint on disk. As of the July
13, 2006 release of the Java 6 JDK, Derby is installed (by default) inC:\Program Files\Java\ and includes the core libraries, demonstration programs, and an example database. jdk1.6.0\db
Derby started its life as CloudScape, a product IBM acquired with Informix. In 2004, IBM decided
to open source CloudScape and it became an incubator project under the Apache SoftwareFoundation with the name Derby. The real benefits to using Derby are that it has minimal adminis-
tration needs and a small footprint. The databases are small on disk, roughly 2MB for a basicdatabase. The fact that administration is minimal allows you, as a developer, to easily create and
use databases in code. This speeds up development. Deployment is made that much easierbecause Derby supports storage of a database archived in a JAR file, allowing you to simply dis-
tribute the JAR file.