Вы находитесь на странице: 1из 333

June 2009

Edition 0.9

July 2009 Edition 0.19

The Common Java Cookbook

Edition 0.9 July 2009 Edition 0.19 The Common Java Cookbook Tim O’Brien discursive.com/books/cjcook A Discursive Open
Edition 0.9 July 2009 Edition 0.19 The Common Java Cookbook Tim O’Brien discursive.com/books/cjcook A Discursive Open

Tim O’Brien

discursive.com/books/cjcook A Discursive Open Book

Copyright and License

 

xx

1.

Creative Commons BY-NC-ND 3.0 US License

xx

Foreword: 0.19

 

xxiv

Preface

xxv

1.

What's Inside

xxv

2.

Conventions Used in This Book

xxviii

3.

What You'll Need

xxix

4.

Book Examples

xxix

5.

The Apache Commons Community

xxix

6.

The Apache Software License

xxx

7.

We'd Like to Hear from You

xxxi

1. Supplements to the Java 2 Platform

1

1.1.

Introduction

 

1

1.1.

Depending on Commons Lang

1

 

1.1.1. Problem

1

1.1.2. Solution

1

1.1.3. Discussion

2

1.4.

Automating the Generation of toString( ) Content

2

 

1.4.1. Problem

2

1.4.2. Solution

2

1.4.3. Discussion

2

1.5.

Customizing Generated toString( ) Content

4

 

1.5.1. Problem

4

1.5.2. Solution

4

1.5.3. Discussion

5

1.6.

Automating hashCode( ) and equals( )

6

 

1.6.1. Problem

6

1.6.2. Solution

6

1.6.3. Discussion

7

1.7.

Automating compareTo( )

8

 

1.7.1. Problem

8

1.7.2. Solution

8

1.7.3. Discussion

8

1.7.4. See

Also

9

1.8.

Printing an Array

10

 

1.8.1. Problem

10

1.8.2. Solution

10

1.8.3. Discussion

10

1.9.

Cloning and Reversing Arrays

10

 

1.9.1. Problem

10

1.9.2. Solution

11

1.9.3. Discussion

11

1.10. Transforming Between Object Arrays and Primitive Arrays

12

 

1.10.1. Problem

12

1.10.2. Solution

12

1.10.3. Discussion

13

1.10.4. See Also

14

1.11. Finding Items in an Array

14

Common Java Cookbook

 

1.11.1. Problem

14

1.11.2. Solution

14

1.11.3. Discussion

15

1.11.4. See Also

16

1.12.

Creating a Map from a Multidimensional Array

16

1.12.1. Problem

16

1.12.2. Solution

16

1.12.3. Discussion

16

1.12.4. See

Also

16

1.13.

Formatting

Dates

17

1.13.1. Problem

17

1.13.2. Solution

17

1.13.3. Discussion

17

1.13.4. See Also

18

1.14.

Rounding Date Objects

18

1.14.1. Problem

18

1.14.2. Solution

19

1.14.3. Discussion

19

1.14.4. See

Also

20

1.15.

Truncating Date Objects

20

1.15.1. Problem

20

1.15.2. Solution

20

1.15.3. Discussion

21

1.15.4. See Also

21

1.16.

Creating an Enum

21

1.16.1. Problem

21

1.16.2. Solution

21

1.16.3. Discussion

22

1.16.4. See Also

25

1.18.

Validation of Method Parameters

25

1.18.1. Problem

25

1.18.2. Solution

25

1.18.3. Discussion

25

1.18.4. See Also

27

1.19.

Measuring Time

27

1.19.1. Problem

27

1.19.2. Solution

27

1.19.3. Discussion

28

2. Manipulating Text

 

30

2.1.

Introduction

30

2.1.

Setting Up StringUtils and WordUtils

30

2.1.1. Problem

30

2.1.2. Solution

30

2.1.3. Discussion

30

2.2.

Checking for an Empty String

31

2.2.1. Problem

31

2.2.2. Solution

31

2.2.3. Discussion

31

2.3.

Abbreviating Strings

32

Common Java Cookbook

2.3.1. Problem

32

2.3.2. Solution

32

2.3.3. Discussion

33

2.4. Splitting a String

34

2.4.1. Problem

34

2.4.2. Solution

34

2.4.3. Discussion

34

2.4.4. See Also

35

2.5. Finding Nested Strings

35

2.5.1. Problem

35

2.5.2. Solution

35

2.5.3. Discussion

35

2.6. Stripping and Trimming a String

36

2.6.1. Problem

36

2.6.2. Solution

36

2.6.3. Discussion

36

2.7. Chomping a String

37

2.7.1. Problem

37

2.7.2. Solution

37

2.8. Creating an Emphasized Header

38

2.8.1. Problem

38

2.8.2. Solution

38

2.8.3. Discussion

38

2.9. Reversing a String

38

2.9.1. Problem

38

2.9.2. Solution

38

2.9.3. Discussion

39

2.10. Wrapping Words

39

2.10.1. Problem

39

2.10.2. Solution

40

2.10.3. Discussion

40

2.11. Testing the Contents of a String

41

2.11.1. Problem

41

2.11.2. Solution

41

2.11.3. Discussion

41

2.12. Measuring the Frequency of a String

42

2.12.1. Problem

42

2.12.2. Solution

43

2.12.3. Discussion

43

2.12.4. See Also

43

2.13. Parsing Formatted Strings

43

2.13.1. Problem

43

2.13.2. Solution

44

2.13.3. Discussion

44

2.14. Calculating String Difference

45

2.14.1. Problem

46

2.14.2. Solution

46

2.14.3. Discussion

46

2.14.4. See Also

47

Common Java Cookbook

 

2.15.

Using Commons Codec

47

 

2.15.1. Problem

47

2.15.2. Solution

47

2.15.3. Discussion

48

2.15.4. See Also

48

 

2.17.

Calculating Soundex

48

 

2.17.1. Problem

48

2.17.2. Solution

48

2.17.3. Discussion

48

2.17.4. See Also

49

3.

JavaBeans

50

 

3.1.

Introduction

50

3.2.

Obtaining Commons BeanUtils

51

 

3.2.1. Problem

51

3.2.2. Solution

51

3.2.3. Discussion

51

3.2.4. See Also

