Professional Java.JDK.5.Edition (Wrox)
.pdfAcknowledgments
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 from 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. My fellow authors—Donnie, Mark, Scot, Jeff, and Joe—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 Eileen Bien Calabro for all of their hard work and perseverance working with us on this project. I would like to acknowledge my leadership, Joe Duffy, Jim Moorhead, Don Heginbotham, Tom Eger, Mark Cramer, Jon Grasmeder, and Doug Dillingham, 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 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, Marshall Sayen, Joe Sayen, Hanchol Do, Greg Scheyer, Scot Schrager, Don Avondolio, and Mark (Mojo) Mitchell. To my duty crew at the Gainesville District VFD: Bob Nowlen, Gary Sprifke, Patrick Vaughn, Seth Bowie, Matt Tyrrell, and Gerry Clemente—we have been through a lot together! To Kevin Smith, I think you were smart to pass on writing to spend more time with Isabella—I think I will do the same with Jennifer. Matt Tyrrell, I thought about giving you a hard time again this time around but decided not to tempt fate too much, so I will just remark the obvious—you are still like a brother to me.—WCR
First, I’d like to thank all of my BV pals: Wendong Wang, Arun Singh, Shawn Sherman, Henry Zhang, Bin Li, Feng Peng, Henry Chang., Sanath Shetty, Prabahkar Ramakrishnan, Yuanlin Shi, Andy Zhang, and John Zhang. Additionally, I’d also 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 with 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 and organizers of The Great Cow Harbor Run (Northport, New York) and The Columbia Triathlon (Columbia, Maryland) for organizing world-class events I like to participate in, but more importantly for inspiring me to be a more disciplined and focused person.
Finally, I wish to thank all of the coauthors, who are fun guys to work with and be around: Joe, Jeff, Mark, Scot, and Clay; and my co-workers: Mauro Marcellino, Joe and Marshall Sayen, Jon Simasek, Terry Trepel, Hanchol Do, Keith Berman, and Rob Brown. To all of my family: Mom, Dad, Michael, John, Patricia, Kiel, Jim, Sue, Reenie, Donna, Kelly, Stephen, Emily, Jack, and Gillian, Matt and Danielle, you guys are great. To my wife Van, who I love more than anything for her continual support during the writing of this book.—DJA
Acknowledgments
First, I’d like to thank my wife Jennifer Vitale and my son Andrew. They have been so supportive throughout my book-writing adventures, and without their encouragement I would not have found the time or energy to complete this task. I’d also like to thank my grandfather and grandmother Carlo and Annette Vitale, as well as my father Joseph Vitale, my stepmother Linda Vitale, and my fatherand mother-in-law James and Marlaine Moore. Many thanks also go to John Carver, Brandon Vient, and Aron Lee for their great supporting roles as friends. Finally, I’d like to thank all of my co-workers at McDonald Bradley, including Kyle Rice, Danny Proko, Joe Broussard, Rebecca Smith, Joe Cook, Ken Pratt, Adam Dean, Joon Lee, Adam Silver, John Johnson, Keith Bohnenberger, Bill Vitucci, Barry Edmond, Arnold Voketaitis, Steven Brockman, Peter Len, Ken Bartee, Dave Shuping, John Sutton, William Babilon, and many others who have been very supportive. And a special thanks goes to my coauthors for all of their hard work and encouragement. Thank you all!—JV
I would like to dedicate my contribution of this book to the memory of my father. My biggest fan—I know he would have put a copy of this book in the hand of everyone he knew. I appreciate the opportunities I have had as the result of the hard work and sacrifice of both of my parents.
I would like to thank my colleagues for helping me be part of this book. I would especially like to thank Clay and Donnie for their guidance. You make the very difficult seem easy.
This was my first participation in a technical book. I would like to thank my beautiful wife, Heather, for helping me stay the course. I could not have done it without you.
I would also like to thank Don Schaefer. It has been a privilege to work with you. You have taught me several lessons firsthand on leadership, professionalism, and conviction. I learned from you that the quality of a person’s ideas should be judged independent of their position in a company.
One of my early mentors was my high school computer science teacher, Mr. John Nadig. I remember specifically having some trouble with an assignment. Instead of just telling me the correct answer, he handed me a thick reference book and said with confidence, “I’m sure you will find the answer in here.” Thank you for getting me hooked on solving problems; I have been using that approach ever since.—SRS
I would like to thank my parents: my mother for teaching me how to write and showing me by her example how to work diligently and persistently through any problem and my father for introducing me to computer science and programming very early in my life. I would sit by his side and watch him program and through his patience learned quite a bit—sparking my interest for what would later become my career. I would like to thank the people I work with right now, and whom 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 senior—there is something to be learned from everyone, each and every day of the week. I would like to thank my friends for understanding why I was always busy around book deadlines and for continuing to support me even as I became a hermit. Most of all I would like to thank God, as writing this book has been an exercise in faith and trust. Last, but certainly not least, I would like to thank my ever-loving and supporting fiancée, without whose support I certainly would not have been able to complete my chapters. Thank you for planning our wedding and for being patient with me during my many hours of writing. I promise I will spend more time with the wedding planning!—MWM
I would like to thank the people who made this book possible: Dave Nelson for introducing me to the world of software development and for being my long-standing friend; Joe Vitale for his friendship and
x
Acknowledgments
involving me with this book; and Eileen Bien Calabro for working with us as a developmental editor, helping to ensure that this book succeeds. I would also like to thank those who offer their support and belief in me—my parents, my family, Phil Bickel, Eric Anderton, John Tarcza, Joseph Kapp, Mark Orletsky, Gwynne Sayres, Keith Obenschain, Robert Burtt, Myke Weiskopf, Randy Nguyen, Randy Shine, James Kwon, David Hu, Sung Kwak, Tim Weber, Bobby Suh, Albert Young, Jacob Kim, and a few others I am sure I am forgetting who stand by me.—JS
xi
Contents
Acknowledgments |
ix |
Introduction |
xxv |
Chapter 1: Key Java Language Features and Libraries |
1 |
New Language Features |
1 |
Generics |
2 |
Generic Types and Defining Generic Classes |
3 |
Using Generics |
5 |
Enhanced for Loop |
7 |
Additions to the Java Class Library |
8 |
Variable Arguments |
9 |
Boxing/Unboxing Conversions |
11 |
Unboxing Conversions |
12 |
Valid Contexts for Boxing/Unboxing Conversions |
12 |
Static Imports |
13 |
Enumerations |
15 |
Meta data |
17 |
AnnotationDesc |
20 |
AnnotationDesc.ElementValuePair |
21 |
AnnotationTypeDoc |
21 |
AnnotationTypeElementDoc |
21 |
AnnotationValue |
22 |
Important Java Utility Libraries |
26 |
Java Logging |
26 |
The Log Manager |
28 |
The Logger Class |
30 |
The LogRecord Class |
34 |
The Level Class |
37 |
The Handler Class |
38 |
The Formatter Class |
44 |
Stock Formatters |
45 |
The Filter Interface |
48 |
The ErrorManager |
49 |
Logging Examples |
49 |
Regular Expressions |
53 |
The Pattern Class |
58 |
Contents
The Matcher Class |
59 |
The MatchResult Interface |
61 |
Regular Expression Example |
61 |
Java Preferences |
63 |
The Preference Class |
63 |
Exporting to XML |
68 |
Using Preferences |
69 |
Summary |
71 |
Chapter 2: Tools and Techniques for Developing Java Solutions |
73 |
Principles of Quality Software Development |
74 |
Habits of Effective Software Development |
75 |
Communicate |
75 |
Model |
75 |
Be Agile |
75 |
Be Disciplined |
76 |
Trace Your Actions to Need |
76 |
Don’t Be Afraid to Write Code |
77 |
Think of Code as a Design, not a Product |
77 |
Read a LOT! |
78 |
Build Your Process from the Ground Up |
78 |
Manage Your Configuration |
78 |
Unit Test Your Code |
79 |
Continuously Integrate |
79 |
Maintaining Short Iterations |
79 |
Measure What You Accomplished — Indirectly |
80 |
Track Your Issues |
81 |
Development Methodology |
82 |
Waterfall Methodology |
82 |
Unified Process |
83 |
eXtreme Programming |
85 |
Observations on Methodology |
86 |
Practical Development Scenarios |
87 |
Ant |
87 |
Scenario 1 |
88 |
Scenario 2 |
90 |
Scenario 3 |
94 |
Maven |
95 |
JUnit |
98 |
XDoclet |
101 |
JMeter |
107 |
Summary |
109 |
xiv
|
Contents |
Chapter 3: Exploiting Patterns in Java |
111 |
Why Patterns Are Important |
112 |
Keys to Understanding the Java Programming Language |
112 |
Keys to Understanding Tools Used in Java Development |
113 |
ANT |
113 |
JUnit |
113 |
XDoclet |
113 |
Keys to Developing Effective Java Solutions |
113 |
Develop Common Design Vocabulary |
114 |
Understand the Fundamentals of Design |
114 |
Building Patterns with Design Principles |
115 |
Designing a Single Class |
115 |
Creating an Association between Classes |
115 |
Creating an Interface |
117 |
Creating an Inheritance Loop |
117 |
Important Java Patterns |
119 |
Adapter |
119 |
The Adapter Pattern Is a Collaboration of Four Classes |
120 |
Client |
120 |
Adaptee |
121 |
Adapter |
121 |
Model-View-Controller |
122 |
Scenario 1: Changing to the Model |
123 |
Scenario 2: Refreshing When the Model Changes |
123 |
Scenario 3: Initializing the Application |
124 |
Model |
124 |
View |
125 |
Controller |
128 |
Command |
130 |
Command |
130 |
CommandManager |
131 |
Invoker |
131 |
Strategy |
134 |
Strategy |
135 |
Context |
137 |
Composite |
138 |
Component |
139 |
Leaf |
139 |
Composite |
140 |
Summary |
142 |
xv
Contents
Chapter 4: Developing Effective User Interfaces with JFC |
143 |
Layout Managers |
144 |
BorderLayout |
144 |
BoxLayout |
151 |
FlowLayout |
161 |
GridLayout |
167 |
GridBagLayout |
177 |
SpringLayout |
183 |
CardLayout |
191 |
JFrame and JDialog Components |
197 |
Managing Navigation Flows in Swing Applications |
214 |
Summary |
221 |
Chapter 5: Persisting Your Application Using Files |
223 |
Application Data |
224 |
Saving Application Data |
225 |
A Configuration Data Model for the Imager Application |
225 |
Java Serialization: Persisting Object Graphs |
228 |
Key Classes |
229 |
Serializing Your Objects |
229 |
Configuration Example: Saving Your App’s Configuration to Disk |
230 |
Giving Your Application a Time-based License Using Serialization |
235 |
Implementing the License |
236 |
Implementing the Timeserver |
238 |
Tying Your Serialization Components into the Application |
239 |
Extending and Customizing Serialization |
243 |
The Transient Keyword |
243 |
Customizing the Serialization Format |
243 |
Versioning |
245 |
When to Use Java Serialization |
247 |
Java Beans Long-Term Serialization: XMLEncoder/Decoder |
248 |
Design Differences |
248 |
XML: The Serialization Format |
249 |
Key Classes |
250 |
Serializing Your Java Beans |
251 |
Robustness Demonstrated: Changing Configuration’s Internal Data |
252 |
Possible Customization |
254 |
Persistence Delegates |
255 |
When to Use XMLEncoder/Decoder |
255 |
xvi
|
Contents |
XML Schema-Based Serialization: Java API for XML Binding (JAXB) |
256 |
Sample XML Document for Your Configuration Object |
257 |
Defining Your XML Format with an XML Schema |
259 |
Defining Your Data: Configuration.xsd |
260 |
Generating JAXB Java Classes from Your Schema |
263 |
Generated JAXB Object Graphs |
265 |
JAXB API Key Classes |
269 |
Marshalling and Unmarshalling XML Data |
269 |
Creating New XML Content with JAXB-Generated Classes |
270 |
Using JAXB-Generated Classes in Your Application |
271 |
Implementing Your Save Action |
273 |
Implementing Your Load Action |
275 |
When to Use JAXB |
278 |
Future Direction of JAXB 2.0 |
279 |
Summary |
279 |
Chapter 6: Persisting Your Application Using Databases |
281 |
JDBC API Overview |
281 |
Setting Up Your Environment |
283 |
JDBC API Usage in the Real World |
283 |
Understanding the Two-Tier Model |
283 |
Understanding the Three-Tier Model |
284 |
Grasping JDBC API Concepts |
285 |
Managing Connections |
286 |
DriverManager Class |
286 |
DataSource Interface |
286 |
Understanding Statements |
287 |
Investigating the Statement Interface |
288 |
Exploring the PreparedStatement Interface |
289 |
Exploring the CallableStatement Interface |
292 |
Utilizing Batch Updates |
294 |
Utilizing Result Sets |
298 |
Investigating Types of Result Sets |
298 |
Setting Concurrency of Result Sets |
298 |
Setting Holdability of Result Sets |
299 |
Using Result Sets |
299 |
Examining JDBC Advanced Concepts |
302 |
Managing Database Meta Data |
302 |
Discovering Limitations of a Data Source |
303 |
Determining Which Features a Data Source Supports |
303 |
Retrieving General Information about a Data Source |
304 |
xvii