Highlights of Apache Commons Lang, Part 1

Highlights of Apache Commons Lang, Part 1

By Lance Finney, OCI Principal Software Engineer

July 2009


Introduction

The Apache Commons libraries are a rich set of Java libraries. Commons Lang is the library within the suite which adds many helper methods for the core of Java SE. Many developers are familiar with parts of the library, but are likely not familiar with the breadth of useful components in the library.

This article is not a comprehensive review of all of the methods of the library; the Javadocs provide that level of detail. Instead, this article exposes to the reader many of the useful tools within the library, specifically those within the org.apache.commons.lang package. The tools within subpackages of org.apache.commons.lang will be covered in a later article.

Commons Lang uses the open source Apache License, and it is available for download from http://commons.apache.org/downloads/download_lang.cgi.

SerializationUtils

SerializationUtils provides a few convenience methods for serializing and deserializing Serializable objects. As is the case for many methods in Commons Lang, these serialize and deserialize methods do nothing particularly fancy. However, they hide a lot of the boilerplate exception and resource handling necessary for certain APIs.

The other method that SerializationUtils provides is clone(Serializable object), which provides a valid deep cloning service for Serializable objects. This is much less efficient than a custom clone implementation, but it can be an easy alternate implementation for simple classes.

SystemUtils

SystemUtils is a simple class that provides components for accessing information about the operating system and the JVM. Most of the information is provided through constants, but there are also methods that return File objects. For example, there is one that returns a File object representing the user's home directory on the local machine..

The information presented by SystemUtils is really just the information that anyone could get from the System properties. What SystemUtils provides is a simple, consistent way of getting to the information without having to remember the System property keys.

Here is an example of a bit of the information provided on my machine:

  1. package com.ociweb.jnb.jul2009;
  2.  
  3. import org.apache.commons.lang.SystemUtils;
  4.  
  5.  
  6. public class SystemExample {
  7. public static void main(String[] args) {
  8. System.out.println("SystemUtils.AWT_TOOLKIT = " +
  9. SystemUtils.AWT_TOOLKIT);
  10. System.out.println("SystemUtils.FILE_ENCODING = " +
  11. SystemUtils.FILE_ENCODING);
  12. System.out.println("SystemUtils.FILE_SEPARATOR = " +
  13. SystemUtils.FILE_SEPARATOR);
  14.  
  15. System.out.println("SystemUtils.IS_JAVA_1_5 = " +
  16. SystemUtils.IS_JAVA_1_5);
  17. System.out.println("SystemUtils.IS_JAVA_1_6 = " +
  18. SystemUtils.IS_JAVA_1_6);
  19.  
  20. System.out.println("SystemUtils.IS_OS_MAC_OSX = " +
  21. SystemUtils.IS_OS_MAC_OSX);
  22. System.out.println("SystemUtils.IS_OS_WINDOWS = " +
  23. SystemUtils.IS_OS_WINDOWS);
  24. System.out.println("SystemUtils.IS_OS_WINDOWS_VISTA = " +
  25. SystemUtils.IS_OS_WINDOWS_VISTA);
  26. System.out.println("SystemUtils.IS_OS_WINDOWS_XP = " +
  27. SystemUtils.IS_OS_WINDOWS_XP);
  28.  
  29. System.out.println("SystemUtils.JAVA_AWT_PRINTERJOB = " +
  30. SystemUtils.JAVA_AWT_PRINTERJOB);
  31.  
  32. System.out.println("SystemUtils.JAVA_HOME = " + SystemUtils.JAVA_HOME);
  33.  
  34. System.out.println("SystemUtils.JAVA_VERSION = " +
  35. SystemUtils.JAVA_VERSION);
  36.  
  37. System.out.println("SystemUtils.OS_ARCH = " + SystemUtils.OS_ARCH);
  38. System.out.println("SystemUtils.OS_NAME = " + SystemUtils.OS_NAME);
  39.  
  40. System.out.println("SystemUtils.PATH_SEPARATOR = " +
  41. SystemUtils.PATH_SEPARATOR);
  42.  
  43. System.out.println("SystemUtils.USER_COUNTRY = " +
  44. SystemUtils.USER_COUNTRY);
  45.  
  46. System.out.println("SystemUtils.USER_LANGUAGE = " +
  47. SystemUtils.USER_LANGUAGE);
  48.  
  49. System.out.println("SystemUtils.isJavaAwtHeadless() = " +
  50. SystemUtils.isJavaAwtHeadless());
  51. System.out.println("SystemUtils.isJavaVersionAtLeast(14) = " +
  52. SystemUtils.isJavaVersionAtLeast(14));
  53. System.out.println("SystemUtils.isJavaVersionAtLeast(1.4f) = " +
  54. SystemUtils.isJavaVersionAtLeast(1.4f));
  55. }
  56. }
  57. > SystemUtils.AWT_TOOLKIT = sun.awt.windows.WToolkit
  58. > SystemUtils.FILE_ENCODING = windows-1252
  59. > SystemUtils.FILE_SEPARATOR = \
  60. > SystemUtils.IS_JAVA_1_5 = false
  61. > SystemUtils.IS_JAVA_1_6 = true
  62. > SystemUtils.IS_OS_MAC_OSX = false
  63. > SystemUtils.IS_OS_WINDOWS = true
  64. > SystemUtils.IS_OS_WINDOWS_VISTA = false
  65. > SystemUtils.IS_OS_WINDOWS_XP = true
  66. > SystemUtils.JAVA_AWT_PRINTERJOB = sun.awt.windows.WPrinterJob
  67. > SystemUtils.JAVA_HOME = C:\Program Files\Java\jdk1.6.0_12\fastdebug\jre
  68. > SystemUtils.JAVA_VERSION = 1.6.0_12-ea-fastdebug
  69. > SystemUtils.OS_ARCH = x86
  70. > SystemUtils.OS_NAME = Windows XP
  71. > SystemUtils.PATH_SEPARATOR = ;
  72. > SystemUtils.USER_COUNTRY = US
  73. > SystemUtils.USER_LANGUAGE = en
  74. > SystemUtils.isJavaAwtHeadless() = false
  75. > SystemUtils.isJavaVersionAtLeast(14) = true
  76. > SystemUtils.isJavaVersionAtLeast(1.4f) = true