51

 

3.4.

Accessing Simple Bean Properties

52

 

3.4.1. Problem

52

3.4.2. Solution

52

3.4.3. Discussion

52

3.4.4. See Also

53

 

3.5.

Accessing Nested Bean Properties

53

 

3.5.1. Problem

53

3.5.2. Solution

54

3.5.3. Discussion

54

 

3.6.

Accessing Indexed Bean Properties

55

 

3.6.1. Problem

55

3.6.2. Solution

55

3.6.3. Discussion

55

 

3.7.

Accessing Mapped Bean Properties

56

 

3.7.1. Problem

56

3.7.2. Solution

56

3.7.3. Discussion

56

 

3.8.

Accessing a Simple, Nested, Indexed, and Mapped Bean Property

57

 

3.8.1. Problem

57

3.8.2. Solution

57

3.8.3. Discussion

58

3.8.4. See Also

58

 

3.9.

Determining the Type of a Bean Property

59

 

3.9.1. Problem

59

3.9.2. Solution

59

3.9.3. Discussion

59

 

3.10. Comparing Beans

60

 

3.10.1. Problem

60

3.10.2. Solution

60

3.10.3. Discussion

60

3.10.4. See Also

62

 

3.11. Copying Bean Properties

62

Common Java Cookbook

 

3.11.1. Problem

62

3.11.2. Solution

62

3.11.3. Discussion

63

3.11.4. See Also

63

 

3.12. Cloning a Bean

63

 

3.12.1. Problem

63

3.12.2. Solution

64

3.12.3. Discussion

64

 

3.13. Setting a Bean Property

64

 

3.13.1. Problem

64

3.13.2. Solution

64

3.13.3. Discussion

65

 

3.14. Testing Property Access

65

 

3.14.1. Problem

65

3.14.2. Solution

65

3.14.3. Discussion

65

 

3.15. Validating Beans with Predicates

66

 

3.15.1. Problem

66

3.15.2. Solution

66

3.15.3. Discussion

67

3.15.4. See Also

67

 

3.16. Creating a Map of Bean Properties

67

 

3.16.1. Problem

68

3.16.2. Solution

68

3.16.3. Discussion

68

3.16.4. See Also

68

 

3.17. Wrapping a Bean with a Map

68

 

3.17.1. Problem

68

3.17.2. Solution

68

3.17.3. Discussion

69

3.17.4. See Also

70

 

3.18. Creating a Dynamic Bean

71

 

3.18.1. Problem

71

3.18.2. Solution

71

3.18.3. Discussion

71

3.18.4. See Also

72

 

3.19. Getting and Setting Properties as Strings

72

 

3.19.1. Problem

72

3.19.2. Solution

72

3.19.3. Discussion

73

3.19.4. See Also

73

4.

Functors

74

 

4.1.

Introduction

74

4.1.

Obtaining Commons Collections

74

 

4.1.1. Problem

74

4.1.2. Solution

74

4.1.3. Discussion

75

4.1.4. See Also

75

 

4.3.

Reversing a Comparator

75

Common Java Cookbook

4.3.1. Problem

75

4.3.2. Solution

75

4.3.3. Discussion

76

4.3.4. See Also

77

4.4. Chaining Comparators

77

4.4.1. Problem

77

4.4.2. Solution

77

4.4.3. Discussion

78

4.4.4. See Also

79

4.5. Comparing Nulls

79

4.5.1. Problem

79

4.5.2. Solution

79

4.5.3. Discussion

79

4.5.4. See Also

80

4.6. Fixed-Order Comparison

80

4.6.1. Problem

80

4.6.2. Solution

80

4.6.3. Discussion

81

4.6.4. See Also

83

4.7. Using Simple Predicates

83

4.7.1. Problem

83

4.7.2. Solution

83

4.7.3. Discussion

84

4.7.4. See Also

86

4.8. Writing a Custom Predicate

86

4.8.1. Problem

86

4.8.2. Solution

87

4.8.3. Discussion

87

4.8.4. See Also

88

4.9. Creating Composite Predicates

88

4.9.1. Problem

88

4.9.2. Solution

88

4.9.3. Discussion

89

4.10. Transforming Objects

91

4.10.1. Problem

91

4.10.2. Solution

91

4.10.3. Discussion

92

4.11. Creating a Chain of Transformations

92

4.11.1. Problem

92

4.11.2. Solution

92

4.11.3. Discussion

93

4.12. Applying Conditional Transformations

93

4.12.1. Problem

93

4.12.2. Solution

93

4.12.3. Discussion

94

4.13. Writing a Closure

94

4.13.1. Problem

94

4.13.2. Solution

95

4.13.3. Discussion

95

Common Java Cookbook

4.14. Chaining Closures

95

 

4.14.1. Problem

95

4.14.2. Solution

95

4.14.3. Discussion

96

4.15. Modeling Conditional Statements with Closures

96

 

4.15.1. Problem

96

4.15.2. Solution

96

4.15.3. Discussion

97

4.16. Modeling Loops with Closures

98

 

4.16.1. Problem

98

4.16.2. Solution

98

4.16.3. Discussion

99

5. Collections

100

5.1.

Introduction

100

5.1.

Obtaining Commons Collections

100

5.1.1. Problem

100

5.1.2. Solution

100

5.1.3. See Also

100

5.2.

Using a Looping Iterator

101

5.2.1. Problem

101

5.2.2. Solution

101

5.2.3. Discussion

101

5.2.4. See Also

102

5.3.

Iterating Over an ArrayList

102

5.3.1. Problem

102

5.3.2. Solution

102

5.3.3. Discussion

103

5.3.4. See Also

104

5.4.

Filtering a Collection with a Predicate

104

5.4.1. Problem

104

5.4.2. Solution

104

5.4.3. Discussion

105

5.4.4. See Also

106

5.5.

Iterating Through Distinct Elements

106

5.5.1. Problem

106

5.5.2. Solution

107

5.5.3. Discussion

107

5.5.4. See Also

107

5.6.

Using a Bag

107

5.6.1. Problem

107

5.6.2. Solution

108

5.6.3. Discussion

108

5.6.4. See Also

111

5.7.

Using a Buffer

111

5.7.1. Problem

111

5.7.2. Solution

