Loading




Common Java Cookbook

Timothy M. O'Brien

Abstract

This collection provides expert tips for using Java-based utilities from projects such as Apache Commons, Apache Lucene, and Apache Velocity. You don't have to be an expert, the book's solution-based format contains code examples for a wide variety of web, XML, network, testing, and application projects. If you want to learn how to combine common open-source Java utilities to create powerful Java applications and tools, the Common Java Cookbook is for you.


Copyright and License
Foreword: 0.26
1. Changes in Edition 0.26
Preface
1. What's Inside
2. Conventions Used in This Book
3. What You'll Need
4. Book Examples
5. The Apache Commons Community
6. The Apache Software License
7. We'd Like to Hear from You
1. Supplements to the Java 2 Platform
1.1. Introduction
1.1. Depending on Commons Lang
1.4. Automating the Generation of toString( ) Content
1.5. Customizing Generated toString( ) Content
1.6. Automating hashCode( ) and equals( )
1.7. Automating compareTo( )
1.8. Printing an Array
1.9. Cloning and Reversing Arrays
1.10. Transforming Between Object Arrays and Primitive Arrays
1.11. Finding Items in an Array
1.12. Creating a Map from a Multidimensional Array
1.13. Formatting Dates
1.14. Rounding Date Objects
1.15. Truncating Date Objects
1.16. Creating an Enum
1.18. Validation of Method Parameters
1.19. Measuring Time
2. Manipulating Text
2.1. Introduction
2.1. Setting Up StringUtils and WordUtils
2.2. Checking for an Empty String
2.3. Abbreviating Strings
2.4. Splitting a String
2.5. Finding Nested Strings
2.6. Stripping and Trimming a String
2.7. Chomping a String
2.8. Creating an Emphasized Header
2.9. Reversing a String
2.10. Wrapping Words
2.11. Testing the Contents of a String
2.12. Measuring the Frequency of a String
2.13. Parsing Formatted Strings
2.14. Calculating String Difference
2.15. Using Commons Codec
2.17. Calculating Soundex
3. JavaBeans
3.1. Introduction
3.2. Obtaining Commons BeanUtils
3.4. Accessing Simple Bean Properties
3.5. Accessing Nested Bean Properties
3.6. Accessing Indexed Bean Properties
3.7. Accessing Mapped Bean Properties
3.8. Accessing a Simple, Nested, Indexed, and Mapped Bean Property
3.9. Determining the Type of a Bean Property
3.10. Comparing Beans
3.11. Copying Bean Properties
3.12. Cloning a Bean
3.13. Setting a Bean Property
3.14. Testing Property Access
3.15. Validating Beans with Predicates
3.16. Creating a Map of Bean Properties
3.17. Wrapping a Bean with a Map
3.18. Creating a Dynamic Bean
3.19. Getting and Setting Properties as Strings
4. Functors
4.1. Introduction
4.1. Obtaining Commons Collections
4.3. Reversing a Comparator
4.4. Chaining Comparators
4.5. Comparing Nulls
4.6. Fixed-Order Comparison
4.7. Using Simple Predicates
4.8. Writing a Custom Predicate
4.9. Creating Composite Predicates
4.10. Transforming Objects
4.11. Creating a Chain of Transformations
4.12. Applying Conditional Transformations
4.13. Writing a Closure
4.14. Chaining Closures
4.15. Modeling Conditional Statements with Closures
4.16. Modeling Loops with Closures
5. Collections
5.1. Introduction
5.1. Obtaining Commons Collections
5.2. Using a Looping Iterator
5.3. Iterating Over an ArrayList
5.4. Filtering a Collection with a Predicate
5.5. Iterating Through Distinct Elements
5.6. Using a Bag
5.7. Using a Buffer
5.8. Creating a Priority Queue
5.9. Using a Blocking Buffer
5.10. Storing Multiple Values in a Map
5.11. Retrieving a Key by Value (Working with Bi-directional Maps)
5.12. Using a Case-Insensitive Map
5.13. Creating Typed Collections and Maps
5.14. Constraining Map Values
5.15. Constraining List Contents
5.16. Transforming Collections
5.17. Creating a Least Recently Used Cache
5.18. Using a Lazy Map
5.19. Counting Objects in a Collection
5.20. Performing Set Operations
5.21. Retrieving Map Values Without Casting
6. XML
6.1. Introduction
6.1. Obtaining Commons Digester
6.2. Turning XML Documents into Objects
6.3. Namespace-Aware Parsing
6.4. Creating a Simple XML Command Language
6.5. Variable Substitution and XML Parsing
6.6. Obtaining Commons Betwixt
6.7. Turning Beans into XML Documents
6.8. Customizing XML Generated from an Object
6.9. Turning XML Documents into Beans
7. Application Infrastructure
7.1. Introduction
1.1. Depending on Commons CLI
7.2. Parsing a Simple Command Line
7.3. Parsing a Complex Command Line
7.4. Printing Usage Information
1.1. Depending on Commons Configuration
7.6. Configuring Applications with Properties Files
7.7. Configuring Applications with XML
7.8. Using Composite Configuration
7.9. Depending on Commons Logging
7.10. Using an Abstract Logging Interface
7.11. Specifying a Logging Implementation
7.12. Depending on Apache Log4J
7.13. Configuring Log4J with a Properties File
7.14. Configuring Log4J with XML
8. Math
8.1. Introduction
8.1. Using Fractions
8.2. Finding the Maximum and Minimum in an Array
8.3. Using Number Ranges
8.4. Generating Random Variables
8.5. Obtaining Commons Math
8.6. Calculating Simple Univariate Statistics
8.7. Solving a System of Linear Equations
8.8. Arithmetic with Complex Numbers
8.9. Establishing Relationships Between Variables
8.10. Estimating the Amount of Time Left in a Process
9. Templating
9.1. Introduction
9.1. Obtaining Commons JEXL
9.2. Using an Expression Language
9.3. Invoking Methods in an Expression
9.4. Externalizing Logic with an Expression Language
9.5. Obtaining Velocity
9.6. Using a Simple Templating Language
9.7. Writing Templates with Conditionals and Loops
9.8. Using Macros in a Templating Engine
9.9. Invoking Methods in a Template
9.10. Obtaining FreeMarker
9.11. Using a Complex Scripting Engine
9.12. Accessing XML Documents from a Templating Engine
9.13. Using Velocity in a Web Application
9.14. Using FreeMarker in a Web Application
10. I/O and Networking
10.1. Introduction
10.1. Obtaining Commons IO
10.2. Copying Streams, byte[ ], Readers, and Writers
10.3. Closing Streams, Readers, and Writers
10.4. Printing a Human-Readable File Size
10.5. Copying Files, Strings, and URLs
10.6. Deleting Directories Recursively
10.7. Obtaining the Size of a Directory
10.8. Touching a File
10.9. Filtering Files
10.10. Measuring Stream Traffic
10.11. Splitting an OutputStream
10.12. Obtaining Jakarta ORO
10.13. Using Globs and Perl5 Regular Expressions to List Files
10.14. Obtaining Commons Net
10.15. Writing an FTP Client
10.16. Sending Mail with SMTP
10.17. Checking a POP3 Mailbox
10.18. Testing an IP Address Against a Subnet
11. HTTP and WebDAV
11.1. Introduction
11.1. Obtaining HttpClient
11.3. Performing an HTTP GET
11.4. Sending Parameters in a Query String
11.5. Retrieving Content with a Conditional GET
11.6. Debugging HTTP Communications
11.7. Making an HTTP POST Request
11.8. Sending POST Data from a File
11.9. Uploading Files with a Multipart POST
11.10. Basic Authentication
11.11. NTLM Authentication
11.12. Working with Cookies
11.13. Handling Redirects
11.14. SSL
11.15. Accepting a Self-Signed Certificate
11.16. Obtaining Jakarta Slide
11.17. Connecting to WebDAV Resources
11.18. Modifying a WebDAV Resource
12. Searching and Filtering
12.1. Introduction
12.1. Obtaining Commons JXPath
12.2. Querying an Object Graph with XPath
12.3. Search a Collection of Simple Objects
12.4. Applying XPath Queries to Complex Object Graphs
12.5. Obtaining Lucene
12.6. Creating an Index of XML Documents
12.7. Searching for a Specific Term in a Document Index
12.8. Finding the Frequency of Terms in an Index
13. JSON
13.1. Introduction
13.2. Obtaining JSON-lib
13.3. Creating JSON
13.4. Converting a Map to JSON
13.5. Converting a Bean to JSON
13.6. Parsing JSON
13.7. Converting XML to JSON
13.8. Converting JSON to XML
13.9. Measuring JSON Encoding and Parsing Performance
14. Protocol Buffers
14.1. Introduction
14.2. Downloading Protocol Buffers
14.3. Compiling Protocol Buffers
14.4. Adding Protocol Buffers as a Project Dependency
14.5. Defining a Message Type
14.6. Encoding and Decoding Messages Using Byte Arrays
14.7. Measuring Protocol Buffers Performance
15. Google Guava: I/O
15.1. Introduction
15.2. Obtaining Google Guava
15.3. Copying and InputStream to an OutputStream
15.4. Calculating a Checksum for a Byte Array
15.5. Calculating a Message Digest for a Byte Array
15.6. Concatenating Multiple Files
15.7. Concatenating Multiple Readers
15.8. Reading and Writing Byte Arrays to and from Memory
15.9. Slicing (and Dicing) an InputStream
15.10. Flushing and Closing Stream, Writer, or Reader (without the Headache of Exception Handling)
15.11. Measuring Amount of Data Written To and Read From a Stream
15.12. Buffering Data to a File As Needed
15.13. Appending Text to Files
15.14. Create Parent Directories (mkdir -p for Java)
15.15. Make a Temporary Directory
15.16. Delete Everything in a Directory
15.17. Recursively Delete Everything in a Directory (including Subdirectories)
15.18. Compare Two Files for Equality
15.19. Calculate the Checksum of a File
15.20. Calculate the Digest of a File
15.21. Map a File to Memory
15.22. Move a File
15.23. Create New InputStreams and OutputStreams for a File
15.24. Create New Readers and Writers for a File
15.25. Read Bytes from a File
15.26. Read Text from a File
15.27. Create a File
15.28. Overwrite a File
15.29. Convert a File to a Byte Array
15.30. Putting Limits on an InputStream
15.31. Discarding Bytes into the Abyss
15.32. Filtering Files by Regular Expression
16. Google Guava: Collections
16.1. Introduction
16.2. Obtaining Google Guava
16.3. Obtaining the Union of Two Sets
16.4. Obtaining the Intersection of Two Sets
16.5. Obtaining the Difference Between Two Sets
16.6. Obtaining the Symmetric Difference Between Two Sets
16.7. Generate All Possible Subsets of a Set
16.8. Working with Multisets
16.9. Retrieving a Key by Value (Working with Bi-directional Maps)
16.10. Adding Constraints to a Collection (List or Set)
16.11. Adding Constraints to a Map
Index