String Manipulation

Commons Lang provides several component classes for manipulating and examining Strings. StringUtils is the most important of these, but StringEscapeUtilsRandomStringUtils, and WordUtils are also useful.

StringUtils

StringUtils provides many useful small components for analyzing Strings. In many cases (as in contains(String, String) and equals(String, String)), the methods here are simply versions of methods that the JDK provides, with additional handling for null inputs.

Here are examples of a subset of the provided methods. Please see the Javadocs for more details on how nulls are handled and to see overloaded versions of the methods demonstrated here.

  1. package com.ociweb.jnb.jul2009;
  2.  
  3. import org.apache.commons.lang.StringUtils;
  4.  
  5. import java.util.Arrays;
  6.  
  7.  
  8. public class StringUtilsExample {
  9. public static void main(String[] args) {
  10.  
  11. // cuts the String down to never be longer than 7, using an ellipsis
  12. System.out.println(
  13. "StringUtils.abbreviate(\"This text is just too long.\", 7) = " +
  14. StringUtils.abbreviate("This text is just too long.", 7));
  15.  
  16. // capitalizes, uncapitalizes, lowercases, or uppercases the word
  17. System.out.println("StringUtils.capitalize(\"faMily\") = " +
  18. StringUtils.capitalize("faMily"));
  19. System.out.println("StringUtils.uncapitalize(\"FaMily\") = " +
  20. StringUtils.uncapitalize("FaMily"));
  21. System.out.println("StringUtils.lowerCase(\"faMily\") = " +
  22. StringUtils.lowerCase("faMily"));
  23. System.out.println("StringUtils.upperCase(\"faMily\") = " +
  24. StringUtils.upperCase("faMily"));
  25.  
  26. // centers the word, padding with spaces
  27. System.out.println("StringUtils.center(\"Title\", 15) = '" +
  28. StringUtils.center("Title", 15) + "'");
  29.  
  30. // removes the given separator from the end of the String, if necessary
  31. System.out.println(
  32. "StringUtils.chomp(\"I like apple pie!\", \"!\") = " +
  33. StringUtils.chomp("I like apple pie!", "!"));
  34.  
  35. // removes the last character from the String
  36. System.out.println("StringUtils.chop(\"I like apple pie!\") = " +
  37. StringUtils.chop("I like apple pie!"));
  38.  
  39. // similar to String.contains(), but is nullsafe
  40. // there are many similar methods (containsAny, containsIgnoreCase, etc)
  41. System.out.println(
  42. "StringUtils.contains(\"I like apple pie!\", \"apple\") = " +
  43. StringUtils.contains("I like apple pie!", "apple"));
  44.  
  45. // returns either the first String or the second String (if the first
  46. // is null or empty)
  47. System.out.println("StringUtils.defaultIfEmpty(null, \"oops!\") = " +
  48. StringUtils.defaultIfEmpty(null, "oops!"));
  49.  
  50. // removes all whitespace from the String
  51. System.out.println(
  52. "StringUtils.deleteWhitespace(\"I like apple pie!\") = " +
  53. StringUtils.deleteWhitespace("I like apple pie!"));
  54.  
  55. // returns the part of the second String after a difference is seen
  56. System.out.println("StringUtils.difference(\"I like apple pie!\", " +
  57. "\"I like cherry pie!\") = " +
  58. StringUtils.difference("I like apple pie!", "I like cherry pie!"));
  59.  
  60. // nullsafe check on the end or beginning of a String
  61. System.out.println(
  62. "StringUtils.endsWith(\"I like apple pie!\", \"cake!\") = " +
  63. StringUtils.endsWith("I like apple pie!", "cake!"));
  64. System.out.println(
  65. "StringUtils.startsWith(\"I like apple pie!\", \"I \") = " +
  66. StringUtils.startsWith("I like apple pie!", "I "));
  67.  
  68. // nullsafe equality check
  69. System.out.println(
  70. "StringUtils.equals(null, \"I like apple pie!\") = " +
  71. StringUtils.equals(null, "I like apple pie!"));
  72.  
  73. // returns the commons prefix of an array of Strings
  74. System.out.println(
  75. "StringUtils.getCommonPrefix(new String[] {\"bar\", \"baz\"}) = " +
  76. StringUtils.getCommonPrefix(new String[] { "bar", "baz" }));
  77.  
  78. // returns the number of character changes needed to turn one String
  79. // into another
  80. System.out.println(
  81. "StringUtils.getLevenshteinDistance(\"I like pie!\", " +
  82. "\"I like cake!\") = " +
  83. StringUtils.getLevenshteinDistance("I like pie!", "I like cake!"));
  84.  
  85. // similar to String.indexOf(), but is nullsafe
  86. // there are many similar methods (indexOfAny, indexOfDifference, etc.)
  87. // there are also versions of lastIndexOf
  88. System.out.println(
  89. "StringUtils.indexOf(\"I like apple pie!\", \"apple\") = " +
  90. StringUtils.indexOf("I like apple pie!", "apple"));
  91.  
  92. // returns whether the String contains only unicode letters
  93. // there are similar methods for numeric, alphanumeric,
  94. // including space, etc.
  95. System.out.println("StringUtils.isAlpha(\"I like apple pie!\") = " +
  96. StringUtils.isAlpha("I like apple pie!"));
  97.  
  98. // nullsafe checks for empty and blank Strings
  99. System.out.println("StringUtils.isBlank(\"I like apple pie!\") = " +
  100. StringUtils.isBlank("I like apple pie!"));
  101. System.out.println("StringUtils.isBlank(\" \") = " +
  102. StringUtils.isBlank(" "));
  103. System.out.println("StringUtils.isBlank(\"\") = " +
  104. StringUtils.isBlank(""));
  105. System.out.println("StringUtils.isBlank(null) = " +
  106. StringUtils.isBlank(null));
  107. System.out.println("StringUtils.isEmpty(\"I like apple pie!\") = " +
  108. StringUtils.isEmpty("I like apple pie!"));
  109. System.out.println("StringUtils.isEmpty(\" \") = " +
  110. StringUtils.isEmpty(" "));
  111. System.out.println("StringUtils.isEmpty(\"\") = " +
  112. StringUtils.isEmpty(""));
  113. System.out.println("StringUtils.isEmpty(null) = " +
  114. StringUtils.isEmpty(null));
  115.  
  116. // joins the elements of the array to a single String with the given
  117. // separator
  118. System.out.println(
  119. "StringUtils.join(new Object[] {5, \"happy\", 3.14}, '-') = " +
  120. StringUtils.join(new Object[] { 5, "happy", 3.14 }, '-'));
  121.  
  122. // like String.substring, but is ok with the String being too small,
  123. // and can pad the difference
  124. System.out.println(
  125. "StringUtils.left(\"I like apple pie!\", 10) + \"'\" = '" +
  126. StringUtils.left("I like apple pie!", 10) + "'");
  127. System.out.println(
  128. "StringUtils.left(\"I like apple pie!\", 20) + \"'\" = '" +
  129. StringUtils.left("I like apple pie!", 20) + "'");
  130. System.out.println(
  131. "StringUtils.leftPad(\"I like apple pie!\", 20) + \"'\" = '" +
  132. StringUtils.leftPad("I like apple pie!", 20) + "'");
  133. System.out.println(
  134. "StringUtils.right(\"I like apple pie!\", 10) + \"'\" = '" +
  135. StringUtils.right("I like apple pie!", 10) + "'");
  136. System.out.println(
  137. "StringUtils.right(\"I like apple pie!\", 20) + \"'\" = '" +
  138. StringUtils.right("I like apple pie!", 20) + "'");
  139. System.out.println(
  140. "StringUtils.rightPad(\"I like apple pie!\", 20) + \"'\" = '" +
  141. StringUtils.rightPad("I like apple pie!", 20) + "'");
  142.  
  143. // nullsafe version of String.length()
  144. System.out.println("StringUtils.length(null) = " +
  145. StringUtils.length(null));
  146.  
  147. // similar to String.replace(), but nullsafe
  148. // there are many variants of replaceXXX methods
  149. System.out.println(
  150. "StringUtils.remove(\"I like apple pie!\", \"e\") = " +
  151. StringUtils.remove("I like apple pie!", "e"));
  152. System.out.println(
  153. "StringUtils.replace(\"I like apple pie!\", \"e\", \"u\") = " +
  154. StringUtils.replace("I like apple pie!", "e", "u"));
  155.  
  156. // creates a new String from a repetition of another String
  157. System.out.println("StringUtils.repeat(\"apple \", 5) = " +
  158. StringUtils.repeat("apple ", 5));
  159.  
  160. // similar to StringBuffer.reverse(), but nullsafe
  161. System.out.println("StringUtils.reverse(\"I like apple pie!\") = " +
  162. StringUtils.reverse("I like apple pie!"));
  163.  
  164. // splits a String into an array using whitespace as the delimiter.
  165. // There are many variant methods
  166. System.out.println("StringUtils.split(\"I like apple pie!\") = " +
  167. Arrays.toString(StringUtils.split("I like apple pie!")));
  168.  
  169. // nullsafe removal of all leading and trailing whitespace. There are
  170. // many variant methods
  171. System.out.println(
  172. "StringUtils.strip(\"\\t I like apple pie!\\r\\n\") = '" +
  173. StringUtils.strip("\t I like apple pie!\r\n") + "'");
  174.  
  175. // similar to String.substring(), but nullsafe. There are many variant
  176. // methods
  177. System.out.println(
  178. "StringUtils.substring(\"I like apple pie!\", 4) = " +
  179. StringUtils.substring("I like apple pie!", 4));
  180. System.out.println("StringUtils.substring(null, 4) = " +
  181. StringUtils.substring(null, 4));
  182.  
  183. // converts lowercase to caps and vice versa
  184. System.out.println("StringUtils.swapCase(\"I like apple pie!\") = " +
  185. StringUtils.swapCase("I like apple pie!"));
  186.  
  187. // nullsafe version of String.trim(). Leaves non-space whitespace
  188. System.out.println("StringUtils.trim(\" /tI like apple pie! \") = '" +
  189. StringUtils.trim(" /tI like apple pie! ") + "'");
  190. }
  191. }
  192. > StringUtils.abbreviate("This text is just too long.", 7) = This...
  193. > StringUtils.capitalize("faMily") = FaMily
  194. > StringUtils.uncapitalize("FaMily") = faMily
  195. > StringUtils.lowerCase("faMily") = family
  196. > StringUtils.upperCase("faMily") = FAMILY
  197. > StringUtils.center("Title", 15) = ' Title '
  198. > StringUtils.chomp("I like apple pie!", "!") = I like apple pie
  199. > StringUtils.chop("I like apple pie!") = I like apple pie
  200. > StringUtils.contains("I like apple pie!", "apple") = true
  201. > StringUtils.defaultIfEmpty(null, "oops!") = oops!
  202. > StringUtils.deleteWhitespace("I like apple pie!") = Ilikeapplepie!
  203. > StringUtils.difference("I like apple pie!", "I like cherry pie!") = cherry pie!
  204. > StringUtils.endsWith("I like apple pie!", "cake!") = false
  205. > StringUtils.startsWith("I like apple pie!", "I ") = true
  206. > StringUtils.equals(null, "I like apple pie!") = false
  207. > StringUtils.getCommonPrefix(new String[] {"bar", "baz"}) = ba
  208. > StringUtils.getLevenshteinDistance("I like pie!", "I like cake!") = 3
  209. > StringUtils.indexOf("I like apple pie!", "apple") = 7
  210. > StringUtils.isAlpha("I like apple pie!") = false
  211. > StringUtils.isBlank("I like apple pie!") = false
  212. > StringUtils.isBlank(" ") = true
  213. > StringUtils.isBlank("") = true
  214. > StringUtils.isBlank(null) = true
  215. > StringUtils.isEmpty("I like apple pie!") = false
  216. > StringUtils.isEmpty(" ") = false
  217. > StringUtils.isEmpty("") = true
  218. > StringUtils.isEmpty(null) = true
  219. > StringUtils.join(new Object[] {5, "happy", 3.14}, '-') = 5-happy-3.14
  220. > StringUtils.left("I like apple pie!", 10) + "'" = 'I like app'
  221. > StringUtils.left("I like apple pie!", 20) + "'" = 'I like apple pie!'
  222. > StringUtils.leftPad("I like apple pie!", 20) + "'" = ' I like apple pie!'
  223. > StringUtils.right("I like apple pie!", 10) + "'" = 'apple pie!'
  224. > StringUtils.right("I like apple pie!", 20) + "'" = 'I like apple pie!'
  225. > StringUtils.rightPad("I like apple pie!", 20) + "'" = 'I like apple pie! '
  226. > StringUtils.length(null) = 0
  227. > StringUtils.remove("I like apple pie!", "e") = I lik appl pi!
  228. > StringUtils.replace("I like apple pie!", "e", "u") = I liku applu piu!
  229. > StringUtils.repeat("apple ", 5) = apple apple apple apple apple
  230. > StringUtils.reverse("I like apple pie!") = !eip elppa ekil I
  231. > StringUtils.split("I like apple pie!") = [I, like, apple, pie!]
  232. > StringUtils.strip("\t I like apple pie!\r\n") = 'I like apple pie!'
  233. > StringUtils.substring("I like apple pie!", 4) = ke apple pie!
  234. > StringUtils.substring(null, 4) = null
  235. > StringUtils.swapCase("I like apple pie!") = i LIKE APPLE PIE!
  236. > StringUtils.trim(" /tI like apple pie! ") = '/tI like apple pie!'