111

5.7.3. Discussion

111

5.7.4. See Also

112

5.8.

Creating a Priority Queue

113

Common Java Cookbook

5.8.1. Problem

113

5.8.2. Solution

113

5.8.3. Discussion

113

5.8.4. See Also

115

5.9. Using a Blocking Buffer

116

5.9.1. Problem

116

5.9.2. Solution

116

5.9.3. Discussion

117

5.9.4. See Also

118

5.10. Storing Multiple Values in a Map

118

5.10.1. Problem

118

5.10.2. Solution

118

5.10.3. Discussion

119

5.11. Retrieving a Key by a Value

120

5.11.1. Problem

120

5.11.2. Solution

120

5.11.3. Discussion

120

5.11.4. See Also

122

5.12. Using a Case-Insensitive Map

122

5.12.1. Problem

122

5.12.2. Solution

122

5.12.3. Discussion

123

5.12.4. See Also

123

5.13. Creating Typed Collections and Maps

123

5.13.1. Problem

124

5.13.2. Solution

124

5.13.3. Discussion

124

5.13.4. See Also

126

5.14. Constraining Map Values

126

5.14.1. Problem

127

5.14.2. Solution

127

5.14.3. Discussion

127

5.15. Constraining List Contents

129

5.15.1. Problem

129

5.15.2. Solution

129

5.15.3. Discussion

129

5.15.4. See Also

130

5.16. Transforming Collections

130

5.16.1. Problem

130

5.16.2. Solution

130

5.16.3. Discussion

131

5.16.4. See Also

132

5.17. Creating a Least Recently Used Cache

132

5.17.1. Problem

132

5.17.2. Solution

132

5.17.3. Discussion

133

5.18. Using a Lazy Map

133

5.18.1. Problem

133

5.18.2. Solution

133

Common Java Cookbook

 

5.18.3. Discussion

134

5.18.4. See Also

136

5.19. Counting Objects in a Collection

136

 

5.19.1. Problem

136

5.19.2. Solution

136

5.19.3. Discussion

137

5.19.4. See Also

138

5.20. Performing Set Operations

138

 

5.20.1. Problem

138

5.20.2. Solution

138

5.20.3. Discussion

139

5.21. Retrieving Map Values Without Casting

139

 

5.21.1. Problem

139

5.21.2. Solution

139

5.21.3. Discussion

140

6. XML

142

6.1.

Introduction

142

6.1.

Obtaining Commons Digester

143

 

6.1.1. Problem

143

6.1.2. Solution

143

 

6.1.3. Discussion

143

 

6.1.4. See Also

143

6.2.

Turning XML Documents into Objects

143

 

6.2.1. Problem

143

6.2.2. Solution

143

 

6.2.3. Discussion

145

 

6.2.4. See Also

146

6.3.

Namespace-Aware Parsing

147

 

6.3.1. Problem

147

6.3.2. Solution

147

 

6.3.3. Discussion

148

 

6.3.4. See Also

149

6.4.

Creating a Simple XML Command Language

149

 

6.4.1. Problem

150

6.4.2. Solution

150

 

6.4.3. Discussion

152

 

6.4.4. See Also

152

6.5.

Variable Substitution and XML Parsing

152

 

6.5.1. Problem

152

6.5.2. Solution

152

 

6.5.3. Discussion

154

 

6.5.4. See Also

154

6.6.

Obtaining Commons Betwixt

154

 

6.6.1. Problem

154

6.6.2. Solution

154

 

6.6.3. Discussion

155

 

6.6.4. See Also

155

6.7.

Turning Beans into XML Documents

155

6.7.1.

Problem

155

Common Java Cookbook

 

6.7.2. Solution

155

6.7.3. Discussion

156

6.7.4. See Also

157

6.8. Customizing XML Generated from an Object

157

 

6.8.1. Problem

157

6.8.2. Solution

157

6.8.3. Discussion

158

6.8.4. See Also

159

6.9. Turning XML Documents into Beans

160

 

6.9.1. Problem

160

6.9.2. Solution

160

6.9.3. Discussion

160

6.9.4. See Also

161

7. Application Infrastructure

162

7.1.

Introduction

162

1.1.

Depending on Commons CLI

162

1.1.1. Problem

162

1.1.2. Solution

162

1.1.3. Discussion

162

1.1.4. See Also

162

7.2.

Parsing a Simple Command Line

162

7.2.1. Problem

162

7.2.2. Solution

163

7.2.3. Discussion

163

7.2.4. See Also

164

7.3.

Parsing a Complex Command Line

164

7.3.1. Problem

164

7.3.2. Solution

164

7.3.3. Discussion

165

7.3.4. See Also

165

7.4.

Printing Usage Information

165

7.4.1. Problem

165

7.4.2. Solution

165

7.4.3. Discussion

166

1.1.

Depending on Commons Configuration

167

1.1.1. Problem

167

1.1.2. Solution

167

1.1.3. Discussion

167

1.1.4. See Also

167

7.6.

Configuring Applications with Properties Files

167

7.6.1. Problem

167

7.6.2. Solution

168

7.6.3. Discussion

168

7.6.4. See Also

168

7.7.

Configuring Applications with XML

168

7.7.1. Problem

168

7.7.2. Solution

168

7.7.3. Discussion

169

7.7.4. See Also

169

Common Java Cookbook

7.8. Using Composite Configuration

170

 

7.8.1. Problem

170

7.8.2. Solution

170

7.8.3. Discussion

172

7.8.4. See Also

172

7.9. Depending on Commons Logging

172

 

7.9.1. Problem

172

7.9.2. Solution

172

7.9.3. Discussion

173

7.9.4. See Also

173

7.10. Using an Abstract Logging Interface

173

 

7.10.1. Problem

173

7.10.2. Solution

173

7.10.3. Discussion

174

7.10.4. See Also

174

7.11. Specifying a Logging Implementation

174

 

7.11.1. Problem

174

7.11.2. Solution

174

7.11.3. Discussion

174

7.11.4. See Also

175

7.12. Depending on Apache Log4J

175

 

7.12.1. Problem

175

7.12.2. Solution

175

7.12.3. Discussion

176

7.12.4. See Also

176

7.13. Configuring Log4J with a Properties File

176

 

