|
|
|
|
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
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
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:
package com.ociweb.jnb.jul2009;
import org.apache.commons.lang.SystemUtils;
public class SystemExample {
public static void main(String[] args) {
System.out.println("SystemUtils.AWT_TOOLKIT = " +
SystemUtils.AWT_TOOLKIT);
System.out.println("SystemUtils.FILE_ENCODING = " +
SystemUtils.FILE_ENCODING);
System.out.println("SystemUtils.FILE_SEPARATOR = " +
SystemUtils.FILE_SEPARATOR);
System.out.println("SystemUtils.IS_JAVA_1_5 = " +
SystemUtils.IS_JAVA_1_5);
System.out.println("SystemUtils.IS_JAVA_1_6 = " +
SystemUtils.IS_JAVA_1_6);
System.out.println("SystemUtils.IS_OS_MAC_OSX = " +
SystemUtils.IS_OS_MAC_OSX);
System.out.println("SystemUtils.IS_OS_WINDOWS = " +
SystemUtils.IS_OS_WINDOWS);
System.out.println("SystemUtils.IS_OS_WINDOWS_VISTA = " +
SystemUtils.IS_OS_WINDOWS_VISTA);
System.out.println("SystemUtils.IS_OS_WINDOWS_XP = " +
SystemUtils.IS_OS_WINDOWS_XP);
System.out.println("SystemUtils.JAVA_AWT_PRINTERJOB = " +
SystemUtils.JAVA_AWT_PRINTERJOB);
System.out.println("SystemUtils.JAVA_HOME = " + SystemUtils.JAVA_HOME);
System.out.println("SystemUtils.JAVA_VERSION = " +
SystemUtils.JAVA_VERSION);
System.out.println("SystemUtils.OS_ARCH = " + SystemUtils.OS_ARCH);
System.out.println("SystemUtils.OS_NAME = " + SystemUtils.OS_NAME);
System.out.println("SystemUtils.PATH_SEPARATOR = " +
SystemUtils.PATH_SEPARATOR);
System.out.println("SystemUtils.USER_COUNTRY = " +
SystemUtils.USER_COUNTRY);
System.out.println("SystemUtils.USER_LANGUAGE = " +
SystemUtils.USER_LANGUAGE);
System.out.println("SystemUtils.isJavaAwtHeadless() = " +
SystemUtils.isJavaAwtHeadless());
System.out.println("SystemUtils.isJavaVersionAtLeast(14) = " +
SystemUtils.isJavaVersionAtLeast(14));
System.out.println("SystemUtils.isJavaVersionAtLeast(1.4f) = " +
SystemUtils.isJavaVersionAtLeast(1.4f));
}
}
> SystemUtils.AWT_TOOLKIT = sun.awt.windows.WToolkit
> SystemUtils.FILE_ENCODING = windows-1252
> SystemUtils.FILE_SEPARATOR = \
> SystemUtils.IS_JAVA_1_5 = false
> SystemUtils.IS_JAVA_1_6 = true
> SystemUtils.IS_OS_MAC_OSX = false
> SystemUtils.IS_OS_WINDOWS = true
> SystemUtils.IS_OS_WINDOWS_VISTA = false
> SystemUtils.IS_OS_WINDOWS_XP = true
> SystemUtils.JAVA_AWT_PRINTERJOB = sun.awt.windows.WPrinterJob
> SystemUtils.JAVA_HOME = C:\Program Files\Java\jdk1.6.0_12\fastdebug\jre
> SystemUtils.JAVA_VERSION = 1.6.0_12-ea-fastdebug
> SystemUtils.OS_ARCH = x86
> SystemUtils.OS_NAME = Windows XP
> SystemUtils.PATH_SEPARATOR = ;
> SystemUtils.USER_COUNTRY = US
> SystemUtils.USER_LANGUAGE = en
> SystemUtils.isJavaAwtHeadless() = false
> SystemUtils.isJavaVersionAtLeast(14) = true
> SystemUtils.isJavaVersionAtLeast(1.4f) = true
Commons Lang provides several component classes for manipulating and examining Strings. StringUtils is the most important of these, but StringEscapeUtils, RandomStringUtils, and WordUtils are also useful.
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.
package com.ociweb.jnb.jul2009;
import org.apache.commons.lang.StringUtils;
import java.util.Arrays;
public class StringUtilsExample {
public static void main(String[] args) {
// cuts the String down to never be longer than 7, using an ellipsis
System.out.println(
"StringUtils.abbreviate(\"This text is just too long.\", 7) = " +
StringUtils.abbreviate("This text is just too long.", 7));
// capitalizes, uncapitalizes, lowercases, or uppercases the word
System.out.println("StringUtils.capitalize(\"faMily\") = " +
StringUtils.capitalize("faMily"));
System.out.println("StringUtils.uncapitalize(\"FaMily\") = " +
StringUtils.uncapitalize("FaMily"));
System.out.println("StringUtils.lowerCase(\"faMily\") = " +
StringUtils.lowerCase("faMily"));
System.out.println("StringUtils.upperCase(\"faMily\") = " +
StringUtils.upperCase("faMily"));
// centers the word, padding with spaces
System.out.println("StringUtils.center(\"Title\", 15) = '" +
StringUtils.center("Title", 15) + "'");
// removes the given separator from the end of the String, if necessary
System.out.println(
"StringUtils.chomp(\"I like apple pie!\", \"!\") = " +
StringUtils.chomp("I like apple pie!", "!"));
// removes the last character from the String
System.out.println("StringUtils.chop(\"I like apple pie!\") = " +
StringUtils.chop("I like apple pie!"));
// similar to String.contains(), but is nullsafe
// there are many similar methods (containsAny, containsIgnoreCase, etc)
System.out.println(
"StringUtils.contains(\"I like apple pie!\", \"apple\") = " +
StringUtils.contains("I like apple pie!", "apple"));
// returns either the first String or the second String (if the first
// is null or empty)
System.out.println("StringUtils.defaultIfEmpty(null, \"oops!\") = " +
StringUtils.defaultIfEmpty(null, "oops!"));
// removes all whitespace from the String
System.out.println(
"StringUtils.deleteWhitespace(\"I like apple pie!\") = " +
StringUtils.deleteWhitespace("I like apple pie!"));
// returns the part of the second String after a difference is seen
System.out.println("StringUtils.difference(\"I like apple pie!\", " +
"\"I like cherry pie!\") = " +
StringUtils.difference("I like apple pie!", "I like cherry pie!"));
// nullsafe check on the end or beginning of a String
System.out.println(
"StringUtils.endsWith(\"I like apple pie!\", \"cake!\") = " +
StringUtils.endsWith("I like apple pie!", "cake!"));
System.out.println(
"StringUtils.startsWith(\"I like apple pie!\", \"I \") = " +
StringUtils.startsWith("I like apple pie!", "I "));
// nullsafe equality check
System.out.println(
"StringUtils.equals(null, \"I like apple pie!\") = " +
StringUtils.equals(null, "I like apple pie!"));
// returns the commons prefix of an array of Strings
System.out.println(
"StringUtils.getCommonPrefix(new String[] {\"bar\", \"baz\"}) = " +
StringUtils.getCommonPrefix(new String[] { "bar", "baz" }));
// returns the number of character changes needed to turn one String
// into another
System.out.println(
"StringUtils.getLevenshteinDistance(\"I like pie!\", " +
"\"I like cake!\") = " +
StringUtils.getLevenshteinDistance("I like pie!", "I like cake!"));
// similar to String.indexOf(), but is nullsafe
// there are many similar methods (indexOfAny, indexOfDifference, etc.)
// there are also versions of lastIndexOf
System.out.println(
"StringUtils.indexOf(\"I like apple pie!\", \"apple\") = " +
StringUtils.indexOf("I like apple pie!", "apple"));
// returns whether the String contains only unicode letters
// there are similar methods for numeric, alphanumeric,
// including space, etc.
System.out.println("StringUtils.isAlpha(\"I like apple pie!\") = " +
StringUtils.isAlpha("I like apple pie!"));
// nullsafe checks for empty and blank Strings
System.out.println("StringUtils.isBlank(\"I like apple pie!\") = " +
StringUtils.isBlank("I like apple pie!"));
System.out.println("StringUtils.isBlank(\" \") = " +
StringUtils.isBlank(" "));
System.out.println("StringUtils.isBlank(\"\") = " +
StringUtils.isBlank(""));
System.out.println("StringUtils.isBlank(null) = " +
StringUtils.isBlank(null));
System.out.println("StringUtils.isEmpty(\"I like apple pie!\") = " +
StringUtils.isEmpty("I like apple pie!"));
System.out.println("StringUtils.isEmpty(\" \") = " +
StringUtils.isEmpty(" "));
System.out.println("StringUtils.isEmpty(\"\") = " +
StringUtils.isEmpty(""));
System.out.println("StringUtils.isEmpty(null) = " +
StringUtils.isEmpty(null));
// joins the elements of the array to a single String with the given
// separator
System.out.println(
"StringUtils.join(new Object[] {5, \"happy\", 3.14}, '-') = " +
StringUtils.join(new Object[] { 5, "happy", 3.14 }, '-'));
// like String.substring, but is ok with the String being too small,
// and can pad the difference
System.out.println(
"StringUtils.left(\"I like apple pie!\", 10) + \"'\" = '" +
StringUtils.left("I like apple pie!", 10) + "'");
System.out.println(
"StringUtils.left(\"I like apple pie!\", 20) + \"'\" = '" +
StringUtils.left("I like apple pie!", 20) + "'");
System.out.println(
"StringUtils.leftPad(\"I like apple pie!\", 20) + \"'\" = '" +
StringUtils.leftPad("I like apple pie!", 20) + "'");
System.out.println(
"StringUtils.right(\"I like apple pie!\", 10) + \"'\" = '" +
StringUtils.right("I like apple pie!", 10) + "'");
System.out.println(
"StringUtils.right(\"I like apple pie!\", 20) + \"'\" = '" +
StringUtils.right("I like apple pie!", 20) + "'");
System.out.println(
"StringUtils.rightPad(\"I like apple pie!\", 20) + \"'\" = '" +
StringUtils.rightPad("I like apple pie!", 20) + "'");
// nullsafe version of String.length()
System.out.println("StringUtils.length(null) = " +
StringUtils.length(null));
// similar to String.replace(), but nullsafe
// there are many variants of replaceXXX methods
System.out.println(
"StringUtils.remove(\"I like apple pie!\", \"e\") = " +
StringUtils.remove("I like apple pie!", "e"));
System.out.println(
"StringUtils.replace(\"I like apple pie!\", \"e\", \"u\") = " +
StringUtils.replace("I like apple pie!", "e", "u"));
// creates a new String from a repetition of another String
System.out.println("StringUtils.repeat(\"apple \", 5) = " +
StringUtils.repeat("apple ", 5));
// similar to StringBuffer.reverse(), but nullsafe
System.out.println("StringUtils.reverse(\"I like apple pie!\") = " +
StringUtils.reverse("I like apple pie!"));
// splits a String into an array using whitespace as the delimiter.
// There are many variant methods
System.out.println("StringUtils.split(\"I like apple pie!\") = " +
Arrays.toString(StringUtils.split("I like apple pie!")));
// nullsafe removal of all leading and trailing whitespace. There are
// many variant methods
System.out.println(
"StringUtils.strip(\"\\t I like apple pie!\\r\\n\") = '" +
StringUtils.strip("\t I like apple pie!\r\n") + "'");
// similar to String.substring(), but nullsafe. There are many variant
// methods
System.out.println(
"StringUtils.substring(\"I like apple pie!\", 4) = " +
StringUtils.substring("I like apple pie!", 4));
System.out.println("StringUtils.substring(null, 4) = " +
StringUtils.substring(null, 4));
// converts lowercase to caps and vice versa
System.out.println("StringUtils.swapCase(\"I like apple pie!\") = " +
StringUtils.swapCase("I like apple pie!"));
// nullsafe version of String.trim(). Leaves non-space whitespace
System.out.println("StringUtils.trim(\" /tI like apple pie! \") = '" +
StringUtils.trim(" /tI like apple pie! ") + "'");
}
}
> StringUtils.abbreviate("This text is just too long.", 7) = This...
> StringUtils.capitalize("faMily") = FaMily
> StringUtils.uncapitalize("FaMily") = faMily
> StringUtils.lowerCase("faMily") = family
> StringUtils.upperCase("faMily") = FAMILY
> StringUtils.center("Title", 15) = ' Title '
> StringUtils.chomp("I like apple pie!", "!") = I like apple pie
> StringUtils.chop("I like apple pie!") = I like apple pie
> StringUtils.contains("I like apple pie!", "apple") = true
> StringUtils.defaultIfEmpty(null, "oops!") = oops!
> StringUtils.deleteWhitespace("I like apple pie!") = Ilikeapplepie!
> StringUtils.difference("I like apple pie!", "I like cherry pie!") = cherry pie!
> StringUtils.endsWith("I like apple pie!", "cake!") = false
> StringUtils.startsWith("I like apple pie!", "I ") = true
> StringUtils.equals(null, "I like apple pie!") = false
> StringUtils.getCommonPrefix(new String[] {"bar", "baz"}) = ba
> StringUtils.getLevenshteinDistance("I like pie!", "I like cake!") = 3
> StringUtils.indexOf("I like apple pie!", "apple") = 7
> StringUtils.isAlpha("I like apple pie!") = false
> StringUtils.isBlank("I like apple pie!") = false
> StringUtils.isBlank(" ") = true
> StringUtils.isBlank("") = true
> StringUtils.isBlank(null) = true
> StringUtils.isEmpty("I like apple pie!") = false
> StringUtils.isEmpty(" ") = false
> StringUtils.isEmpty("") = true
> StringUtils.isEmpty(null) = true
> StringUtils.join(new Object[] {5, "happy", 3.14}, '-') = 5-happy-3.14
> StringUtils.left("I like apple pie!", 10) + "'" = 'I like app'
> StringUtils.left("I like apple pie!", 20) + "'" = 'I like apple pie!'
> StringUtils.leftPad("I like apple pie!", 20) + "'" = ' I like apple pie!'
> StringUtils.right("I like apple pie!", 10) + "'" = 'apple pie!'
> StringUtils.right("I like apple pie!", 20) + "'" = 'I like apple pie!'
> StringUtils.rightPad("I like apple pie!", 20) + "'" = 'I like apple pie! '
> StringUtils.length(null) = 0
> StringUtils.remove("I like apple pie!", "e") = I lik appl pi!
> StringUtils.replace("I like apple pie!", "e", "u") = I liku applu piu!
> StringUtils.repeat("apple ", 5) = apple apple apple apple apple
> StringUtils.reverse("I like apple pie!") = !eip elppa ekil I
> StringUtils.split("I like apple pie!") = [I, like, apple, pie!]
> StringUtils.strip("\t I like apple pie!\r\n") = 'I like apple pie!'
> StringUtils.substring("I like apple pie!", 4) = ke apple pie!
> StringUtils.substring(null, 4) = null
> StringUtils.swapCase("I like apple pie!") = i LIKE APPLE PIE!
> StringUtils.trim(" /tI like apple pie! ") = '/tI like apple pie!'
StringExampleUtils provides convenient methods for correctly escaping and unescaping text for CSV, HTML, Java, JavaScript, XML, and SQL (there is no unescape for SQL):
package com.ociweb.jnb.jul2009;
import org.apache.commons.lang.StringEscapeUtils;
public class StringEscapeExample {
private static final String[] testStrings = {
"Simple", "I told him, \"She said, \'Hey, are you there?\'\"",
"static class Foo<T extends List & Serializable>,
"Intel® Pentium™ 4 @ 2.40 GHz"
};
public static void main(String[] args) {
// escapeCsv adds quotes, if needed
for (String testString : testStrings) {
final String escaped = StringEscapeUtils.escapeCsv(testString);
final String unescaped = StringEscapeUtils.unescapeCsv(escaped);
System.out.println("StringEscapeUtils.escapeCsv(\"" + testString +
"\") = \n\t" + escaped);
System.out.println("unescaped = " + unescaped);
}
System.out.println();
// escapeHtml escapes html special characters
for (String testString : testStrings) {
final String escaped = StringEscapeUtils.escapeHtml(testString);
final String unescaped = StringEscapeUtils.unescapeHtml(escaped);
System.out.println("StringEscapeUtils.escapeHtml(\"" + testString +
"\") = \n\t" + escaped);
System.out.println("unescaped = " + unescaped);
}
System.out.println();
// escapeJava escapes Java special characters
for (String testString : testStrings) {
final String escaped = StringEscapeUtils.escapeJava(testString);
final String unescaped = StringEscapeUtils.unescapeJava(escaped);
System.out.println("StringEscapeUtils.escapeJava(\"" + testString +
"\") = \n\t" + escaped);
System.out.println("unescaped = " + unescaped);
}
System.out.println();
// escapeJavaScript escapes JavaScript special characters
for (String testString : testStrings) {
final String escaped = StringEscapeUtils.escapeJavaScript(
testString);
final String unescaped = StringEscapeUtils.unescapeJavaScript(
escaped);
System.out.println("StringEscapeUtils.escapeJavaScript(\"" +
testString + "\") = \n\t" + escaped);
System.out.println("unescaped = " + unescaped);
}
System.out.println();
// escapeSql escapes Sql special characters
for (String testString : testStrings) {
final String escaped = StringEscapeUtils.escapeSql(testString);
System.out.println("StringEscapeUtils.escapeSql(\"" + testString +
"\") = \n\t" + escaped);
}
System.out.println();
// escapeXml escapes Xml special characters (similar to html, but also
// escapes '
for (String testString : testStrings) {
final String escaped = StringEscapeUtils.escapeXml(testString);
final String unescaped = StringEscapeUtils.unescapeXml(escaped);
System.out.println("StringEscapeUtils.escapeXml(\"" + testString +
"\") = \n\t" + escaped);
System.out.println("unescaped = " + unescaped);
}
}
}
> StringEscapeUtils.escapeCsv("Simple") =
> Simple
> unescaped = Simple
> StringEscapeUtils.escapeCsv("I told him, "She said,
> 'Hey, are you there?'"") =
> "I told him, ""She said, 'Hey, are you there?'"""
> unescaped = I told him, "She said, 'Hey, are you there?'"
> StringEscapeUtils.escapeCsv("static class Foo<T extends List &
> Serializable>") =
> static class Foo<T extends List & Serializable>
> unescaped = static class Foo<T extends List & Serializable>
> StringEscapeUtils.escapeCsv("Intel® Pentium™ 4 @ 2.40 GHz") =
> Intel® Pentium™ 4 @ 2.40 GHz
> unescaped = Intel® Pentium™ 4 @ 2.40 GHz
>
> StringEscapeUtils.escapeHtml("Simple") =
> Simple
> unescaped = Simple
> StringEscapeUtils.escapeHtml("I told him, "She said,
> 'Hey, are you there?'"") =
> I told him, "She said, 'Hey, are you there?'"
> unescaped = I told him, "She said, 'Hey, are you there?'"
> StringEscapeUtils.escapeHtml("static class Foo<T extends List &
> Serializable>") =
> static class Foo<T extends List & Serializable>
> unescaped = static class Foo<T extends List & Serializable>
> StringEscapeUtils.escapeHtml("Intel® Pentium™ 4 @ 2.40 GHz") =
> Intel® Pentium™ 4 @ 2.40 GHz
> unescaped = Intel® Pentium™ 4 @ 2.40 GHz
>
> StringEscapeUtils.escapeJava("Simple") =
> Simple
> unescaped = Simple
> StringEscapeUtils.escapeJava("I told him, "She said,
> 'Hey, are you there?'"") =
> I told him, \"She said, 'Hey, are you there?'\"
> unescaped = I told him, "She said, 'Hey, are you there?'"
> StringEscapeUtils.escapeJava("static class Foo<T extends List &
> Serializable>") =
> static class Foo<T extends List & Serializable>
> unescaped = static class Foo<T extends List & Serializable>
> StringEscapeUtils.escapeJava("Intel® Pentium™ 4 @ 2.40 GHz") =
> Intel\u00AE Pentium\u2122 4 @ 2.40 GHz
> unescaped = Intel® Pentium™ 4 @ 2.40 GHz
>
> StringEscapeUtils.escapeJavaScript("Simple") =
> Simple
> unescaped = Simple
> StringEscapeUtils.escapeJavaScript("I told him, "She said,
> 'Hey, are you there?'"") =
> I told him, \"She said, \'Hey, are you there?\'\"
> unescaped = I told him, "She said, 'Hey, are you there?'"
> StringEscapeUtils.escapeJavaScript("static class Foo<T extends List &
> Serializable>") =
> static class Foo<T extends List & Serializable>
> unescaped = static class Foo<T extends List & Serializable>
> StringEscapeUtils.escapeJavaScript("Intel® Pentium™ 4 @ 2.40 GHz") =
> Intel\u00AE Pentium\u2122 4 @ 2.40 GHz
> unescaped = Intel® Pentium™ 4 @ 2.40 GHz
>
> StringEscapeUtils.escapeSql("Simple") =
> Simple
> StringEscapeUtils.escapeSql("I told him, "She said,
> 'Hey, are you there?'"") =
> I told him, "She said, ''Hey, are you there?''"
> StringEscapeUtils.escapeSql("static class Foo<T extends List &
> Serializable>") =
> static class Foo<T extends List & Serializable>
> StringEscapeUtils.escapeSql("Intel® Pentium™ 4 @ 2.40 GHz") =
> Intel® Pentium™ 4 @ 2.40 GHz
>
> StringEscapeUtils.escapeXml("Simple") =
> Simple
> unescaped = Simple
> StringEscapeUtils.escapeXml("I told him, "She said,
> 'Hey, are you there?'"") =
> I told him, "She said, 'Hey, are you there?'"
> unescaped = I told him, "She said, 'Hey, are you there?'"
> StringEscapeUtils.escapeXml("static class Foo<T extends List &
> Serializable>") =
> static class Foo<T extends List & Serializable>
> unescaped = static class Foo<T extends List & Serializable>
> StringEscapeUtils.escapeXml("Intel® Pentium™ 4 @ 2.40 GHz") =
> Intel® Pentium™ 4 @ 2.40 GHz
> 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 is fairly self-explanatory; it's a utility to create random Strings. These might be good for passwords. Here's some examples:
package com.ociweb.jnb.jul2009;
import org.apache.commons.lang.RandomStringUtils;
public class RandomStringExample {
public static void main(String[] args) {
// 8-char random - most chars are not human readable
System.out.println("RandomStringUtils.random(8) = " +
RandomStringUtils.random(8));
// 8-char alphabetic random
System.out.println("RandomStringUtils.randomAlphabetic(8) = " +
RandomStringUtils.randomAlphabetic(8));
// 8-char ascii random
System.out.println("RandomStringUtils.randomAscii(8) = " +
RandomStringUtils.randomAscii(8));
// 8-char numeric random
System.out.println("RandomStringUtils.randomNumeric(8) = " +
RandomStringUtils.randomNumeric(8));
// 8-char alphanumeric random
System.out.println("RandomStringUtils.random(8, true, true) = " +
RandomStringUtils.random(8, true, true));
// 8-char octal random - using a version that uses the specified
// characters for the generated String
System.out.println("RandomStringUtils.random(8, \"01234567\") = " +
RandomStringUtils.random(8, "01234567"));
}
}
> RandomStringUtils.random(8) = ??????L?
> RandomStringUtils.randomAlphabetic(8) = yOOrPTbu
> RandomStringUtils.randomAscii(8) = t&eTP)w=
> RandomStringUtils.randomNumeric(8) = 15595314
> RandomStringUtils.random(8, true, true) = 2SDuqPeZ
> 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 provides many of the same nullsafe for sentences that StringUtils provides for Strings:
package com.ociweb.jnb.jul2009;
import org.apache.commons.lang.WordUtils;
public class WordExample {
public static void main(String[] args) {
// abbreviate somewhere between 2 and 8 characters
System.out.println(
"WordUtils.abbreviate(\"Object Computing, Inc.\", 2, 8, \"huh?\") = " +
WordUtils.abbreviate("Object Computing, Inc.", 2, 8, "..."));
// capitalize all words
System.out.println(
"WordUtils.capitalize(\"object computing, inc.\") = " +
WordUtils.capitalize("object COMPUTING, inc."));
// capitalize all words, removing extra capitalizations
System.out.println(
"WordUtils.capitalizeFully(\"object computing, inc.\") = " +
WordUtils.capitalizeFully("object COMPUTING, inc."));
// create an initial
System.out.println("WordUtils.initials(\"object computing, inc.\") = " +
WordUtils.initials("object COMPUTING, inc."));
// swap case for all letters
System.out.println("WordUtils.swapCase(\"object computing, inc.\") = " +
WordUtils.swapCase("object COMPUTING, inc."));
// uncapitalize all words
System.out.println(
"WordUtils.uncapitalize(\"object computing, inc.\") = " +
WordUtils.uncapitalize("object COMPUTING, inc."));
// wrap a phrase after 12 characters
System.out.println(
"WordUtils.wrap(\"This is a sentence to show the wrapping\", 12) = " +
WordUtils.wrap("This is a sentence to show the wrapping", 12));
}
}
> WordUtils.abbreviate("Object Computing, Inc.", 2, 6, "huh?") = Object...
> WordUtils.capitalize("object computing, inc.") = Object COMPUTING, Inc.
> WordUtils.capitalizeFully("object computing, inc.") = Object Computing, Inc.
> WordUtils.initials("object computing, inc.") = oCi
> WordUtils.swapCase("object computing, inc.") = OBJECT computing, INC.
> WordUtils.uncapitalize("object computing, inc.") = object cOMPUTING, inc.
> WordUtils.uncapitalize("This is a sentence to show the wrapping", 12) = This is a
> sentence to
> show the
> wrapping
The next batch of components are what the Commons Lang documentation refers to as "Assorted Functions," ObjectUtils, ClassUtils, ArrayUtils, and BooleanUtils.
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 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.
package com.ociweb.jnb.jul2009;
import org.apache.commons.lang.ClassUtils;
import java.util.ArrayList;
import java.util.Arrays;
public class ClassExample {
public static void main(String[] args) {
// class and package names
System.out.println(
"ClassUtils.getPackageCanonicalName(ClassExample.class) = " +
ClassUtils.getPackageCanonicalName(ClassExample.class));
System.out.println("ClassUtils.getPackageName(ClassExample.class) = " +
ClassUtils.getPackageName(ClassExample.class));
System.out.println(
"ClassUtils.getShortCanonicalName(ClassExample.class) = " +
ClassUtils.getShortCanonicalName(ClassExample.class));
System.out.println(
"ClassUtils.getShortClassName(ClassExample.class) = " +
ClassUtils.getShortClassName(ClassExample.class));
// primitive and wrapper conversion
System.out.println("ClassUtils.primitiveToWrapper(Byte.TYPE) = " +
ClassUtils.primitiveToWrapper(Byte.TYPE));
System.out.println("ClassUtils.primitivesToWrappers(new Class[] " +
"{Byte.TYPE, Integer.TYPE}) = \n\t" +
Arrays.toString(
ClassUtils.primitivesToWrappers(
new Class[] { Byte.TYPE, Integer.TYPE })));
System.out.println("ClassUtils.wrapperToPrimitive(Byte.class) = " +
ClassUtils.wrapperToPrimitive(Byte.class));
System.out.println(
"ClassUtils.primitivesToWrappers(new Class[] {Byte.class, " +
"Integer.class}) = \n\t" +
Arrays.toString(
ClassUtils.wrappersToPrimitives(
new Class[] { Byte.class, Integer.class })));
// determining the classes for lots of objects
System.out.println("ClassUtils.toClass(new Object[] {5, \"happy\", " +
"new ArrayList()}) = \n\t" +
Arrays.toString(
ClassUtils.toClass(
new Object[] { 5, "happy", new ArrayList() })));
// determining class names for lots of classes
System.out.println(
"ClassUtils.convertClassesToClassNames(Integer.TYPE, " +
"String.class, ArrayList.class) = \n\t" +
ClassUtils.convertClassesToClassNames(
Arrays.asList(Integer.TYPE, String.class, ArrayList.class)));
}
}
> ClassUtils.getPackageCanonicalName(ClassExample.class) = com.ociweb.jnb.jul2009
> ClassUtils.getPackageName(ClassExample.class) = com.ociweb.jnb.jul2009
> ClassUtils.getShortCanonicalName(ClassExample.class) = ClassExample
> ClassUtils.getShortClassName(ClassExample.class) = ClassExample
> ClassUtils.primitiveToWrapper(Byte.TYPE) = class java.lang.Byte
> ClassUtils.primitivesToWrappers(new Class[] {Byte.TYPE, Integer.TYPE}) =
> [class java.lang.Byte, class java.lang.Integer]
> ClassUtils.wrapperToPrimitive(Byte.class) = byte
> ClassUtils.primitivesToWrappers(new Class[] {Byte.class, Integer.class}) =
> [byte, int]
> ClassUtils.toClass(new Object[] {5, "happy", new ArrayList()}) =
> [class java.lang.Integer, class java.lang.String, class java.util.ArrayList]
> ClassUtils.convertClassesToClassNames(Integer.TYPE, String.class, ArrayList.class) =
> [int, java.lang.String, java.util.ArrayList]
ArrayUtils is on the scale of StringUtils for the number of useful methods.
Some methods here (like add, addAll, clone,
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.
package com.ociweb.jnb.jul2009;
import org.apache.commons.lang.ArrayUtils;
import java.util.Arrays;
public class ArrayExample {
public static void main(String[] args) {
// add an element to the end of an array
System.out.println("ArrayUtils.add(new int[4], 6) = " +
Arrays.toString(ArrayUtils.add(new int[4], 6)));
// insert an element into an array
System.out.println("ArrayUtils.add(new int[4], 2, 6) = " +
Arrays.toString(ArrayUtils.add(new int[4], 2, 6)));
// merge two arrays
System.out.println(
"ArrayUtils.addAll(new int[] {1, 2}, new int [] {5, 6}) = " +
Arrays.toString(
ArrayUtils.addAll(new int[] { 1, 2 }, new int[] { 5, 6 })));
// shallow clone of an array
System.out.println("ArrayUtils.clone(new int[][] {{ 1, 2 }}) = " +
Arrays.toString(ArrayUtils.clone(new int[][] {
{ 1, 2 }
})));
// check if the value is in the array
System.out.println("ArrayUtils.contains(new int[] { 1, 2 }, 2) = " +
ArrayUtils.contains(new int[] { 1, 2 }, 2));
// remove an element from an array by index
System.out.println("ArrayUtils.remove(new int[] {1, 2, 3}, 1) = " +
Arrays.toString(ArrayUtils.remove(new int[] { 1, 2, 3 }, 1)));
// remove an element from an array
System.out.println(
"ArrayUtils.removeElement(new int[] {1, 2, 3}, 1) = " +
Arrays.toString(
ArrayUtils.removeElement(new int[] { 1, 2, 3 }, 1)));
// reverse an array (in place)
final int[] array = { 1, 2, 3 };
ArrayUtils.reverse(array);
System.out.println("reversed array = " + Arrays.toString(array));
// extract a subarray (first is inclusive, last is exclusive)
System.out.println(
"ArrayUtils.subarray(new int[] {1, 2, 3, 4}, 1, 3)) = " +
Arrays.toString(
ArrayUtils.subarray(new int[] { 1, 2, 3, 4 }, 1, 3)));
// convert an array of two-element arrays to a map
System.out.println(
"ArrayUtils.toMap(new Object[][]{{\"DE\", 1}, {\"PA\", 2 }, " +
"{\"NJ\", 3}}) = \n\t" +
ArrayUtils.toMap(
new Object[][] {
{ "DE", 1 },
{ "PA", 2 },
{ "NJ", 3 }
}));
// convert primitives to wrappers
System.out.println(
"ArrayUtils.toObject(new int[] { 1, 2, 3, 4 }) = " +
Arrays.toString(
ArrayUtils.toObject(new int[] { 1, 2, 3, 4 })));
// convert wrappers to primitives
System.out.println(
"ArrayUtils.toPrimitive(new Integer[] { 1, 2, 3, 4 }) = " +
Arrays.toString(
ArrayUtils.toPrimitive(new Integer[] { 1, 2, 3, 4 })));
}
}
> ArrayUtils.add(new int[4], 6) = [0, 0, 0, 0, 6]
> ArrayUtils.add(new int[4], 2, 6) = [0, 0, 6, 0, 0]
> ArrayUtils.addAll(new int[] {1, 2}, new int [] {5, 6}) = [1, 2, 5, 6]
> ArrayUtils.clone(new int[][] {{ 1, 2 }}) = [[I@cdedfd]
> ArrayUtils.contains(new int[] { 1, 2 }, 2) = true
> ArrayUtils.remove(new int[] {1, 2, 3}, 1) = [1, 3]
> ArrayUtils.removeElement(new int[] {1, 2, 3}, 1) = [2, 3]
> reversed array = [3, 2, 1]
> ArrayUtils.subarray(new int[] {1, 2, 3, 4}, 1, 3)) = [2, 3]
> ArrayUtils.toMap(new Object[][]{{"DE", 1}, {"PA", 2 }, {"NJ", 3}}) =
> {NJ=3, DE=1, PA=2}
> ArrayUtils.toObject(new int[] { 1, 2, 3, 4 }) = [1, 2, 3, 4]
> ArrayUtils.toPrimitive(new Integer[] { 1, 2, 3, 4 }) = [1, 2, 3, 4]
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.
package com.ociweb.jnb.jul2009;
import org.apache.commons.lang.BooleanUtils;
public class BooleanExample {
public static void main(String[] args) {
// convert int to boolean and vice verse (assumes 0 is false -
// overridden version allow that to be different
System.out.println("BooleanUtils.toBoolean(0) = " +
BooleanUtils.toBoolean(0));
System.out.println("BooleanUtils.toInteger(true) = " +
BooleanUtils.toInteger(true));
// using alternate String tuples for true|false
System.out.println("BooleanUtils.toStringOnOff(true) = " +
BooleanUtils.toStringOnOff(true));
System.out.println("BooleanUtils.toStringYesNo(true) = " +
BooleanUtils.toStringYesNo(true));
// defining a custom String tuple for true|false
System.out.println(
"BooleanUtils.toString(true, \"Yep!\", \"Nope!\") = " +
BooleanUtils.toString(true, "Yep!", "Nope!"));
System.out.println(
"BooleanUtils.toString(false, \"Yep!\", \"Nope!\") = " +
BooleanUtils.toString(false, "Yep!", "Nope!"));
// xor calculation on an array of booleans
System.out.println(
"BooleanUtils.xor(new boolean[] {true, false, true, true}) = " +
BooleanUtils.xor(new boolean[] { true, false, true, true }));
System.out.println(
"BooleanUtils.xor(new boolean[] {true, true, true, true}) = " +
BooleanUtils.xor(new boolean[] { true, true, true, true }));
System.out.println(
"BooleanUtils.xor(new boolean[] {false, false, false, false}) = " +
BooleanUtils.xor(new boolean[] { false, false, false, false }));
}
}
> BooleanUtils.toBoolean(0) = false
> BooleanUtils.toInteger(true) = 1
> BooleanUtils.toStringOnOff(true) = on
> BooleanUtils.toStringYesNo(true) = yes
> BooleanUtils.toString(true, "Yep!", "Nope!") = Yep!
> BooleanUtils.toString(false, "Yep!", "Nope!") = Nope!
> BooleanUtils.xor(new boolean[] {true, false, true, true}) = false
> BooleanUtils.xor(new boolean[] {true, true, true, true}) = false
> BooleanUtils.xor(new boolean[] {false, false, false, false}) = false
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.
OCI is the leading provider of Object Oriented technology training in the Midwest. More than 3,000 students participated in our training program over the last 12 months. Targeted toward Software Engineers and the development community, our extensive program of over 50 hands-on workshops is delivered to corporations and individuals throughout the U.S. and internationally. OCI's Educational Services include Group Training events and Open Enrollment classes.
For further information regarding OCI's Educational Services programs, please visit our Educational Services section on this site or contact us at training@ociweb.com.
OCI offers real, cost effective, open source support for the JBoss.org software and its suite of associated products. OCI has re-distribution friendly downloads at http://jboss.ociweb.com/ and provides support on a time and materials basis, (not CPU count.).
|
|
|
|