1 vk» Java 7 Recipes (,\['«** - < g!p#«josh Juneau Carl Dea Freddy Guime John O'Conner
Contents J Contents at a Glance About the Authors About the Technical Reviewers Acknowledgments Introduction iv xvi xviii..xix xxi Chapter 1: Getting Started with Java 7 1 1-1. Downloading and Installing Java 7 1 1-2. Configuring the CLASSPATH 3 1-3. Writing an Executable Java Class 5 1-4. Compiling and Executing Java Class 7 1-5. Printing Output 8 1-6. Passing Arguments via the Command Line 9 1-7. Obtaining and Setting Environment Variable Values 10 1-8. Documenting Code with Javadoc 12 1-9. Marking Features as Deprecated 15 1-10. Creating Methods in a Class 17 1-11. Passing Arguments to Methods and Returning Values 19 1-12. Organizing Code with Packages 21 1-13. Accepting Keyboard Input from the Command Line 23 Chapter 2: Strings 25 2-1. Obtaining a Subsection of a String 25 2-2. Comparing Strings 26 2-3. Trimming Whitespace 29 vi
2-4. Changing the Case of a String 30 2-5. Concatenating Strings 31 2-6. Converting Strings to Numeric Values 33 2-7. Iterating Over the Characters of a String 35 2-8. Finding Text Matches 37 2-9. Replacing All Text Matches 40 2-10. Determining Whether a File Name Ends with a Given String 41 Chapter 3: Numbers and Dates 43 3-1. Rounding Float and Double Values to Integers 43 3-2. Formatting Double and Long Decimal Values 44 3-3. Comparing int Values 46 3-4. Comparing Floating-Point Numbers 48 3-5. Performing Calculations with Complex Numbers 49 3-6. Formatting and Parsing Complex Numbers 53 3-7. Calculating Monetary Values 54 3-8. Randomly Generating Values 56 3-9. Obtaining the Current Date 58 3-10. Adding and Subtracting Days, Months, and Years 61 3-11. Finding the Difference Between Two Dates 63 3-12. Formatting Dates for Display 66 3-13. Comparing Dates 68 3-14. Writing Readable Numeric Literals 69 3-15. Declaring Binary Literals 70 Chapter 4: Data Structures, Conditionals, and Iteration 73 4-1. Defining a Fixed Set of Related Constants 73 4-2. Designing Intelligent Constants 77 4-3. Executing Code Based Upon a Specified Value 81 4-4. Working with Fix-Sized Arrays 85 4-5. Using Generic Types 91 4-6. Working with Dynamic Arrays 96 vii
4-7. Making Your Objects Iterable 99 4-8. Iterating Over a Map 102 Chapter 5: Input and Output 105 5-1. Serializing Java Objects 106 5-2. Serializing Java Objects More Efficiently 109 5-3. Serializing Java Objects as XML 111 5-4. Creating a Socket Connection and Sending Serializable Objects Across the Wire.112 5-5. Obtaining the Java Execution Path 115 5-6. Copying a File 115 5-7. Moving a File 116 5-8. Creating a Directory 117 5-9.lterating Over Files in a Directory 118 5-10. Querying (and Setting) File Metadata 119 5-11. Monitoring a Directory for Changes 121 5-12. Reading Property Files 123 5-13. Uncompressing Compressed Files 124 Chapter 6: Exceptions and Logging 127 6-1. Catching Exceptions 129 6-2. Guaranteeing that Cleanup Code Runs, No Matter What 130 6-3. Throwing Exceptions 131 6-4. Catching Multiple Exceptions 132 6-5. Catching the Uncaught Exceptions 134 6-6. Managing Resources with try/catch Blocks 136 6-7. Creating an Exception Class 137 6-8. Rethrowing the caught Exception 138 6-9. Logging Events in Your Application 139 6-10. Rotating and Purging Logs 141 6-11. Logging Exceptions 143 Chapter 7: Object-Oriented Java 145 7-1. Controlling Access to Members of a Class 145 viii
7-2. Making Private Fields Accessible 146 7-3. Creating a Class That Can Have Only One Instance 148 7-4. Generating Instances of a Class 151 7-5. Creating Reusable Objects 153 7-6. Defining an Interface for a Class 155 7-7. Constructing Instances of the Same Class with Different Values 158 7-8. Interacting with a Class via Interfaces 162 7-9. Making a Class Cloneable 164 7-10. Comparing Objects 168 7-11. Extending the Functionality of a Class 174 7-12. Defining a Class Template 176 7-13. Increasing Class Encapsulation 178 Chapter 8: Concurrency 185 8-1. Starting a Background Task 185 8-2. Updating (and Iterating) a Map 186 8-3. Inserting a Key into a Map Only If the Key is not Already Present 188 8-4. Iterating Through a Changing Collection 190 8-5. Coordinating Different Collections 192 8-6. Splitting Work into Separate Threads 196 8-7. Coordinating Threads 198 8-8. Creating Threadsafe Objects 203 8-9. Implementing Threadsafe Counters 206 8-10. Breaking Down Tasks into Discrete Units Of Work 207 Chapter 9: Debugging and Unit Testing... 213 9-1. Understanding Exceptions 213 9-2: Locking Down Behavior of Your Classes 214 9-3. Scripting Your Unit Tests 216 9-4. Determining Code Coverage 220 9-5. Finding Bugs Early 223 9-6.Monitoring Garbage Collection in your Application 226
9-7: Spotting Memory Leaks in Your Application 229 9-8. Getting a Thread Dump 234 Chapter 10: Unicode, Internationalization, and Currency Codes 237 10-1. Converting Unicode Characters to Digits 237 10-2. Creating and Working with Locales 239 10-3. Setting the Default Locale 243 10-4. Searching Unicode with Regular Expressions 247 10-5. Overriding the Default Currency 251 10-6. Converting Byte Arrays to and from Strings 253 10-7. Converting Character Streams and Buffers 255 Chapter 11: Working with Databases 259 11-1. Connecting to a Database 259 11-2. Handling Connection and SQL Exceptions 262 11-3. Querying a Database and Retrieving Results 264 11-4. Performing CRUD Operations 266 11-5. Simplifying Connection Management 271 11-6. Guarding Against SQL Injection 275 11-7. Performing Transactions 280 11-8. Creating a Scrollable ResultSet 284 11-9. Creating an Updatable ResultSet 286 11-10. Caching Data for Use When Disconnected 289 11-11. Joining RowSet Objects When Not Connected to the Data Source 295 11-12. Filtering Data in a RowSet 301 11-13. Querying and Storing Large Objects 308 11-14. Storing Array Values 312 11-15. Retrieving Array Values 315 11-16. Invoking Stored Procedures 317 11-17. Handling Resources Automatically 319 ichapter 12: Java 2D Graphics 321 Helper Class for This Chapter 321 X
12-1. Creating Points 324 12-2. Drawing Lines 326 12-3. Drawing Shapes 331 12-4.Filling Shapes...338 12-5. Gradients 342 12-6. Transforming Shapes 346 12-7. Making Complex Shapes 350 12-8. Creating Interactive Shapes 355 12-9. Changing Text Font 362 12-10. Adding Attributes to Text 365 12-11. Measuring Text 367 12-12. Display Multiple Lines of Text 372 12-13. Adding Shadows to Drawings 375 12-14. Printing Documents 379 12-15. Loading and Drawing an Image 382 12-16. Altering an Image 387 12-17. Storing an Image 391 Chapter 13: Java3D 397 13-1. Installing Java3D 397 13-2. Creating a Simple 3D Object 398 13-3. Transforming Objects 402 13-4. Animating a 3D object 404 13-5. Navigating the Created 3D Universe 406 13-6. Responding to Keyboard Events 408 13-7: Changing an Object's Lighting 410 Chapter 14: Swing API 413 14-1. Creating a GUI 413 14-2. Running a Swing Application 417 14-3. Adding Components to a GUI 418 14-4. Laying Out GUI Components 424
14-5. Generating Events with Buttons 435 14-6. Refreshing a User Interface 437 14-7. Submitting Form Values to a Database 442 14-8. Making a Multi-Window Program 449 14-9. Adding a Menu to an Application 452 14-10. Adding Tabs to a Form 456 14-11. Drawing on a Canvas 458 14-12. Generating and Laying Out Icons 462 14-13. Designing and Manipulating Borders 465 14-14. Creating Text Components 469 14-15. Associating Action Objects with Editing Commands 473 14-16. Creating Keyboard Shortcuts 479 14-17. Creating a Document 482 14-18. Developing a Dialog Box 486 14-19. Associating Listeners with a Document 491 14-20. Formatting GUI Applications with HTML 494 14-21. Changing the Look and Feel of a GUI 496 14-22. Distributing a Swing Application 500 14-23. Creating an Animation 502 14-24. Working with the JLayer Component 505 14-25. Adding Printing Support to Swing Components 509 { Chapter 15: JavaFX Fundamentals 513 15-1. Installing Required Software 514 15-2. Creating a Simple User Interface 518 15-3: Drawing Text 523 15-4: Changing Text Fonts 525 15-5. Creating Shapes 527 15-6. Assigning Colors to Objects 532 15-7. Creating Menus 537 15-8. Adding Components to a Layout 541 xii
51 CONTENTS 15-9. Generating Borders 543 15-10. Binding Expressions 15-11. Creating and Working with Observable Lists 551 15-12. Generating a Background Process 554 15-13. Associating Keyboard Sequences to Applications 559 15-14. Creating and Working with Tables 562 15-15. Organizing Ul with Split Views 567 15-16. Adding Tabs to the Ul 570 15-17. Developing a Dialog Box 573 Chapter 16: Graphics with JavaFX 579 16-1. Creating Images 580 16-2. Generating an Animation 589 16-3. Animating Shapes Along a Path 597 16-4. Manipulating Layout via Grids 603 16-5. Enhancing with CSS 615 Chapter 17: Media with JavaFX 621 17-1. Playing Audio 622 17-2. Playing Video 633 17-3. Controlling Media Actions and Events 642 17-4. Marking a Position in a Video 644 17-5. Synchronizing Animation and Media 647 Chapter 18: Working with Servlets and Applets 651 18-1. Setting Up a Servlet Environment 651 18-2. Developing a Servlet 653-18-3. Packaging, Compiling, and Deploying a Servlet 656 18-4. Registering Servlets without WEB-XML 658 18-5. Setting Initialization Parameters 661 18-6. Handling Requests and Responses 663 18-7. Setting Application-Wide Parameters 666 18-8. Filtering Web Requests 672 546 xiii
m CONTENTS 18-9. Forwarding Requests to Other Web Resources 674 18-10. Listening for Servlet Container Events 675 18-11. Listening for Attribute Changes 677 18-12. Managing Session Information 680 18-13. Finalization of a Servlet... 684 18-14. Creating an Applet 685 18-15. Packaging an Applet and Embedding into a Web Page 689 18-16. Creating Draggable Applets 693 18-17. Loading External Libraries for an Applet 695 18-18. Using Swing Components Within an Applet 699 Chapter 19: Intro to Android 707 19-1. Setting Up a Development Environment with Eclipse 707 19-2. Creating a Basic Application 710 19-3. Compiling and Testing in an Emulator 713 19-4. Constructing a User Interface with XML Layout 714 19-5. Constructing a User Interface Programmatically 721 19-6. Handling Application Events and Activity Changes 724 19-7. Tying All Application Components Together 729 19-8. Handling Incoming Call Events 730 19-9. Building a Tabbed User Interface 733 19-10. Embedding Web Pages into an Application View 739 19-11. Granting Application Device Permissions 743 Chapter 20: Java FX on the Web 745 20-1. Embedding JavaFX Applications in a Web Page 745 20-2. Displaying HTML5 Content 753 20-3. Manipulating HTML5 Content with Java Code 757 20-4. Responding to HTML Events 764 20-5. Displaying Content from the Database 767 Chapter 21: E-mail 779 21-1. Installing JavaMail 779 xiv
-8 CONTENTS 21-2. Sending an E-mail 780 21-3. Attaching a File to an E-mail Message 781 21-4. Sending E-mail to a Group 782 21-5. Checking E-mail 783 21-6. Monitoring an E-mail Account 784 Chapter 22: XML Processing 787 22-1. Writing an XML File 787 22-2. Reading an XML File 791 22-3. Transforming XML 794 22-4. Validating XML 798 22-5. Creating Java Bindings for an XML Schema 800 22-6. Unmarshalling XML to a Java Object 801 22-7. Building an XML Document with JAXB 803 Chapter 23: Networking 805 23-1. Defining a Network Connection to a Server 805 23-2. Listening for Connections on the Server 808 23-3. Bypassing TCP for InfiniBand to Gain Performance Boosts 811 23-4. Broadcasting to a Group of Recipients 813 23-5. Generating and Reading from URLs 818 23-6. Parsing a URL 820 Index 823 XV