7.13.1. Problem

176

7.13.2. Solution

176

7.13.3. Discussion

177

7.13.4. See Also

177

7.14. Configuring Log4J with XML

177

 

7.14.1. Problem

177

7.14.2. Solution

177

7.14.3. See Also

178

8. Math

179

8.1.

Introduction

179

8.1.

Using Fractions

179

8.1.1. Problem

179

8.1.2. Solution

179

8.1.3. Discussion

179

8.1.4. See Also

181

8.2.

Finding the Maximum and Minimum in an Array

181

8.2.1. Problem

181

8.2.2. Solution

181

8.2.3. Discussion

181

8.3.

Using Number Ranges

182

8.3.1. Problem

182

8.3.2. Solution

182

8.3.3. Discussion

182

Common Java Cookbook

 

8.3.4.

See Also

183

8.4. Generating Random Variables

183

 

8.4.1. Problem

183

8.4.2. Solution

183

 

8.4.3. Discussion

184

8.5. Obtaining Commons Math

184

 

8.5.1. Problem

184

8.5.2. Solution

184

 

8.5.3. Discussion

185

 

8.5.4. See Also

185

8.6. Calculating Simple Univariate Statistics

185

 

8.6.1. Problem

185

8.6.2. Solution

185

 

8.6.3. Discussion

186

 

8.6.4. See Also

187

8.7. Solving a System of Linear Equations

187

 

8.7.1. Problem

187

8.7.2. Solution

187

 

8.7.3. Discussion

187

 

8.7.4. See Also

188

8.8. Arithmetic with Complex Numbers

188

 

8.8.1. Problem

188

8.8.2. Solution

188

 

8.8.3. Discussion

189

 

8.8.4. See also

189

8.9. Establishing Relationships Between Variables

189

 

8.9.1. Problem

189

8.9.2. Solution

190

 

8.9.3. Discussion

190

 

8.9.4. See Also

191

8.10. Estimating the Amount of Time Left in a Process

191

 

8.10.1. Problem

191

8.10.2. Solution

191

8.10.3. Discussion

194

8.10.4. See Also

194

9. Templating

 

195

9.1.

Introduction

195

9.1.1. Common Templating Problems in Applications

195

9.1.2. Templating in Web Applications

196

9.1.

Obtaining Commons JEXL

197

 

9.1.1. Problem

197

9.1.2. Solution

197

 

9.1.3. Discussion

198

 

9.1.4. See Also

198

9.2.

Using an Expression Language

198

 

9.2.1. Problem

198

9.2.2. Solution

198

 

9.2.3. Discussion

199

 

9.2.4. See Also

200

Common Java Cookbook

9.3. Invoking Methods in an Expression

200

9.3.1. Problem

200

9.3.2. Solution

200

9.3.3. Discussion

201

9.3.4. See Also

201

9.4. Externalizing Logic with an Expression Language

202

9.4.1. Problem

202

9.4.2. Solution

202

9.4.3. Discussion

203

9.4.4. See Also

203

9.5. Obtaining Velocity

203

9.5.1. Problem

203

9.5.2. Solution

203

9.5.3. See Also

204

9.6. Using a Simple Templating Language

204

9.6.1. Problem

204

9.6.2. Solution

204

9.6.3. Discussion

205

9.6.4. See Also

205

9.7. Writing Templates with Conditionals and Loops

206

9.7.1. Problem

206

9.7.2. Solution

206

9.7.3. Discussion

207

9.7.4. See Also

208

9.8. Using Macros in a Templating Engine

208

9.8.1. Problem

208

9.8.2. Solution

208

9.8.3. Discussion

209

9.8.4. See Also

210

9.9. Invoking Methods in a Template

210

9.9.1. Problem

210

9.9.2. Solution

210

9.9.3. Discussion

212

9.9.4. See Also

213

9.10. Obtaining FreeMarker

213

9.10.1. Problem

213

9.10.2. Solution

213

9.10.3. See Also

213

9.11. Using a Complex Scripting Engine

214

9.11.1. Problem

214

9.11.2. Solution

214

9.11.3. Discussion

215

9.11.4. See Also

216

9.12. Accessing XML Documents from a Templating Engine

217

9.12.1. Problem

217

9.12.2. Solution

217

9.12.3. Discussion

218

9.12.4. See Also

219

9.13. Using Velocity in a Web Application

219

Common Java Cookbook

 

9.13.1. Problem

219

9.13.2. Solution

219

9.13.3. Discussion

220

9.13.4. See Also

220

9.14.

Using FreeMarker in a Web Application

220

9.14.1. Problem

220

9.14.2. Solution

220

9.14.3. Discussion

221

9.14.4. See Also

221

10. I/O and Networking

222

10.1.

Introduction

222

10.1.

Obtaining Commons IO

222

10.1.1. Problem

222

10.1.2. Solution

222

10.1.3. Discussion

223

10.1.4. See Also

223

10.2.

Copying Streams, byte[ ], Readers, and Writers

223

10.2.1. Problem

223

10.2.2. Solution

223

10.2.3. Discussion

224

10.3.

Closing Streams, Readers, and Writers

224

10.3.1. Problem

224

10.3.2. Solution

224

10.3.3. Discussion

224

10.3.4. See Also

226

10.4.

Printing a Human-Readable File Size

226

10.4.1. Problem

226

10.4.2. Solution

226

10.4.3. Discussion

226

10.5.

Copying Files, Strings, and URLs

227

10.5.1. Problem

227

10.5.2. Solution

227

10.5.3. Discussion

227

10.6.

Deleting Directories Recursively

228

10.6.1. Problem

228

10.6.2. Solution

228

10.6.3. Discussion

228

10.7.

Obtaining the Size of a Directory

229

10.7.1. Problem

229

10.7.2. Solution

229

10.8.

Touching a File

229

10.8.1. Problem

229

10.8.2. Solution

229

10.9.

Filtering Files

229

10.9.1. Problem

230

10.9.2. Solution

230

10.9.3. Discussion

230

10.10. Measuring Stream Traffic

231

10.10.1. Problem

231

Common Java Cookbook

 

10.10.2. Solution

231

10.10.3. Discussion

231

10.11.

Splitting an OutputStream

232

10.11.1. Problem

232

10.11.2. Solution