StringEscapeUtils

StringExampleUtils provides convenient methods for correctly escaping and unescaping text for CSV, HTML, Java, JavaScript, XML, and SQL (there is no unescape for SQL):

  1. package com.ociweb.jnb.jul2009;
  2.  
  3. import org.apache.commons.lang.StringEscapeUtils;
  4.  
  5.  
  6. public class StringEscapeExample {
  7. private static final String[] testStrings = {
  8. "Simple", "I told him, \"She said, \'Hey, are you there?\'\"",
  9. "static class Foo<T extends List & Serializable>,
  10. "Intel® Pentium™ 4 @ 2.40 GHz"
  11. };
  12.  
  13. public static void main(String[] args) {
  14.  
  15. // escapeCsv adds quotes, if needed
  16. for (String testString : testStrings) {
  17. final String escaped = StringEscapeUtils.escapeCsv(testString);
  18. final String unescaped = StringEscapeUtils.unescapeCsv(escaped);
  19.  
  20. System.out.println("StringEscapeUtils.escapeCsv(\"" + testString +
  21. "\") = \n\t" + escaped);
  22. System.out.println("unescaped = " + unescaped);
  23. }
  24.  
  25. System.out.println();
  26.  
  27. // escapeHtml escapes html special characters
  28. for (String testString : testStrings) {
  29. final String escaped = StringEscapeUtils.escapeHtml(testString);
  30. final String unescaped = StringEscapeUtils.unescapeHtml(escaped);
  31.  
  32. System.out.println("StringEscapeUtils.escapeHtml(\"" + testString +
  33. "\") = \n\t" + escaped);
  34. System.out.println("unescaped = " + unescaped);
  35. }
  36.  
  37. System.out.println();
  38.  
  39. // escapeJava escapes Java special characters
  40. for (String testString : testStrings) {
  41. final String escaped = StringEscapeUtils.escapeJava(testString);
  42. final String unescaped = StringEscapeUtils.unescapeJava(escaped);
  43.  
  44. System.out.println("StringEscapeUtils.escapeJava(\"" + testString +
  45. "\") = \n\t" + escaped);
  46. System.out.println("unescaped = " + unescaped);
  47. }
  48.  
  49. System.out.println();
  50.  
  51. // escapeJavaScript escapes JavaScript special characters
  52. for (String testString : testStrings) {
  53. final String escaped = StringEscapeUtils.escapeJavaScript(
  54. testString);
  55. final String unescaped = StringEscapeUtils.unescapeJavaScript(
  56. escaped);
  57.  
  58. System.out.println("StringEscapeUtils.escapeJavaScript(\"" +
  59. testString + "\") = \n\t" + escaped);
  60. System.out.println("unescaped = " + unescaped);
  61. }
  62.  
  63. System.out.println();
  64.  
  65. // escapeSql escapes Sql special characters
  66. for (String testString : testStrings) {
  67. final String escaped = StringEscapeUtils.escapeSql(testString);
  68.  
  69. System.out.println("StringEscapeUtils.escapeSql(\"" + testString +
  70. "\") = \n\t" + escaped);
  71. }
  72.  
  73. System.out.println();
  74.  
  75. // escapeXml escapes Xml special characters (similar to html, but also
  76. // escapes '
  77. for (String testString : testStrings) {
  78. final String escaped = StringEscapeUtils.escapeXml(testString);
  79. final String unescaped = StringEscapeUtils.unescapeXml(escaped);
  80.  
  81. System.out.println("StringEscapeUtils.escapeXml(\"" + testString +
  82. "\") = \n\t" + escaped);
  83. System.out.println("unescaped = " + unescaped);
  84. }
  85. }
  86.  
  87. }
  88. > StringEscapeUtils.escapeCsv("Simple") =
  89. > Simple
  90. > unescaped = Simple
  91. > StringEscapeUtils.escapeCsv("I told him, "She said,
  92. > 'Hey, are you there?'"") =
  93. > "I told him, ""She said, 'Hey, are you there?'"""
  94. > unescaped = I told him, "She said, 'Hey, are you there?'"
  95. > StringEscapeUtils.escapeCsv("static class Foo<T extends List &
  96. > Serializable>") =
  97. > static class Foo<T extends List & Serializable>
  98. > unescaped = static class Foo<T extends List & Serializable>
  99. > StringEscapeUtils.escapeCsv("Intel® Pentium™ 4 @ 2.40 GHz") =
  100. > Intel® Pentium™ 4 @ 2.40 GHz
  101. > unescaped = Intel® Pentium™ 4 @ 2.40 GHz
  102. >
  103. > StringEscapeUtils.escapeHtml("Simple") =
  104. > Simple
  105. > unescaped = Simple
  106. > StringEscapeUtils.escapeHtml("I told him, "She said,
  107. > 'Hey, are you there?'"") =
  108. > I told him, "She said, 'Hey, are you there?'"
  109. > unescaped = I told him, "She said, 'Hey, are you there?'"
  110. > StringEscapeUtils.escapeHtml("static class Foo<T extends List &
  111. > Serializable>") =
  112. > static class Foo<T extends List & Serializable>
  113. > unescaped = static class Foo<T extends List & Serializable>
  114. > StringEscapeUtils.escapeHtml("Intel® Pentium™ 4 @ 2.40 GHz") =
  115. > Intel® Pentium™ 4 @ 2.40 GHz
  116. > unescaped = Intel® Pentium™ 4 @ 2.40 GHz
  117. >
  118. > StringEscapeUtils.escapeJava("Simple") =
  119. > Simple
  120. > unescaped = Simple
  121. > StringEscapeUtils.escapeJava("I told him, "She said,
  122. > 'Hey, are you there?'"") =
  123. > I told him, \"She said, 'Hey, are you there?'\"
  124. > unescaped = I told him, "She said, 'Hey, are you there?'"
  125. > StringEscapeUtils.escapeJava("static class Foo<T extends List &
  126. > Serializable>") =
  127. > static class Foo<T extends List & Serializable>
  128. > unescaped = static class Foo<T extends List & Serializable>
  129. > StringEscapeUtils.escapeJava("Intel® Pentium™ 4 @ 2.40 GHz") =
  130. > Intel\u00AE Pentium\u2122 4 @ 2.40 GHz
  131. > unescaped = Intel® Pentium™ 4 @ 2.40 GHz
  132. >
  133. > StringEscapeUtils.escapeJavaScript("Simple") =
  134. > Simple
  135. > unescaped = Simple
  136. > StringEscapeUtils.escapeJavaScript("I told him, "She said,
  137. > 'Hey, are you there?'"") =
  138. > I told him, \"She said, \'Hey, are you there?\'\"
  139. > unescaped = I told him, "She said, 'Hey, are you there?'"
  140. > StringEscapeUtils.escapeJavaScript("static class Foo<T extends List &
  141. > Serializable>") =
  142. > static class Foo<T extends List & Serializable>
  143. > unescaped = static class Foo<T extends List & Serializable>
  144. > StringEscapeUtils.escapeJavaScript("Intel® Pentium™ 4 @ 2.40 GHz") =
  145. > Intel\u00AE Pentium\u2122 4 @ 2.40 GHz
  146. > unescaped = Intel® Pentium™ 4 @ 2.40 GHz
  147. >
  148. > StringEscapeUtils.escapeSql("Simple") =
  149. > Simple
  150. > StringEscapeUtils.escapeSql("I told him, "She said,
  151. > 'Hey, are you there?'"") =
  152. > I told him, "She said, ''Hey, are you there?''"
  153. > StringEscapeUtils.escapeSql("static class Foo<T extends List &
  154. > Serializable>") =
  155. > static class Foo<T extends List & Serializable>
  156. > StringEscapeUtils.escapeSql("Intel® Pentium™ 4 @ 2.40 GHz") =
  157. > Intel® Pentium™ 4 @ 2.40 GHz
  158. >
  159. > StringEscapeUtils.escapeXml("Simple") =
  160. > Simple
  161. > unescaped = Simple
  162. > StringEscapeUtils.escapeXml("I told him, "She said,
  163. > 'Hey, are you there?'"") =
  164. > I told him, "She said, 'Hey, are you there?'"
  165. > unescaped = I told him, "She said, 'Hey, are you there?'"
  166. > StringEscapeUtils.escapeXml("static class Foo<T extends List &
  167. > Serializable>") =
  168. > static class Foo<T extends List & Serializable>
  169. > unescaped = static class Foo<T extends List & Serializable>
  170. > StringEscapeUtils.escapeXml("Intel® Pentium™ 4 @ 2.40 GHz") =
  171. > Intel® Pentium™ 4 @ 2.40 GHz
  172. > unescaped = Intel® Pentium™ 4 @ 2.40 GHz

There are also versions of all these methods that take a Writer instead of returning a String.

RandomStringUtils

RandomStringUtils is fairly self-explanatory; it's a utility to create random Strings. These might be good for passwords. Here's some examples:

  1. package com.ociweb.jnb.jul2009;
  2.  
  3. import org.apache.commons.lang.RandomStringUtils;
  4.  
  5.  
  6. public class RandomStringExample {
  7. public static void main(String[] args) {
  8. // 8-char random - most chars are not human readable
  9. System.out.println("RandomStringUtils.random(8) = " +
  10. RandomStringUtils.random(8));
  11.  
  12. // 8-char alphabetic random
  13. System.out.println("RandomStringUtils.randomAlphabetic(8) = " +
  14. RandomStringUtils.randomAlphabetic(8));
  15.  
  16. // 8-char ascii random
  17. System.out.println("RandomStringUtils.randomAscii(8) = " +
  18. RandomStringUtils.randomAscii(8));
  19.  
  20. // 8-char numeric random
  21. System.out.println("RandomStringUtils.randomNumeric(8) = " +
  22. RandomStringUtils.randomNumeric(8));
  23.  
  24. // 8-char alphanumeric random
  25. System.out.println("RandomStringUtils.random(8, true, true) = " +
  26. RandomStringUtils.random(8, true, true));
  27.  
  28. // 8-char octal random - using a version that uses the specified
  29. // characters for the generated String
  30. System.out.println("RandomStringUtils.random(8, \"01234567\") = " +
  31. RandomStringUtils.random(8, "01234567"));
  32. }
  33. }
  34. > RandomStringUtils.random(8) = ??????L?
  35. > RandomStringUtils.randomAlphabetic(8) = yOOrPTbu
  36. > RandomStringUtils.randomAscii(8) = t&eTP)w=
  37. > RandomStringUtils.randomNumeric(8) = 15595314
  38. > RandomStringUtils.random(8, true, true) = 2SDuqPeZ
  39. > RandomStringUtils.random(8, "01234567") = 64137033

Note that most of the characters returned by the simplist variant of random are not printable. That is because the method uses all legal characters, many of which are not printable in my English character set.

WordUtils

WordUtils provides many of the same nullsafe for sentences that StringUtils provides for Strings:

  1. package com.ociweb.jnb.jul2009;
  2.  
  3. import org.apache.commons.lang.WordUtils;
  4.  
  5.  
  6. public class WordExample {
  7. public static void main(String[] args) {
  8. // abbreviate somewhere between 2 and 8 characters
  9. System.out.println(
  10. "WordUtils.abbreviate(\"Object Computing, Inc.\", 2, 8, \"huh?\") = " +
  11. WordUtils.abbreviate("Object Computing, Inc.", 2, 8, "..."));
  12.  
  13. // capitalize all words
  14. System.out.println(
  15. "WordUtils.capitalize(\"object computing, inc.\") = " +
  16. WordUtils.capitalize("object COMPUTING, inc."));
  17.  
  18. // capitalize all words, removing extra capitalizations
  19. System.out.println(
  20. "WordUtils.capitalizeFully(\"object computing, inc.\") = " +
  21. WordUtils.capitalizeFully("object COMPUTING, inc."));
  22.  
  23. // create an initial
  24. System.out.println("WordUtils.initials(\"object computing, inc.\") = " +
  25. WordUtils.initials("object COMPUTING, inc."));
  26.  
  27. // swap case for all letters
  28. System.out.println("WordUtils.swapCase(\"object computing, inc.\") = " +
  29. WordUtils.swapCase("object COMPUTING, inc."));
  30.  
  31. // uncapitalize all words
  32. System.out.println(
  33. "WordUtils.uncapitalize(\"object computing, inc.\") = " +
  34. WordUtils.uncapitalize("object COMPUTING, inc."));
  35.  
  36. // wrap a phrase after 12 characters
  37. System.out.println(
  38. "WordUtils.wrap(\"This is a sentence to show the wrapping\", 12) = " +
  39. WordUtils.wrap("This is a sentence to show the wrapping", 12));
  40. }
  41. }
  42. > WordUtils.abbreviate("Object Computing, Inc.", 2, 6, "huh?") = Object...
  43. > WordUtils.capitalize("object computing, inc.") = Object COMPUTING, Inc.
  44. > WordUtils.capitalizeFully("object computing, inc.") = Object Computing, Inc.
  45. > WordUtils.initials("object computing, inc.") = oCi
  46. > WordUtils.swapCase("object computing, inc.") = OBJECT computing, INC.
  47. > WordUtils.uncapitalize("object computing, inc.") = object cOMPUTING, inc.
  48. > WordUtils.uncapitalize("This is a sentence to show the wrapping", 12) = This is a
  49. > sentence to
  50. > show the
  51. > wrapping

Assorted Functions

The next batch of components are what the Commons Lang documentation refers to as "Assorted Functions," ObjectUtilsClassUtilsArrayUtils, and BooleanUtils.

ObjectUtils

ObjectUtils provides several nullsafe versions of methods on Object. For example, if you want to call equals()hashCode(), or toString() on an object that might be null, use the ObjectUtils version instead of adding your own boilerplate null-checking.

Additionally, ObjectUtils provides two identityToString() methods to retrieve the default toString() that an object would return if the class hadn't implemented its own toString(), a max and a min that can be used for Comparables, and a defaultIfNull() method to return a default value if a given object is null.

ClassUtils

ClassUtils provides a number of components that can be helpful in reflection. Unfortunately, a lot of these methods could be simplified by converting them to use varargs.

  1. package com.ociweb.jnb.jul2009;
  2.  
  3. import org.apache.commons.lang.ClassUtils;
  4.  
  5. import java.util.ArrayList;
  6. import java.util.Arrays;
  7.  
  8.  
  9. public class ClassExample {
  10. public static void main(String[] args) {
  11.  
  12. // class and package names
  13. System.out.println(
  14. "ClassUtils.getPackageCanonicalName(ClassExample.class) = " +
  15. ClassUtils.getPackageCanonicalName(ClassExample.class));
  16. System.out.println("ClassUtils.getPackageName(ClassExample.class) = " +
  17. ClassUtils.getPackageName(ClassExample.class));
  18. System.out.println(
  19. "ClassUtils.getShortCanonicalName(ClassExample.class) = " +
  20. ClassUtils.getShortCanonicalName(ClassExample.class));
  21. System.out.println(
  22. "ClassUtils.getShortClassName(ClassExample.class) = " +
  23. ClassUtils.getShortClassName(ClassExample.class));
  24.  
  25. // primitive and wrapper conversion
  26. System.out.println("ClassUtils.primitiveToWrapper(Byte.TYPE) = " +
  27. ClassUtils.primitiveToWrapper(Byte.TYPE));
  28. System.out.println("ClassUtils.primitivesToWrappers(new Class[] " +
  29. "{Byte.TYPE, Integer.TYPE}) = \n\t" +
  30. Arrays.toString(
  31. ClassUtils.primitivesToWrappers(
  32. new Class[] { Byte.TYPE, Integer.TYPE })));
  33. System.out.println("ClassUtils.wrapperToPrimitive(Byte.class) = " +
  34. ClassUtils.wrapperToPrimitive(Byte.class));
  35. System.out.println(
  36. "ClassUtils.primitivesToWrappers(new Class[] {Byte.class, " +
  37. "Integer.class}) = \n\t" +
  38. Arrays.toString(
  39. ClassUtils.wrappersToPrimitives(
  40. new Class[] { Byte.class, Integer.class })));
  41.  
  42. // determining the classes for lots of objects
  43. System.out.println("ClassUtils.toClass(new Object[] {5, \"happy\", " +
  44. "new ArrayList()}) = \n\t" +
  45. Arrays.toString(
  46. ClassUtils.toClass(
  47. new Object[] { 5, "happy", new ArrayList() })));
  48.  
  49. // determining class names for lots of classes
  50. System.out.println(
  51. "ClassUtils.convertClassesToClassNames(Integer.TYPE, " +
  52. "String.class, ArrayList.class) = \n\t" +
  53. ClassUtils.convertClassesToClassNames(
  54. Arrays.asList(Integer.TYPE, String.class, ArrayList.class)));
  55. }
  56. }
  57. > ClassUtils.getPackageCanonicalName(ClassExample.class) = com.ociweb.jnb.jul2009
  58. > ClassUtils.getPackageName(ClassExample.class) = com.ociweb.jnb.jul2009
  59. > ClassUtils.getShortCanonicalName(ClassExample.class) = ClassExample
  60. > ClassUtils.getShortClassName(ClassExample.class) = ClassExample
  61. > ClassUtils.primitiveToWrapper(Byte.TYPE) = class java.lang.Byte
  62. > ClassUtils.primitivesToWrappers(new Class[] {Byte.TYPE, Integer.TYPE}) =
  63. > [class java.lang.Byte, class java.lang.Integer]
  64. > ClassUtils.wrapperToPrimitive(Byte.class) = byte
  65. > ClassUtils.primitivesToWrappers(new Class[] {Byte.class, Integer.class}) =
  66. > [byte, int]
  67. > ClassUtils.toClass(new Object[] {5, "happy", new ArrayList()}) =
  68. > [class java.lang.Integer, class java.lang.String, class java.util.ArrayList]
  69. > ClassUtils.convertClassesToClassNames(Integer.TYPE, String.class, ArrayList.class) =
  70. > [int, java.lang.String, java.util.ArrayList]

ArrayUtils

ArrayUtils is on the scale of StringUtils for the number of useful methods. Some methods here (like addaddAllclone, etc.) have many overloaded versions because there are separate versions for each of the primitives, plus one for all Objects.

Most of the methods here are for simple manipulation within and between arrays. One interesting exception is toMap(), which can be useful for creating a quick Map.

  1. package com.ociweb.jnb.jul2009;
  2.  
  3. import org.apache.commons.lang.ArrayUtils;
  4.  
  5. import java.util.Arrays;
  6.  
  7.  
  8. public class ArrayExample {
  9. public static void main(String[] args) {
  10.  
  11. // add an element to the end of an array
  12. System.out.println("ArrayUtils.add(new int[4], 6) = " +
  13. Arrays.toString(ArrayUtils.add(new int[4], 6)));
  14.  
  15. // insert an element into an array
  16. System.out.println("ArrayUtils.add(new int[4], 2, 6) = " +
  17. Arrays.toString(ArrayUtils.add(new int[4], 2, 6)));
  18.  
  19. // merge two arrays
  20. System.out.println(
  21. "ArrayUtils.addAll(new int[] {1, 2}, new int [] {5, 6}) = " +
  22. Arrays.toString(
  23. ArrayUtils.addAll(new int[] { 1, 2 }, new int[] { 5, 6 })));
  24.  
  25. // shallow clone of an array
  26. System.out.println("ArrayUtils.clone(new int[][] {{ 1, 2 }}) = " +
  27. Arrays.toString(ArrayUtils.clone(new int[][] {
  28. { 1, 2 }
  29. })));
  30.  
  31. // check if the value is in the array
  32. System.out.println("ArrayUtils.contains(new int[] { 1, 2 }, 2) = " +
  33. ArrayUtils.contains(new int[] { 1, 2 }, 2));
  34.  
  35. // remove an element from an array by index
  36. System.out.println("ArrayUtils.remove(new int[] {1, 2, 3}, 1) = " +
  37. Arrays.toString(ArrayUtils.remove(new int[] { 1, 2, 3 }, 1)));
  38.  
  39. // remove an element from an array
  40. System.out.println(
  41. "ArrayUtils.removeElement(new int[] {1, 2, 3}, 1) = " +
  42. Arrays.toString(
  43. ArrayUtils.removeElement(new int[] { 1, 2, 3 }, 1)));
  44.  
  45. // reverse an array (in place)
  46. final int[] array = { 1, 2, 3 };
  47. ArrayUtils.reverse(array);
  48. System.out.println("reversed array = " + Arrays.toString(array));
  49.  
  50. // extract a subarray (first is inclusive, last is exclusive)
  51. System.out.println(
  52. "ArrayUtils.subarray(new int[] {1, 2, 3, 4}, 1, 3)) = " +
  53. Arrays.toString(
  54. ArrayUtils.subarray(new int[] { 1, 2, 3, 4 }, 1, 3)));
  55.  
  56. // convert an array of two-element arrays to a map
  57. System.out.println(
  58. "ArrayUtils.toMap(new Object[][]{{\"DE\", 1}, {\"PA\", 2 }, " +
  59. "{\"NJ\", 3}}) = \n\t" +
  60. ArrayUtils.toMap(
  61. new Object[][] {
  62. { "DE", 1 },
  63. { "PA", 2 },
  64. { "NJ", 3 }
  65. }));
  66.  
  67. // convert primitives to wrappers
  68. System.out.println(
  69. "ArrayUtils.toObject(new int[] { 1, 2, 3, 4 }) = " +
  70. Arrays.toString(
  71. ArrayUtils.toObject(new int[] { 1, 2, 3, 4 })));
  72. // convert wrappers to primitives
  73. System.out.println(
  74. "ArrayUtils.toPrimitive(new Integer[] { 1, 2, 3, 4 }) = " +
  75. Arrays.toString(
  76. ArrayUtils.toPrimitive(new Integer[] { 1, 2, 3, 4 })));
  77.  
  78. }
  79. }
  80. > ArrayUtils.add(new int[4], 6) = [0, 0, 0, 0, 6]
  81. > ArrayUtils.add(new int[4], 2, 6) = [0, 0, 6, 0, 0]
  82. > ArrayUtils.addAll(new int[] {1, 2}, new int [] {5, 6}) = [1, 2, 5, 6]
  83. > ArrayUtils.clone(new int[][] {{ 1, 2 }}) = [[I@cdedfd]
  84. > ArrayUtils.contains(new int[] { 1, 2 }, 2) = true
  85. > ArrayUtils.remove(new int[] {1, 2, 3}, 1) = [1, 3]
  86. > ArrayUtils.removeElement(new int[] {1, 2, 3}, 1) = [2, 3]
  87. > reversed array = [3, 2, 1]
  88. > ArrayUtils.subarray(new int[] {1, 2, 3, 4}, 1, 3)) = [2, 3]
  89. > ArrayUtils.toMap(new Object[][]{{"DE", 1}, {"PA", 2 }, {"NJ", 3}}) =
  90. > {NJ=3, DE=1, PA=2}
  91. > ArrayUtils.toObject(new int[] { 1, 2, 3, 4 }) = [1, 2, 3, 4]
  92. > ArrayUtils.toPrimitive(new Integer[] { 1, 2, 3, 4 }) = [1, 2, 3, 4]

BooleanUtils

BooleanUtils provides some components for handling booleans. Many of the methods are simply nullsafe versions of JDK methods. However, there are other useful methods, particularly those that map boolean values with String tuples other than true and false.

  1. package com.ociweb.jnb.jul2009;
  2.  
  3. import org.apache.commons.lang.BooleanUtils;
  4.  
  5.  
  6. public class BooleanExample {
  7. public static void main(String[] args) {
  8.  
  9. // convert int to boolean and vice verse (assumes 0 is false -
  10. // overridden version allow that to be different
  11. System.out.println("BooleanUtils.toBoolean(0) = " +
  12. BooleanUtils.toBoolean(0));
  13. System.out.println("BooleanUtils.toInteger(true) = " +
  14. BooleanUtils.toInteger(true));
  15.  
  16. // using alternate String tuples for true|false
  17. System.out.println("BooleanUtils.toStringOnOff(true) = " +
  18. BooleanUtils.toStringOnOff(true));
  19. System.out.println("BooleanUtils.toStringYesNo(true) = " +
  20. BooleanUtils.toStringYesNo(true));
  21.  
  22. // defining a custom String tuple for true|false
  23. System.out.println(
  24. "BooleanUtils.toString(true, \"Yep!\", \"Nope!\") = " +
  25. BooleanUtils.toString(true, "Yep!", "Nope!"));
  26. System.out.println(
  27. "BooleanUtils.toString(false, \"Yep!\", \"Nope!\") = " +
  28. BooleanUtils.toString(false, "Yep!", "Nope!"));
  29.  
  30. // xor calculation on an array of booleans
  31. System.out.println(
  32. "BooleanUtils.xor(new boolean[] {true, false, true, true}) = " +
  33. BooleanUtils.xor(new boolean[] { true, false, true, true }));
  34. System.out.println(
  35. "BooleanUtils.xor(new boolean[] {true, true, true, true}) = " +
  36. BooleanUtils.xor(new boolean[] { true, true, true, true }));
  37. System.out.println(
  38. "BooleanUtils.xor(new boolean[] {false, false, false, false}) = " +
  39. BooleanUtils.xor(new boolean[] { false, false, false, false }));
  40. }
  41. }
  42. > BooleanUtils.toBoolean(0) = false
  43. > BooleanUtils.toInteger(true) = 1
  44. > BooleanUtils.toStringOnOff(true) = on
  45. > BooleanUtils.toStringYesNo(true) = yes
  46. > BooleanUtils.toString(true, "Yep!", "Nope!") = Yep!
  47. > BooleanUtils.toString(false, "Yep!", "Nope!") = Nope!
  48. > BooleanUtils.xor(new boolean[] {true, false, true, true}) = false
  49. > BooleanUtils.xor(new boolean[] {true, true, true, true}) = false
  50. > BooleanUtils.xor(new boolean[] {false, false, false, false}) = false

Summary

Commons Lang provides many useful components for the general Java developer. Some of the components are clever and reduce a lot of work, but a lot of the components are nothing more than nullsafe versions of methods in the JDK. However, even those simpler methods can significantly reduce the amount of boilerplate code a developer has to write.

I hope that a future version of Commons Lang makes more use of generics and varargs in order to simplify and strengthen the API, but as it is it's already a very useful resource.

I will review additional useful utilities in the library's subpackages in a later article.

References

secret