Acknowledgments xv Introduction xvii Part I: Thinking Like a Java Developer 1 Chapter 1: Key Java Language Features and Libraries 3 Introducing Derby 3 Language Features Added in Java 5
Trang 2W Clay Richardson, Donald Avondolio, Scot Schrager,
Mark W Mitchell, and Jeff Scanlon
Trang 3Professional Java, ® JDK ® 6 Edition
Copyright © 2007 by Wiley Publishing, Inc., Indianapolis, Indiana
Published simultaneously in Canada
LIMIT OF LIABILITY/DISCLAIMER OF WARRANTY:THE PUBLISHER AND THE AUTHOR MAKE NO RESENTATIONS OR WARRANTIES WITH RESPECT TO THE ACCURACY OR COMPLETENESS OF THE CON-TENTS OF THIS WORK AND SPECIFICALLY DISCLAIM ALL WARRANTIES, INCLUDING WITHOUTLIMITATION WARRANTIES OF FITNESS FOR A PARTICULAR PURPOSE NO WARRANTY MAY BE CREATED
REP-OR EXTENDED BY SALES REP-OR PROMOTIONAL MATERIALS THE ADVICE AND STRATEGIES CONTAINEDHEREIN 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 COMPETENTPROFESSIONAL PERSON SHOULD BE SOUGHT NEITHER THE PUBLISHER NOR THE AUTHOR SHALL BELIABLE FOR DAMAGES ARISING HEREFROM THE FACT THAT AN ORGANIZATION OR WEBSITE ISREFERRED 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 THEORGANIZATION 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 ORDISAPPEARED 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 tomer Care Department within the U.S at (800) 762-2974, outside the U.S at (317) 572-3993 or fax (317) 572-4002
Cus-Library of Congress Cataloging-in-Publication Data
Professional Java JDK, 6 Edition / W Clay Richardson [et al.]
Trang 4This 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.
Trang 5About the Authors
W Clay Richardsonis a software consultant concentrating on agile Java solutions for highly specializedbusiness 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 Portal
Development 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-orienteddevelopment with Java He holds degrees from Virginia Tech and the Virginia Military Institute
Donald Avondoliocurrently serves in a lead position as an architect/developer on an enterprise opment project In his spare time, Donald loves fly-fishing, watching baseball and lacrosse, runningtriathlons (not very well), and sitting around his house complaining about things
devel-Scot Schragerhas 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 distributedapplication architecture using J2EE technology
Mark W Mitchellhas extensive experience in enterprise application integration, particularly WebServices integration between Java and the Microsoft platform He has developed and deployed severalmission-critical web applications Mitchell holds a degree in computer science from the University ofVirginia
Jeff Scanlonis 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.
Trang 6Quality Control Technicians
John GreenoughCharles SpencerBrian H Walls
Proofreading and Indexing
Techbooks and Stephen Ingle
Anniversary Logo Design
Richard Pacifico
Trang 8Acknowledgments xv Introduction xvii
Part I: Thinking Like a Java Developer 1
Chapter 1: Key Java Language Features and Libraries 3
Introducing Derby 3
Language Features Added in Java 5 7
Chapter 2: Tools and Techniques for Developing Java Solutions 79
Principles of Quality Software Development 80 Habits of Effective Software Development 81
Trang 9Contents
Measure What You Accomplished — Indirectly 87
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
Important Java Patterns 131
Trang 10Contents
Part II: A Broad Understanding of Java APIs,
Chapter 4: Developing Effective User Interfaces with JFC 157
Sample Configuration Data Model for an Application 239
Java Serialization: Persisting Object Graphs 241
JavaBeans Long-Term Serialization: XMLEncoder/Decoder 262
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
Creating New XML Content with JAXB-Generated Classes 283 Using JAXB-Generated Classes in Your Application 283
Trang 11Contents
Annotating Existing Java Classes for Use with JAXB 290
Chapter 6: Persisting Your Application Using Databases 311
JDBC API Overview 312 Setting Up Your Environment 313 JDBC API Usage in the Real World 313
Chapter 7: Developing Web Applications Using the Model 1 Architecture 355
What Is Model 1? Why Use It? 356
What Is Inversion of Control and Why Is it Useful? 397
Trang 12Contents
Extending the Framework to Support Hibernate 402
Implementing Your Use Cases with Actions 412
Chapter 9: Interacting with C/C++ Using Java Native Interface 427
A First Look at Java Native Interface 427
Java Native Interface 432
Working with Object References in Native Code 451
Developing an Email Client 460
Trang 13Contents
Chapter 11: Communicating between Java Components and
Component Communication Scenarios 520
A Bank Application: An EJB/Java EE Client 520
A Portal: Integrating Heterogeneous Data Sources and Services 521
Overview of Interprocess Communication and Basic Network Architecture 521
Remote Method Invocation 542
Common Object Request Broker Architecture 547
RMI-IIOP: Making RMI Compatible with CORBA 551 How to Turn an RMI Object into an RMI-IIOP Object 551
Distributed File System Notifications: An Example CORBA System 554
Service Oriented Architecture 599 Enabling Technology 600 Java Management Extensions 600
System Integration Patterns 619
Trang 14Contents
Java Cryptography Architecture and Java Cryptography Extension (JCA/JCE) 625
Program Security Using JAAS 666
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 681
Analyzing Applets 691
Exploring Web Applications 694
Understanding the WAR Deployment Descriptor 696
Packaging Enterprise JavaBeans 698 Inspecting Enterprise Archives 699
Jumping into Java Web Start 702
Using Ant with Web Archives 709
Trang 16First, I could not have had any chance of actually getting this book done without the support of mywonderful wife, Alicia She and my daughter Jennifer, who has far less sophisticated expectations of myliterary skills, are the joy in my life and I look forward to spending more time with them I love both ofyou more than words can describe Stephanie, we love you and will never forget you I would like tothank 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 theirhard work and perseverance while working with us on this project I would like to acknowledge myleadership, 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 isvery refreshing to work at a company that exercises the inverse of the cynical “zero sum game.” I wouldlike to thank my parents, Bill and Kay, my in-laws, Stephen and Elaine Mellman, my sister Kari, mybrother-in-law Grayson, my brother Morgan, and my stepfather Dave for always being there I wouldlike 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 theworld a better place: Jon Simasek, Rob Brown, Keith Berman, Mauro Marcellino, Terry Trepel (welcomeback 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 backfrom 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 UncleMatt 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 ComputerScience/Information Technology Departments: Shawn Bohner, Tarun Sen, Stephen Edwards, and JohnViega 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 thisbook 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 Trepeland his wonder-dog Ontio, Hanchol Do, Keith Berman, Rob Brown, Dave Parks, Brian Stearns, MikeClarke, Morgan Ruther, Cliff Toma, Matt Tyrrell, the Thoman family (Brettie-boy, Cindy, and babyZoe),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 continualsupport during the writing of this book.—DJA
Trang 17Acknowledgments
The first person I would like to thank is Heather Seven years together and a wonderful 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
eleven-month-my decisions And eleven-month-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 andzero’s business, we solve problems Don, thanks for putting up with me Dave, thanks for putting upwith 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.—SRS
I would like to first thank my wife, Elisa, for supporting me through this book Projects like this alwaysseem like they will take less time than they actually do, and I thank her for supporting me through myoptimistic time estimates I’d like to thank Clay for giving me the opportunity to write with him, andDon for guiding me through it I’d also like to thank our technical and development editors, Dave andBrian, for helping me with my chapters I would like to thank the people I have worked closely withrecently: 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 thankGod, as writing this book has been an exercise in faith and trust Last but not least I would like to thankall of my family and friends for supporting me around book deadlines and understanding where all mytime was going.—MWM
The following deserve acknowledgment: Dave Nelson for introducing me to programming and forbeing the main reason I am where I am; my parents and family; our editors at Wiley, Brian Herrmannand 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
Trang 18Professional 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-piped
books 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 Professional
Java 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 aprofessional 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 tacklingnew 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 solutionspace 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 ofthe tools and techniques of the Java developer, continues with a discussion of the more sophisticated andnuanced 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 vidual APIs This book is the bridge between Java language texts, methodology books, and specializedJava API books For example, once you have mastered the basics of the Java language, you will invariablyencounter a problem, like building a database-driven web site, which requires you to use a collection oftechnologies like JSP, and tools like Hibernate; this book provides a concrete solution that integrates both
indi-of them The following figure provides a context to this book’s coverage in relation to other Java books Asyou start with the beginning Java books, you would use this book as a solution primer to introduce you tomore in-depth books on a particular subject, such as patterns, Web Services, or JDBC
Trang 19Introduction
Figure Intro-1
How This Book Is Str uctured
Working as an effective professional Java developer requires two major skills: thinking like a Java oper and having a broad understanding of Java APIs, tools, and techniques to solve a wide variety ofJava problems Reviewing the structure of the book, you can see how the chapters help you realize thegoal of improving these skills
devel-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 chapterpicks up where those books leave off by focusing on a number of the key sophisticated Java languagefeatures 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 sition Typically, developers find books that teach the language and books that teach the methodologies
tran-Methodology, Patterns, and API Books
Beginning Java Books
ProfessionalJavaDevelopment
Trang 20Introduction
Furthermore, methodology books are often written defensively, as if they are defending a dissertation orprescribing a diet These books often prescribe ritualistic adherence to their methodology, lest you riskfailure 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 onmethodology and tools with practical insights into how to allow tools to make your work easier andmore productive
Chapter 3: Exploiting Patterns in Java
Patterns provide an invaluable resource to developers in trying to communicate solutions to commonproblems 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 solutionspace, 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 tothree distinct editions targeted at three different platforms Not only has the platform evolved into ahuge undertaking, but the open source movement and the Java community have also added featuresand 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 afocused solution to that problem These solutions do not attempt to provide comprehensive coverage ofall 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 ofbooks 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 builduser 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, thischapter covers the intricacies of Swing in more detail, including some advanced topics like LayoutManagers 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 Inthis 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)
Trang 21Introduction
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 advancedfeatures of the Java Database Connectivity API (JDBC) 4.0 Furthermore, this chapter addresses one ofthe more popular object persistence frameworks (and the foundation for the development of the newEJB 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, ColdFusion, Perl, and so on) to develop web applications Java supports this paradigm through its Java ServerPages and Java Standard Tag Library specifications In this chapter, you learn about these frameworks aswell 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-centricapproach of the Model 1 Architecture In this chapter, you learn about these weaknesses and how theygave rise to the Model 2 Architecture, which is component-centric You will see how using a componentframework 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 programminglanguage, often not alleviating the need for those components to be accessible by your application Thesolution 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 2Enterprise 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 JavaPersistence 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 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 interprocess
tremen-communication, discusses several techniques for interprocess tremen-communication, and culminates in anexample using Web Services
Trang 22Introduction
Chapter 12: Service Oriented Integration
When performing enterprise application integration of components distributed across many machinesand platforms, it is often necessary for you to be able to spread the workload across many differentsteps There are two APIs that are particularly useful in this regard, the Java Message Service (JMS) andthe 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 yourapplication can be secured using the Java Authorization and Authentication Service (JAAS) and yourdata can be secured using the Java Cryptography Extensions (JCE) Also detailed in this chapter is thenew 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 deploymentdescriptors and packaging rules that exist in many of the Java APIs There are JARs, WARs, EARs, andmore on the way Often you get cursory understanding of these formats and specifications within each ofthe stovepipe books In this chapter, you learn about a number of the packaging mechanisms that exist inJava, 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 anIntegrated 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 serverlike 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 areused throughout the book
Tips, hints, tricks, and asides to the current discussion are offset and placed in italics like this.
Boxes like this one hold important, not-to-be forgotten information that is directly relevant to the surrounding text.
Trang 23Introduction
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 presentcontext, 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 able for download at www.wrox.com Once at the site, simply locate the book’s title (either by using theSearch box or by using one of the title lists) and click the Download Code link on the book’s detail page
avail-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, youcan go to the main Wrox code download page at www.wrox.com/dynamic/books/download.aspxtosee 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 fect, and mistakes do occur If you find an error in one of our books, like a spelling mistake or faultypiece of code, we would be very grateful for your feedback By sending in errata you may save anotherreader hours of frustration and at the same time you will be helping us provide even higher qualityinformation
per-To find the errata page for this book, go to www.wrox.comand locate the title using the Search box orone of the title lists Then, on the book details page, click the Book Errata link On this page you can viewall 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.shtmland complete the form there to send us the error you have found We’ll check theinformation and, if appropriate, post a message to the book’s errata page and fix the problem in subse-quent editions of the book
Trang 24web-At http://p2p.wrox.comyou will find a number of different forums that will help you not only as youread 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
2. Read the terms of use and click Agree.
3. Complete the required information to join as well as any optional information you wish to
pro-vide and click Submit
4. You will receive an e-mail with information describing how to verify your account and
com-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 sages at any time on the Web If you would like to have new messages from a particular forum e-mailed
mes-to you, click the Subscribe mes-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 tions about how the forum software works as well as many common questions specific to P2P and Wroxbooks To read the FAQs, click the FAQ link on any P2P page
Trang 26ques-Part 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
Trang 28Key Java Language Features and Libraries
The past two major releases of the JDK have seen some significant changes JDK 5 introduced newfeatures 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 alightweight 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 java.utilbranch of theclass library that are useful for professional programming in Java
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 anduse 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
Because Derby is an involved topic, this section serves only to introduce Derby and its features,using the included command-line tool and a brief exploration of using the JDBC driver Derby isrevisited later in this book
Trang 29Using Derby
As mentioned, Derby is automatically installed as part of the JDK Derby provides a command-line toolcalled ij, which is an abbreviation for interactive JDBC scripting tool This tool provides a way to con-nect to and manipulate Derby databases You must have the following JAR files in your classpath beforeusing this tool The derby.jarfile contains the JDBC drivers, and derbytools.jarcontains the ij
process-The tool works much as you would expect it to, such as issuing a select statement to retrieve a partiallisting of data from the countries table (a table that is part of the example toursdb):
ij> select * from countries where country like ‘A%’;
COUNTRY |C&|REGION
-Afghanistan |AF|Asia
Albania |AL|Europe
Algeria |DZ|North Africa
American Samoa |AS|Pacific Islands
Azerbaijan |AZ|Central Asia
To create a new database from ij, include the parameter create=trueto the connection string Becauseyou’re already connected to the toursdb, first disconnect The selectstatement proves you’re discon-nected Then issue the new connectstatement:
ij> disconnect;
ij> select * from countries;
IJ ERROR: Unable to establish connection
ij> connect ‘jdbc:derby:DerbyTestDB;create=true’;
ij>
4
Part I: Thinking Like a Java Developer
Trang 30The database name (in this case, DerbyTestDB) is created as a subdirectory of the directory where youstarted the ijtool The database appears on disk in the directory C:\DerbyTestDB Exploring thisdirectory is strictly for curiosity’s sake — you should never have to modify any file in this directory,including the service.propertiesfile that may seem tempting to play with The creation of adatabase also creates a derby.logfile at the same level as the DerbyTestDB, so the file in this case is
C:\derby.log This log file is an error log and is useful to check to get more information about theinevitable problems that arise during real development If you create multiple databases they will sharethis log file
Now that you have a new database, create a table, insert some data, and query it:
ij> create table zipcodes(zipcode varchar(5), city varchar(20), state varchar(2));
0 rows inserted/updated/deletedij> insert into zipcodes values (‘22030’, ‘Fairfax’, ‘VA’);
1 row inserted/updated/deletedij> insert into zipcodes values (‘22003’, ‘Annandale’, ‘VA’);
1 row inserted/updated/deletedij> insert into zipcodes values (‘90210’, ‘Beverly Hills’, ‘CA’);
1 row inserted/updated/deletedij> select * from zipcodes;
ZIPC&|CITY |STA&
22030|Fairfax |VA22003|Annandale |VA90210|Beverly Hills |CA
-3 rows selectedij>
By default, auto-commit is onfrom the ijtool, so you don’t have to issue the commit;command tosave changes to the database You can control auto-commit by issuing the command “autocommit on;”
or “autocommit off;” Type “exit;” to exit from the ijtool
Now that you have seen the basics of using the ijtool, look at an example of querying your newly ated database from a Java program using the JDBC driver Because the standard JDBC mechanism isused, there are no surprises with the import statements:
DerbyTestDBClient testClient = new DerbyTestDBClient();
Trang 31The showZipCodesmethod actually opens the connection and performs the query The driver used is
org.apache.derby.jdbc.EmbeddedDriver Derby also includes a ClientDriverfor connecting toDerby in network mode, where Derby runs a network server providing for a client/server approach tousing Derby:
public void showZipCodes(){
try {String driver = “org.apache.derby.jdbc.EmbeddedDriver”;
e.printStackTrace();
}}}
Here’s the output from the previous code:
Trang 32Language Features Added in Java 5
Several useful syntactic elements were introduced in Java 5 All these features are supported by anupdated compiler, and all translate to already defined Java bytecode, meaning that virtual machines canexecute these features with no need for an update:
❑ Generics:A way to make classes type-safe that are written to work on any arbitrary object type,such as narrowing an instance of a collection to hold a specific object type and eliminating theneed to cast objects when taking an object out of the collection
❑ Enhanced forloop:A cleaner and less error-prone version of the forloop for use with iterators
❑ Variable arguments:Support for passing an arbitrary number of parameters to a method
❑ Boxing/unboxing:Direct language support for automatic conversion between primitive typesand their reference types (such as intand Integer)
❑ Type-safe enumerations:Clean syntax for defining and using enumerations, supported at thelanguage level
❑ Static import:Ability to access static members from a class without need to qualify them with aclass name
❑ Metadata:Coupled with new tools developed by third-party companies, saves developers theeffort of writing boilerplate code by automatically generating the code
These features update the Java language to include many constructs developers are used to in other guages They make writing Java code easier, cleaner, and faster Even if you choose not to take advan-tage of these features, familiarity with them is vital to read and maintain code written by otherdevelopers
lan-Generics
Java 5 introduced generics, also known as parameterized types Generics allow you to write a class thatcan operate on any type but that specific type is not specified until declaration of an instance of the class.Because this type is not specified as part of the class definition, the class becomes generic, gaining theability to work on any type specified The most obvious example, and a great use of generics, is the col-lection classes The ArrayListclass, for example, was written to hold, simply, Object This meansobjects lose their type when added to the ArrayListand a cast is needed when accessing an element
of the ArrayList However, code that uses a generic version of the ArrayListcan say “I want this
ArrayListto hold only Strings.” This adds additional type-safety to Java because, if anything otherthan a Stringis added to the collection, the compiler will catch it This also means that a cast is nolonger needed when accessing elements — the compiler knows it only holds Stringsand will produce
an error if the elements are treated as anything other than a String Specifying Stringas the terized type is as easy as placing the type in angle brackets:
parame-ArrayList<String> listOfStrings; // <TYPE_NAME> is new to the syntaxString stringObject;
listOfStrings = new ArrayList<String>(); // <TYPE_NAME> is new to the syntaxlistOfStrings.add(new String(“Test string”)); // Can only pass in String objectsstringObject = listOfStrings.get(0); // no cast required
7
Chapter 1: Key Java Language Features and Libraries
Trang 33Generics are also known as parameterized types where a type is the parameter As can be seen in the
previ-ous example, Stringis the formal type parameter This same parameterized type must be used when
instantiating the parameterized type
Because one of the goals of the new language features in Java 5 was to not change the Java instructionset, generics are, basically, syntactic sugar When accessing elements of the ArrayList, the compilerautomatically inserts the casts that you now don’t have to write It’s also possible to use the primitivedata types as a parameterized type, but realize that these incur boxing/unboxing costs because they areimplicitly converted to and from Object Nonetheless, there are benefits in increased type-safety andincreased program readability
Type Erasure
A generic type in Java is compiled to a single class file There aren’t separate versions of the generic typefor each formal parameterized type The implementation of generics utilizes type erasure, which meansthe actual parameterized type is reduced to Object Strangely, the decision to use erasure, althoughrequiring no bytecode changes, hobbles the generics mechanism in its determination to maintain strongtyping, as you’ll soon see
By way of example, the following code will not compile:
interface Shape {
void draw();
}
class Square implements Shape {
public String name;
public Square(){
public class ErasureExample {
public static <T> void drawShape(T shape){
8
Part I: Thinking Like a Java Developer
Trang 34The compiler issues the following error:
ErasureExample.java:23: cannot find symbolsymbol : method draw()
location: class java.lang.Objectshape.draw();
how-Start with a new generic class to hold a data item of arbitrary type:
public class CustomHolder<E>
{
E storedItem;
public E getItem(){
By convention, single letters are used for formal type parameters, usually E for element and T for type.Add a main method to this class:
public static void main(String args[]){
CustomHolder<String> stringHolder = new CustomHolder<String>();
CustomHolder<Object> objectHolder = new CustomHolder<Object>();
String str = new String(“test string”);
Trang 35to the Stringtype.
Because of type erasure, it is possible to assign a generic class reference to a reference of its nongeneric(legacy) version Therefore, the following code compiles without error:
Vector oldVector;
Vector<Integer> intVector;
oldVector = intVector; // valid
However, though not an error, assigning a reference to a nongeneric class to a reference to a generic classwill cause an unchecked compiler warning This happens when an erasure changes the argument types
of a method or a field assignment to a raw type if the erasure changes the method/field type As anexample, the following program causes the warnings shown after it You must pass -Xlint:unchecked
on the command line to javacto see the specific warnings:
import java.util.*;
public class UncheckedExample {
public void processIntVector(Vector<Integer> v){
// perform some processing on the vector}
public static void main(String args[]){
Vector<Integer> intVector = new Vector<Integer>();
Vector oldVector = new Vector();
UncheckedExample ue = new UncheckedExample();
// This is permitted
10
Part I: Thinking Like a Java Developer
Trang 36oldVector = intVector;
// This causes an unchecked warningintVector = oldVector;
// This is permittedue.processIntVector(intVector);
// This causes an unchecked warningue.processIntVector(oldVector);
}}
Attempting to compile the previous code leads to the following compiler warnings:
UncheckedExample.java:16: warning: unchecked assignment: java.util.Vector tojava.util.Vector<java.lang.Integer>
intVector = oldVector; // This causes an unchecked warning
UncheckedExample.java:18: warning: unchecked method invocation:
processIntVector(java.util.Vector<java.lang.Integer>) in UncheckedExample isapplied to (java.util.Vector)
ue.processIntVector(oldVector); // This causes an unchecked warning
2 warnings
Wildcards and Bounded Type Variables
Because you can’t use CustomHolder<Object>as if it were a super-type of CustomHolder<String>, youcan’t write a method that would process both CustomHolder<Object>and CustomHolder<String>.There is, however, a special way to accomplish this As part of the generics syntax, a wildcard is intro-duced, which, when used, basically means “any type parameter.” Revisit the previous example andshow how the wildcard, a single question mark, is used
Take the CustomHolderclass and add a few new methods and a new mainas follows:
public static void processHolderObject(CustomHolder2<Object> holder){
Object obj = holder.getItem();
System.out.println(“Item is: “ + obj);
}
public static void processHolderString(CustomHolder2<String> holder){
Object obj = holder.getItem();
System.out.println(“Item is: “ + obj);
}
public static void processHolderWildcard (CustomHolder2<?> holder){
Object obj = holder.getItem();
System.out.println(“Item is: “ + obj);
11
Chapter 1: Key Java Language Features and Libraries
Trang 37public static void main(String args[]){
CustomHolder2<String> stringHolder = new CustomHolder2<String>();
CustomHolder2<Object> objectHolder = new CustomHolder2<Object>();
String str = new String(“test string”);
processHolderObject(stringHolder);
^CustomHolder2.java:52: processHolderString(CustomHolder2<java.lang.String>) in CustomHolder2<E> cannot be applied to (CustomHolder2<java.lang.Object>)
Stringtype.”
A type parameter can be restricted to certain types by what is called a bound A bound can be applied to
a regular type parameter or a wildcard Revisit the Shapeexample from earlier in the chapter, whichdefines a Shapeinterface:
Trang 38class Square implements Shape {public void draw()
{System.out.println(“Drawing square”);
}}
class Circle implements Shape {public void draw()
{System.out.println(“Drawing circle”);
}}
Now define a PaintProgramclass to demonstrate bounds If you add a drawShapemethod that defines
a type parameter, this won’t work:
public static <S> void drawShape(S shape){
shape.draw();
}
So you must add a bound to the type parameter so Java treats the shapeformal type parameter as a
Shapeand not an Object By bounding the type parameter to Shape, you dictate that the object passed
in must derive directly or indirectly from Shape Because of this, Java knows that the object is a Shape
and thus can invoke methods that belong to Shapeinstead of only Objectmethods:
public static <S extends Shape> void drawShapeBounded(S shape){
shape.draw();
}
As alluded to earlier, this may make you wonder if generics really are that useful If you have to itly state the bounds on a type parameter, you may as well just use the Shapeinterface to constrain anormal method parameter One of the places generics really do shine is easing the use of collections, andthis is probably the main justification for adding generics to Java
explic-Look at implementing a drawAllShapesmethod that takes a parameterized ArrayList As expected,you need a bound here so Java does not treat the contents of the ArrayListas Objects:
public static <T extends Shape> void drawAllShapes(ArrayList<T> shapeList){
T shape;
Iterator<T> shapeIterator;
shapeIterator = shapeList.iterator();
while(shapeIterator.hasNext()) {shape = shapeIterator.next();
shape.draw();
}}
13
Chapter 1: Key Java Language Features and Libraries