232

10.12.

Obtaining Jakarta ORO

232

10.12.1. Problem

232

10.12.2. Solution

233

10.12.3. Discussion

233

10.12.4. See Also

233

10.13.

Using Globs and Perl5 Regular Expressions to List Files

233

10.13.1. Problem

233

10.13.2. Solution

233

10.14.

Obtaining Commons Net

234

10.14.1. Problem

234

10.14.2. Solution

234

10.14.3. Discussion

234

10.14.4. See Also

234

10.15.

Writing an FTP Client

234

10.15.1. Problem

234

10.15.2. Solution

235

10.15.3. Discussion

235

10.15.4. See Also

236

10.16.

Sending Mail with SMTP

236

10.16.1. Problem

236

10.16.2. Solution

236

10.16.3. Discussion

237

10.16.4. See Also

237

10.17.

Checking a POP3 Mailbox

238

10.17.1. Problem

238

10.17.2. Solution

238

10.17.3. Discussion

239

10.17.4. See Also

239

11. HTTP and WebDAV

240

11.1.

Introduction

240

11.1.

Obtaining HttpClient

240

11.1.1. Problem

240

11.1.2. Solution

240

11.1.3. Discussion

240

11.1.4. See Also

241

11.3.

Performing an HTTP GET

241

 

11.3.1. Problem

241

11.3.2. Solution

241

11.3.3. Discussion

242

11.3.4. See Also

242

11.4.

Sending Parameters in a Query String

242

11.4.1. Problem

242

11.4.2. Solution

242

11.4.3. Discussion

243

Common Java Cookbook

 

11.4.4.

See Also

244

11.5. Retrieving Content with a Conditional GET

244

 

11.5.1. Problem

244

11.5.2. Solution

244

 

11.5.3. Discussion

246

 

11.5.4. See Also

246

11.6. Debugging HTTP Communications

246

 

11.6.1. Problem

247

11.6.2. Solution

247

 

11.6.3. Discussion

248

11.7. Making an HTTP POST Request

248

 

11.7.1. Problem

248

 

11.7.2. Discussion

249

11.7.3. Discussion

249

 

11.7.4. See Also

250

11.8. Sending POST Data from a File

250

 

11.8.1. Problem

250

11.8.2. Solution

250

 

11.8.3. Discussion

251

11.9. Uploading Files with a Multipart POST

251

 

11.9.1. Problem

251

11.9.2. Solution

251

 

11.9.3. Discussion

252

 

11.9.4. See Also

252

11.10.

Basic Authentication

252

11.10.1. Problem

252

11.10.2. Solution

253

11.10.3. Discussion

253

11.10.4. See Also

255

11.11.

NTLM Authentication

255

11.11.1. Problem

255

11.11.2. Solution

255

11.11.3. Discussion

255

11.11.4. See Also

256

11.12.

Working with Cookies

256

11.12.1. Problem

256

11.12.2. Solution

256

11.12.3. Discussion

257

11.12.4. See Also

258

11.13.

Handling Redirects

258

11.13.1. Problem

258

11.13.2. Solution

258

11.13.3. Discussion

259

11.13.4. See Also

260

11.14.

SSL

260

11.14.1. Problem

260

11.14.2. Solution

260

11.14.3. Discussion

261

11.14.4. See Also

261

Common Java Cookbook

11.15.

Accepting a Self-Signed Certificate

261

11.15.1. Problem

262

11.15.2. Solution

262

11.15.3. Discussion

262

11.15.4. See Also

262

11.16.

Obtaining Jakarta Slide

263

11.16.1. Problem

263

11.16.2. Solution

263

11.16.3. Discussion

263

11.16.4. See Also

264

11.17.

Connecting to WebDAV Resources

264

11.17.1. Problem

264

11.17.2. Solution

264

11.17.3. Discussion

265

11.18.

Modifying a WebDAV Resource

266

11.18.1. Problem

266

11.18.2. Solution

266

11.18.3. Discussion

266

11.18.4. See Also

267

12. Searching and Filtering

268

12.1.

Introduction

268

12.1.

Obtaining Commons JXPath

268

12.1.1. Problem

268

12.1.2. Solution

268

12.1.3. Discussion

269

12.1.4. See Also

269

12.2.

Querying an Object Graph with XPath

269

12.2.1. Problem

269

12.2.2. Solution

269

12.2.3. Discussion

270

12.2.4. See Also

270

12.3.

Search a Collection of Simple Objects

270

12.3.1. Problem

271

12.3.2. Solution

271

12.3.3. Discussion

272

12.3.4. See Also

272

12.4.

Applying XPath Queries to Complex Object Graphs

272

12.4.1. Problem

272

12.4.2. Solution

272

12.4.3. Discussion

274

12.4.4. See Also

275

12.5.

Obtaining Lucene

275

12.5.1. Problem

275

12.5.2. Solution

275

12.5.3. Discussion

276

12.5.4. See Also

276

12.6.

Creating an Index of XML Documents

276

12.6.1. Problem

276

12.6.2. Solution

276

Common Java Cookbook

 

12.6.3. Discussion

279

12.6.4. See Also

280

12.7. Searching for a Specific Term in a Document Index

280

12.7.1. Problem

280

12.7.2. Solution

280

12.7.3. Discussion

282

12.8. Finding the Frequency of Terms in an Index

283

12.8.1. Problem

283

12.8.2. Solution

283

12.8.3. Discussion

285

Index

286

Copyright and License

Copyright © 2009 Common Java Cookbook DocBook XML Content. Some rights reserved.

Published by Common Java Cookbook DocBook XML Content, 626 Grove St., Suite 201, Evanston, IL 60202.

Java and all Java-based trademarks and logos are trademarks or registered trademarks of Sun Microsystems, Inc., in the United States and other countries. Discursive is independent of Sun Microsystems, Inc.

Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in this book, and Discursive was aware of a trademark claim, the designations have been printed in caps or initial caps.

While every precaution has been taken in the preparation of this book, the publisher and authors assume no responsibility for errors or omissions, or for damages resulting from the use of the information contained herein.

1. Creative Commons BY-NC-ND 3.0 US License