List of Examples

1.1. Adding a Dependency on Commons Lang
1-1. The PoliticalCandidate class using ReflectionToStringBuilder
1-2. Automating hashCode( ) and equals( )
1-3. Implementing compareTo( ) using a reflection builder
1-4. Customizing a compareTo( ) method with CompareToBuilder
1-5. Cloning and reversing a primitive array with ArrayUtils
1-6. Cloning and reversing an Object[ ] with ArrayUtils
1-7. Searching an array using ArrayUtils.contains( ) and ArrayUtils.indexOf( )
1-8. Creating a Map from an Object[ ][ ]
1-9. Truncating a Date object at Calendar.MONTH
1-10. Defining a Flavor enumeration by extending Enum
1-11. Extending ValuedEnum to create an enum
1-12. Vocalist bean with a PartEnum
1-13. Using public static final constants for category information
1-14. Simplifying with ValueEnum
1-18. Using Validate to perform simple validations
1-19. Using the Validator and the DoubleRange to validate method parameters
1-20. Using StopWatch to measure time
1-21. Using the StopWatch.split( ) and StopWatch.unsplit( ) methods
2.1. Adding a Dependency on Commons Codec
3-1. Sample bean
3.2. Adding a Dependency on Commons BeanUtils
3-4. A Person bean with two simple properties
3-5. Decorating a Comparator with a BeanComparator
3-6. BeanMap methods getBean( ), setBean( ), getType( ), getReadMethod( ), and getWriteMethod( )
3-7. Using BeanUtils to populate a bean from user input
4.1. Adding a Dependency on Commons Collections
4-1. A Comparator that compares Book objects by name and author
4-2. Using ReverseComparator to sort Book objects
4-3. A bean representing a playing card
4-4. Combining FixedOrderComparator with BeanComparator, NullComparator, and ComparatorChain
4-5. A simple Predicate implementation
4-6. Implementing the Predicate interface
4-7. InputPredicate: a predicate that selects an input from a Map
4-8. Implementing a multilevel composite Predicate
4-9. Using a SwitchTransformer
5.1. Adding a Dependency on Commons Collections
5-1. An EarthQuake bean
5-2. Major earthquake classification Predicate
5-3. Using a Bag to track inventory
5-4. Using a BoundedFifoBuffer
5-5. A Patient object
5-6. A Comparator to sort Patient objects by priority
5-7. Using a prioritizing buffer
5-8. A BufferListener constantly calling remove( )
5-9. An Indexer stage in a pipeline
5-10. Using MultiMap.remove( )
5-11. Storing ISO country codes in a BidiMap
5-12. Using a CaseInsensitiveMap for U.S. states
5-13. Using TypedList to decorate a list
5-14. Decorating a map with TypedMap
5-15. A Predicate to validate a Team's name property
5-16. Predicate to validate a Team's coach property
5-17. Example using a LazyMap
5-18. A StockQuoteTransformer
5-19. Using CollectionUtils union( ), intersection( ), disjunction( ), and subtract( )
6.1. Adding a Dependency on Commons Digester
6.2. Adding a Dependency on Commons Betwixt
7.1. Adding a Dependency on Commons CLI
7-1. Printing usage information with HelpFormatter
7.3. Adding a Dependency on Commons Configuration
7-2. global. properties
7-3. local .properties
7-4. user. properties
7.7. Adding a Dependency on Commons Logging
7.8. Adding a Dependency on Apache Log4J
8.1. Adding a Dependency on Commons Math
8-1. ProcessEstimator to estimate time of program execution
8-2. An example using the ProcessEstimator
9.1. Adding a Dependency on Commons JEXL
9.2. Adding a Dependency on Velocity
9.3. Adding a Dependency on Commons BeanUtils
10.1. Adding a Dependency on Commons IO
10.2. Adding a Dependency on Commons ORO
10.3. Adding a Dependency on Commons Net
10.4. Testing an IP Address against a Subnet
10.5. Printing Information about a Subnet
11.1. Adding a Dependency on Commons HttpClient
11-1. Requesting information with a conditional GET
11.3. Adding a Dependency on Slide
12.1. Adding a Dependency on Commons JXPath
12.2. Adding a Dependency on Lucene
12-1. PlayIndexer using Commons Digester and Apache Lucene
12-2. Digester rules for PlayIndexer
12-3. TermFreq finding the most frequent terms in an index
13.1. Adding a Dependency on Commons Digester
13.2. Generating JSON from Java
13.3. Converting a Map to JSON
13.4. Converting a Bean to JSON
13.5. Parsing JSON in Java
13.6. Adding Dependencies to Parse XML and Generate JSON
13.7. Converting XML to JSON
13.8. Adding Dependencies to Parse JSON and Generate XML
13.9. Converting JSON to XML
13.10. Generating XML from JSON without Type Hints
13.11. Supplying a Root Name to the XMLSerializer
13.12. Mesuring the Performance of Simple JSON Operations
14.1. Adding a Dependency on Commons Digester
14.2. A Protocol Buffers Message Definition
14.3. Encoding and Decoding a Protocol Buffers Message
14.4. Measuring Average Execution Time for Protocol Buffers Operations
15.1. Adding a Dependency on Google Guava
15.2. Copying the Contents of an InputStream to an OutputStream
15.3. Calculating the Checksum of a Byte Array
15.4. Calculating the MessageDigest of a Byte Array
15.5. Joining Two Files using ByteStreams.join() and ByteStreams.copy()
15.6. Joining Two Readers using CharStreams.join() and CharStreams.copy()
15.7. Using ByteArrayDataOutput and ByteArrayDataInput
15.8. Writing Data with the ByteArrayDataOutput Class
15.9. Writing Data without the ByteArrayDataOutput Class
15.10. Slicing Data from an InputStream
15.11. One of the Reasons Java Gets a Bad Rap
15.12. Using Closeables and Flushables in a finally block
15.13. Avoid Most Exception Handling with ByteStreams.write()
15.14. Using a CountingInputStream and CountingOutputStream
15.15. Measuring the Performance of FileBackedOutputStream
15.16. Appending Text to a File with Files.append()
15.17. Creating Subdirectories with File.createParentDirs()
15.18. Creating Nested Subdirectories using Files.createParentDirs()
16.1. Adding a Dependency on Google Guava
16.2. Using Sets.union() to Calculate the Union of Two Set Collections
16.3. Calculating the Intersection of Two Sets
16.4. Calculating the Difference Between Two Sets
16.5. Calculating the Symmetric Difference Between Two Sets
16.6. Generating all Possible Subsets of a Given Set
16.7. Using a Multiset
16.8. Using a BiMap
16.9. Defining a Custom Constraint
16.10. Adding Constraints to a Collection
16.11. Defining a custom MapConstraint
16.12. Validating entries as they are added to Map with MapConstraints.