THE WORK (AS DEFINED BELOW) IS PROVIDED UNDER THE TERMS OF THIS CREATIVE COMMONS PUBLIC LICENSE ("CCPL" OR "LICENSE"). THE WORK IS PROTECTED BY COPYRIGHT AND/OR OTHER APPLICABLE LAW. ANY USE OF THE WORK OTHER THAN AS AUTHORIZED UNDER THIS LICENSE OR COPYRIGHT LAW IS PROHIBITED.

BY EXERCISING ANY RIGHTS TO THE WORK PROVIDED HERE, YOU ACCEPT AND AGREE TO BE BOUND BY THE TERMS OF THIS LICENSE. TO THE EXTENT THIS LICENSE MAY BE CONSIDERED TO BE A CONTRACT, THE LICENSOR GRANTS YOU THE RIGHTS CONTAINED HERE IN CONSIDERATION OF YOUR ACCEPTANCE OF SUCH TERMS AND CONDITIONS.

1. Definitions

a. "Collective Work" means a work, such as a periodical issue, anthology or encyclopedia, in which the Work in its entirety in unmodified form, along with one or more other contributions, constituting separate and independent works in themselves, are assembled into a collective whole. A work that constitutes a Collective Work will not be considered a Derivative Work (as defined below) for the purposes of this License.

b. "Derivative Work" means a work based upon the Work or upon the Work and other pre-existing works, such as a translation, musical arrangement, dramatization, fictionalization, motion picture version, sound recording, art reproduction, abridgment, condensation, or any other form in which the Work may be recast, transformed, or adapted, except that a work that constitutes a Collective Work will not be considered a Derivative Work for the purpose of this License. For the avoidance of doubt, where the Work is a musical composition or sound recording, the synchronization of the Work in timed-relation with a moving image ("synching") will be considered a Derivative Work for the purpose of this License.

c. "Licensor" means the individual, individuals, entity or entities that offers the Work under the terms of this License.

d. "Original Author" means the individual, individuals, entity or entities who created the Work.

e. "Work" means the copyrightable work of authorship offered under the terms of this License.

Copyright and License

f. "You" means an individual or entity exercising rights under this License who has not previously violated the terms of this License with respect to the Work, or who has received express permission from the Licensor to exercise rights under this License despite a previous violation.

2. Fair Use Rights. Nothing in this license is intended to reduce, limit, or restrict any rights arising from fair use, first sale or other limitations on the exclusive rights of the copyright owner under copyright law or other applicable laws.

3. License Grant. Subject to the terms and conditions of this License, Licensor hereby grants You a worldwide, royalty-free, non-exclusive, perpetual (for the duration of the applicable copyright) license to exercise the rights in the Work as stated below:

a. to reproduce the Work, to incorporate the Work into one or more Collective Works, and to reproduce the Work as incorporated in the Collective Works; and,

b. to distribute copies or phonorecords of, display publicly, perform publicly, and perform publicly by means of a

digital audio transmission the Work including as incorporated in Collective Works. The above rights may be exercised in all media and formats whether now known or hereafter devised. The above rights include the right to make such modifications as are technically necessary to exercise the rights in other media and formats, but otherwise you have no rights to make Derivative Works. All rights not expressly granted by Licensor are hereby reserved, including but not limited to the rights set forth in Sections 4(d) and 4(e).

4. Restrictions.The license granted in Section 3 above is expressly made subject to and limited by the following restrictions:

a. You may distribute, publicly display, publicly perform, or publicly digitally perform the Work only under the terms of this License, and You must include a copy of, or the Uniform Resource Identifier for, this License with every copy or phonorecord of the Work You distribute, publicly display, publicly perform, or publicly digitally perform. You may not offer or impose any terms on the Work that restrict the terms of this License or the ability of a recipient of the Work to exercise the rights granted to that recipient under the terms of the License. You may not sublicense the Work. You must keep intact all notices that refer to this License and to the disclaimer of warranties. When You distribute, publicly display, publicly perform, or publicly digitally perform the Work, You may not impose any technological measures on the Work that restrict the ability of a recipient of the Work from You to exercise the rights granted to that recipient under the terms of the License. This Section 4(a) applies to the Work as incorporated in a Collective Work, but this does not require the Collective Work apart from the Work itself to be made subject to the terms of this License. If You create a Collective Work, upon notice from any Licensor You must, to the extent practicable, remove from the Collective Work any credit as required by Section 4(c), as requested.

b. You may not exercise any of the rights granted to You in Section 3 above in any manner that is primarily intended for or directed toward commercial advantage or private monetary compensation. The exchange of the Work for other copyrighted works by means of digital file-sharing or otherwise shall not be considered to be intended for or directed toward commercial advantage or private monetary compensation, provided there is no payment of any monetary compensation in connection with the exchange of copyrighted works.

c. If You distribute, publicly display, publicly perform, or publicly digitally perform the Work (as defined in Section 1 above) or Collective Works (as defined in Section 1 above), You must, unless a request has been made pursuant to Section 4(a), keep intact all copyright notices for the Work and provide, reasonable to the medium or means You are utilizing: (i) the name of the Original Author (or pseudonym, if applicable) if supplied, and/or (ii) if the Original Author and/or Licensor designate another party or parties (e.g. a sponsor institute, publishing entity,

Copyright and License

journal) for attribution ("Attribution Parties") in Licensor's copyright notice, terms of service or by other reasonable means, the name of such party or parties; the title of the Work if supplied; to the extent reasonably practicable, the Uniform Resource Identifier, if any, that Licensor specifies to be associated with the Work, unless such URI does not refer to the copyright notice or licensing information for the Work. The credit required by this Section 4(c) may be implemented in any reasonable manner; provided, however, that in the case of a Collective Work, at a minimum such credit will appear, if a credit for all contributing authors of the Collective Work appears, then as part of these credits and in a manner at least as prominent as the credits for the other contributing authors. For the avoidance of doubt, You may only use the credit required by this clause for the purpose of attribution in the manner set out above and, by exercising Your rights under this License, You may not implicitly or explicitly assert or imply any connection with, sponsorship or endorsement by the Original Author, Licensor and/or Attribution Parties, as appropriate, of You or Your use of the Work, without the separate, express prior written permission of the Original Author, Licensor and/or Attribution Parties.

d. For the avoidance of doubt, where the Work is a musical composition:

i. Performance Royalties Under Blanket Licenses. Licensor reserves the exclusive right to collect whether individually or, in the event that Licensor is a member of a performance rights society (e.g. ASCAP, BMI, SESAC), via that society, royalties for the public performance or public digital performance (e.g. webcast) of the Work if that performance is primarily intended for or directed toward commercial advantage or private monetary compensation.

ii. Mechanical Rights and Statutory Royalties. Licensor reserves the exclusive right to collect, whether individually or via a music rights agency or designated agent (e.g. Harry Fox Agency), royalties for any phonorecord You create from the Work ("cover version") and distribute, subject to the compulsory license created by 17 USC Section 115 of the US Copyright Act (or the equivalent in other jurisdictions), if Your distribution of such cover version is primarily intended for or directed toward commercial advantage or private monetary compensation.

e. Webcasting Rights and Statutory Royalties. For the avoidance of doubt, where the Work is a sound recording, Licensor reserves the exclusive right to collect, whether individually or via a performance-rights society (e.g. SoundExchange), royalties for the public digital performance (e.g. webcast) of the Work, subject to the compulsory license created by 17 USC Section 114 of the US Copyright Act (or the equivalent in other jurisdictions), if Your public digital performance is primarily intended for or directed toward commercial advantage or private monetary compensation.

5. Representations, Warranties and Disclaimer UNLESS OTHERWISE MUTUALLY AGREED TO BY THE PARTIES IN WRITING, LICENSOR OFFERS THE WORK AS-IS AND ONLY TO THE EXTENT OF ANY RIGHTS HELD IN THE LICENSED WORK BY THE LICENSOR. THE LICENSOR MAKES NO REPRESENTATIONS OR WARRANTIES OF ANY KIND CONCERNING THE WORK, EXPRESS, IMPLIED, STATUTORY OR OTHERWISE, INCLUDING, WITHOUT LIMITATION, WARRANTIES OF TITLE, MARKETABILITY, MERCHANTIBILITY, FITNESS FOR A PARTICULAR PURPOSE, NONINFRINGEMENT, OR THE ABSENCE OF LATENT OR OTHER DEFECTS, ACCURACY, OR THE PRESENCE OF ABSENCE OF ERRORS, WHETHER OR NOT DISCOVERABLE. SOME JURISDICTIONS DO NOT ALLOW THE EXCLUSION OF IMPLIED WARRANTIES, SO SUCH EXCLUSION MAY NOT APPLY TO YOU.

6. Limitation on Liability. EXCEPT TO THE EXTENT REQUIRED BY APPLICABLE LAW, IN NO EVENT WILL LICENSOR BE LIABLE TO YOU ON ANY LEGAL THEORY FOR ANY SPECIAL, INCIDENTAL,

Copyright and License

CONSEQUENTIAL, PUNITIVE OR EXEMPLARY DAMAGES ARISING OUT OF THIS LICENSE OR THE USE OF THE WORK, EVEN IF LICENSOR HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH

DAMAGES.

7. Termination

a. This License and the rights granted hereunder will terminate automatically upon any breach by You of the terms of this License. Individuals or entities who have received Collective Works (as defined in Section 1 above) from You under this License, however, will not have their licenses terminated provided such individuals or entities remain in full compliance with those licenses. Sections 1, 2, 5, 6, 7, and 8 will survive any termination of this License.

b. Subject to the above terms and conditions, the license granted here is perpetual (for the duration of the applicable copyright in the Work). Notwithstanding the above, Licensor reserves the right to release the Work under different license terms or to stop distributing the Work at any time; provided, however that any such election will not serve to withdraw this License (or any other license that has been, or is required to be, granted under the terms of this License), and this License will continue in full force and effect unless terminated as stated above.

8. Miscellaneous

a. Each time You distribute or publicly digitally perform the Work (as defined in Section 1 above) or a Collective Work (as defined in Section 1 above), the Licensor offers to the recipient a license to the Work on the same terms and conditions as the license granted to You under this License.

b. If any provision of this License is invalid or unenforceable under applicable law, it shall not affect the validity or enforceability of the remainder of the terms of this License, and without further action by the parties to this agreement, such provision shall be reformed to the minimum extent necessary to make such provision valid and enforceable.

c. No term or provision of this License shall be deemed waived and no breach consented to unless such waiver or consent shall be in writing and signed by the party to be charged with such waiver or consent.

d. This License constitutes the entire agreement between the parties with respect to the Work licensed here. There

are no understandings, agreements or representations with respect to the Work not specified here. Licensor shall not be bound by any additional provisions that may appear in any communication from You. This License may not be modified without the mutual written agreement of the Licensor and You. Creative Commons Notice

Creative Commons is not a party to this License, and makes no warranty whatsoever in connection with the Work. Creative Commons will not be liable to You or any party on any legal theory for any damages whatsoever, including without limitation any general, special, incidental or consequential damages arising in connection to this license. Notwithstanding the foregoing two (2) sentences, if Creative Commons has expressly identified itself as the Licensor hereunder, it shall have all rights and obligations of Licensor.

Except for the limited purpose of indicating to the public that the Work is licensed under the CCPL, Creative Commons does not authorize the use by either party of the trademark "Creative Commons" or any related trademark or logo of Creative Commons without the prior written consent of Creative Commons. Any permitted use will be in compliance with Creative Commons' then-current trademark usage guidelines, as may be published on its website or otherwise made available upon request from time to time. For the avoidance of doubt, this trademark restriction does not form part of this License.

Creative Commons may be contacted at http://creativecommons.org/.

Foreword: 0.19

May 17, 2009 - I've had some great feedback after putting the book up on the web site, in the last week, I've open sourced the book, and I'll be slowly upgrading the book project infrastructure. Again, stay tuned.

Edition: 0.19

February 20, 2009 - This is an early version of the second edition of Jakarta Commons Cookbook. I'm updating the content, and you might experience some problems with links between chapters and sections. Don't rely on any of the URLs in this book just yet, I'm currently renaming all of the sections and chapters so that every section has a reasonable URL. I'm also trying to find some interesting ways to link to related O'Reilly content using the new O'Reilly metadata interface that was just published by O'Reilly Labs. Stay Tuned.

Preface

In this book, you'll find information about a set of libraries developed within the Apache Commons (also referred to as "Commons"). Commons (http://commons.apache.org/) is a set of small, popular components which forms a Top-level Project at the Apache Software Foundation. Ranging from the elementary to the complex, many would consider some of these libraries indispensable to any Java project. These components are so widespread, they may already be on your classpath. If you develop an application using Wicket, Maven, Struts, Tomcat, Spring, Hibernate, or any other popular Java library, you likely have Commons Lang and Commons BeanUtils in your classpath. If you just installed Red Hat Enterprise Linux with the default configuration, you've got Commons libraries somewhere in /usr. While Apache Commons may be everywhere, many are still unaware of the capabilities these components provide. This book is an attempt to provide some documentation for these popular components.

This book focuses on tactical implementation details, answering such questions as: How do we parse XML? How do we serialize beans? Is there an easier way to work with Collections? How do we work with HTTP and keep track of cookies? In enterprise software development, the tactical is often sacrificed for the strategic. Consider a complex enterprise-scale system with a solid, well-conceived architecture. The strategic (or high-level) design appears reasonable from 40,000 feet, but as soon as you drill into the details, you notice that every component contains pages upon pages of unmaintainable and unnecessary code because the developers were not aware of some valuable time-saver like BeanUtils, Collections, or the Digester. Or, worse, the developer may have spent a week reimplementing most of the capabilities of Commons BeanUtils even though BeanUtils was already in the classpath. While a familiarity with Apache Commons may not directly affect the architecture of your application, knowing what Apache Commons can do often helps to inform decisions made at the class level.

Few application developers would consider writing a custom XML parser, but developers will frequently write custom components that duplicate freely available libraries. Take, as an example, a set of static utility methods that seems to pop up in almost every complex project. A common process such as reading a file to a String may be refactored into a CommonFileUtils class, or turning a DOM Document into a set of beans may be accomplished with a set of classes in some custom code. Apache Commons provides solutions to both of these problems and many more, and reading this book may help you avoid unnecessary wheel reinvention.

Many people know of these components in a general sense, but few have the months or weeks necessary to sit down and read the relevant tutorials, FAQs, blogs, and archived mailing lists associated with each component. The amount of work involved in keeping up-to-date with an array of open source communities is not trivial. This is why I've tried to compact much of this information into easily accessible recipes. These recipes were written to provide you with the information you need to start using Commons in a few minutes, but the Discussion and See Also sections give you an opportunity to dig deeper into the motivation behind each Commons component if you need more information.

The tools introduced herein save you serious time and provide you with a set of alternatives you may not currently be aware of. I wish I had read a book like this five years ago; it would have accelerated my learning and helped me to avoid some costly design decisions. Use this text as you will; if you are only interested in Commons Collections, you should be able to quickly familiarize yourself with Collections by browsing Chapter 5. On the other hand, if you are looking for a survey of some of the major projects in Apache Commons, read this book from start to finish. Part structured reference, part prose, the cookbook format lets you customize your reading experience, and I hope this book is as interesting to read as it was to write.

1. What's Inside

This book covers components from Apache Commons, and a few projects outside of the Apache Software Foundation. This book covers the following components:

Preface

• Apache Commons BeanUtils

• Apache Commons Betwixt

• Apache Commons CLI

• Apache Commons Codec

• Apache Commons Collections

• Apache Commons Configuration

• Apache Commons Digester

• Apache Commons HttpClient

• Apache Commons ID

• Apache Commons IO

• Apache Commons JEXL

• Apache Commons JXPath

• Apache Commons Lang

• Apache Commons Logging

• Apache Commons Math

• Apache Commons Net

• Apache Log4J

• Apache Velocity

• FreeMarker

• Apache Lucene

• Apache Slide

All of these projects are covered in detail in the following chapters. Here's what's in each chapter:

Chapter 1, Supplements to the Java 2 Platform This chapter introduces Commons Lang. Automation of toString( ), working with arrays, formatting and rounding dates, working with enumerations, generating identifiers, and measuring time are some of the topics discussed in this chapter. This chapter also covers the generation of unique identifiers with Commons ID.

Chapter 2, Manipulating Text While Java does not have the extensive text manipulation capabilities of a scripting language like Perl, Commons Lang's StringUtils has a number of utility methods that can be used to manipulate text. This chapter deals with

StringUtils, WordUtils, and Commons Codec.

Preface

Chapter 3, JavaBeans Beans appear throughout Java; from Apache Struts to Hibernate, beans are a unit of information in an object model. This chapter introduces Commons BeanUtils, one of the most widely used components from Apache Commons.

Chapter 4, Functors Functors are a fundamental way of thinking about programming as a set of functional objects. Commons Collections introduced predicates, transformers, and closures, and functors, which can be used to model control structures and loops. This chapter demonstrates how one would apply functors to any program.

Chapter 5, Collections Iterators, filtering with predicates, buffers, queues, bidirectional maps, type-safe collections, constraining collections, lazy maps, and set operations are a few of the topics introduced in this chapter. This chapter deals with Commons Collections, new collection types introduced, and the application of functors to various collections.

Chapter 6, XML If you are constantly parsing or creating XML documents, this chapter introduces some alternatives to the standard parser APIs (SAX, DOM, and JDOM). This chapter introduces Commons Digester, Commons Betwixt, and Commons JXPath.

Chapter 7, Application Infrastructure Commons Configuration is introduced as a way to parse properties files and XML configuration files. Other recipes in this chapter show how Commons CLI can be used to parse a complex set of required and optional command-line options. This chapter also details the configuration and use of Commons Logging and Apache Log4J.

Chapter 8, Math This chapter focuses on simple mathematical capabilities in both Commons Lang and Commons Math. This chapter introduces classes to work with fractions, complex numbers, matrices, and simple univariate statistics.

Chapter 9, Templating This chapter deals with simple expression languages such as Commons JEXL to more complex templating engines such as Apache Velocity and FreeMarker. This chapter also demonstrates the integration of both Velocity and FreeMarker with a J2EE servlet container such as Apache Tomcat.

Chapter 10, I/O and Networking This chapter introduces Commons IO, which contains a number of utilities for working with streams and files, and Commons Net, which contains simple clients for the FTP, POP, and SMTP protocols.