Base Lang Classes


Unfortunately, the functionality in the base org.apache.commons.lang classes does not easily sort into any particular logical groups. Therefore, this section touches on each class in alphabetical order.

ArrayUtils

The ArrayUtils class affords the following basic functionality: a set of immutable empty arrays corresponding to all of the various primitive types and their corresponding object types, clone operations for primitive arrays, and methods to check if an array contains a particular value. For example, the code:

 boolean contains = false; for(int i = 0; i < myArray.length; i++)     if(myArray[i] == searchVal) contains = true; 

...can be replaced with a simple:

 boolean contains = ArrayUtils.contains(myArray, searchVal); 

In addition, indexOf methods will return the index of the search value (or -1 if the search value is not found). The lastIndexOf methods work backwards. The double versions of contains, indexOf, and lastIndexOf methods even allow for a search range tolerance.

An isEquals method with support for multidimensional arrays is provided. A set of reverse methods is provided to reorder arrays. The toMap method converts an object array to a java.util.Map instance. Finally, toObject and toPrimitive methods allow for easy conversion of arrays from the primitive version to object versions. For example:

 long[] vals = {1, 2, 3}; Long valObjects = ArrayUtils.toObject(vals); 

BitField

A wide suite of operations for operating on bits. Unlike many of the other operations in the base Lang package, a BitField is an actual class, not a collection of static methods.

A BitField is created with an int mask, specifying the number of bits of interest. Further operations may be performed using provided methods, such as clearing and setting particular bits.

BooleanUtils

Methods for working with boolean valuesin particular, operations for converting values to and from boolean values. For example, this:

 boolean isOk = true; String result; if(isOk)     result = "ready"; else     result = "not ready"; 

...can be replaced simply with:

 String result = BooleanUtils.toString(isOk, "ready", "not ready"); 

Generally speaking, BooleanUtils can be grouped into a set of methods to convert values to Boolean or boolean or from a boolean/Boolean to integers or String objects. Additional methods are provided specifically for converting strings such as "on," "off," "true," "false," "yes," and "no" to and from boolean/Boolean values.

Finally, xor methods are provided for Boolean/boolean arrays.

CharRange, CharSet, and CharSetUtils

A CharRange represents a contiguous range of characters. The CharSet class uses the CharRange class to express various ASCII ranges such as alphabetic and numeric characters.

For character sets that happen to afford logical sorting of characters into ranges (such as ASCII), these classes provide helpful containment checks. The full range of Unicode characters supported by Java is much larger than ASCII, however, and so many applications will likely need to describe their own CharRange sets, perhaps in conjunction with the data available from the java.lang.Character.

You can use CharRange and CharSet values (either the predefined values or custom values) in conjunction with the CharSetUtils class to perform certain useful operations, such as counting the number of characters, deleting characters present in a String based on sets passed in, or even squeezing repeated characters as shown:

 String in = "abc123def"; String chars = CharSetUtils.delete(in, CharSet.ASCII_NUMERIC         .toString()); String nums = CharSetUtils.keep(in, CharSet.ASCII_NUMERIC         .toString()); System.out.println(chars); // prints abcdef System.out.println(nums);  // prints 123 String extras = "bookkeeping"; extras = CharSetUtils.squeeze(extras, CharSet.ASCII_ALPHA         .toString()); System.out.println(extras);  // prints bokeping 

ClassUtils

In addition to BeanUtils, the Lang ClassUtils package provides additional functionality for working with classes. The utilities in this package do not use the functionality in the java.lang.reflect.* packagethey use only the information available directly from java.lang.Class and where possible from the class name (for example, the class name string is parsed to retrieve package information in lieu of reflection).

The methods convertClassesToClassNames and convertClassNamesToClasses convert a List of classes to class names and back. The methods getAllInterfaces and getAllSuperclasses return List objects. Although it's hard to think of a relevant situation for applications other than development tools, an isInnerClass method is provided. Several different signatures are provided to getPackageName and getShortClassName. Perhaps one of the most useful is the isAssignable method, allowing you to check if you can cast a value before actually performing the operation (which is useful if you want to check if an assignment is valid without incurring the risk of a ClassCastException).

ObjectUtils and ObjectUtils.Null

The ObjectUtils class principally provides extra semantic control over null values. For example, defaultIfNull, equals, and toString implementations all handle null values gracefully. The appendIdentityToString allows you to retrieve the identity value normally returned by the Object.toString implementation even if the object has overridden toString.

Perhaps the most interesting part of ObjectUtils is the addition of an ObjectUtils.Null class to serve as a placeholder for null in instances when null has an additional meaning. Ironically, the addition of type-safe collections to JDK 1.5 will likely mean that this class is increasingly less useful, which is probably for the best in many situations.

RandomStringUtils

The various implementations of random in this class allow you to easily create random string values according to a wide range of configurable options.

 System.out.println(RandomStringUtils.randomAscii(16)); // Prints ]_uKDOL*md):fDTT System.out.println(RandomStringUtils.randomAlphabetic(16)); // Prints ygatjcqBbYbCwVBt System.out.println(RandomStringUtils.randomNumeric(16)); // Prints 6731467475431887 char[] availChars = {'A', 'B', 'C', 'D'}; System.out.println(RandomStringUtils.random(16, availChars)); // Prints ADDADCCCDDDDCCBC 

Note that an additional RandomUtils package is provided in the Lang math package, which is described later.

SerializationUtils

This class provides a few methods to assist with the use of Java serialization. The functionality available includes a generic deep clone operation, allowing a graph of objects to be serialized with a single method call. In addition, serialization and deserialization methods are provided, which wrap the various exceptions as well as the closing of the stream.

StringEscapeUtils

This class is perhaps one of the most immediately useful for many web applications. Routines are provided to escape and unescape strings for Java, JavaScript, HTML, XML, and SQL. This is useful to guard against attempts by unscrupulous users to inject code into your application (for example, JavaScript in a bit of text to be displayed on a web page, or even an attempt to inject SQL into a form in an attempt to hijack a database).

Here is a comparison of the various escape routines in action:

 String HTML = "<B>$ to \u00A3 Rate</B>"; String Java = "\"It's on my \t tab\""; String SQL = "Ain't bad"; // Original values System.out.println(HTML); System.out.println(Java); System.out.println(SQL); System.out.println(); // Conversion examples System.out.println(StringEscapeUtils.escapeHtml(HTML)); System.out.println(StringEscapeUtils.escapeXml(HTML)); System.out.println(StringEscapeUtils.escapeJava(Java)); System.out.println(StringEscapeUtils.escapeJavaScript(Java)); System.out.println(StringEscapeUtils.escapeSql(SQL)); 

. . . produces the output:

 <B>$ to £ Rate</B> "It's on my      tab" Ain't bad &lt;B&gt;$ to &pound; Rate&lt;/B&gt; &lt;B&gt;$ to &#163; Rate&lt;/B&gt; \"It's on my \t tab\" \"It\'s on my \t tab\" Ain''t bad 

StringUtils

The StringUtils class contains a variety of null-safe miscellaneous methods. All of the methods will gracefully handle null values, simply returning null if null is passed as an argument.

isAlpha
isBlank
isEmpty
isNumeric
isWhitespace
contains
containsOnly
containsNone
equals

The various is methods check if the entire String evaluates to true for the mentioned condition.
The contains methods check against a set of characters passed as an argument.

indexOf
indexOfAny
indexOfAnyBut
lastIndexOf
lastIndexOfAny
lastIndexOfAnyBut
countMatches

Various methods to search Strings.

left
mid
right
substring
substringAfter
substringBefore
substringBetween
trim

Methods to trim Strings in various ways.

center
leftPad
repeat
rightPad
strip

Methods that assist the presentation of Strings, particularly useful for console applications.

split

join

split serves as a more convenient wrapper to the StringTokenizer.
join serves as an easy way to fuse an array or Iterator into a single String.

replace
replaceChars
replaceOnce
delete
overlay

Manipulate one String with another.

uppercase
lowerCase
swapCase
capitalize
uncapitalize

Manipulate the case of a String.

defaultString

Wrapper to automatically protect against null values.

chomp

chop

chomp removes the last bit of new line information from a String.
chop removes the last character of a String.

reverse
reverseDelimited

Reverse a String.

difference

Returns the differing characters between two String objects.

abbreviate

Abbreviates a String, terminating with an ellipsis if necessary.

getLevensteinDistance

Number of changes needed to change one String into another.


Most of these methods are self-explanatory. The getLevensteinDistance is perhaps the most unusualit calculates the number of changes need to convert a String from one value to another. Below are examples of the use of the two most interesting methods:

 String longLine = "This is a long bit of text."; System.out.println(StringUtils.abbreviate(longLine, 15)); System.out.println(StringUtils.abbreviate(longLine, 100)); String start = "time"; String end = "fine"; System.out.println(StringUtils.getLevensteinDistance(start, end)); 

This code produces the following output:

 This is a lo... This is a long bit of text. 2 

SystemUtils

The SystemUtils class provides two basic bits of functionalitya set of static variable values corresponding to the various standard system properties, such as file.encoding, file.separator, java.class.path, etc., and a suite of boolean values corresponding to a wide variety of possible platform checks a user might want to perform (e.g., IS_OS_MAC_OSX).

An additional version check method is provided to detect the Java version, allowing for easy basic system conformance checks. For example:

 System.out.println(SystemUtils.isJavaVersionAtLeast(1.3f)); 

... returns the value true on a JDK 1.4 system.

Validate

Validation essentially serves as a mechanism for evaluating conditions and throwing an exception if the condition is not true. Most significantly, the various assertions will generate exceptions and will run on a variety of platforms.

 Validate.isTrue( i > 0, "The value must be greater than zero: ", i); Validate.notNull( surname, "The surname must not be null"); 

A suite of static methods is used to assert that values and expressions evaluate to true; otherwise an exception is thrown. An advantage of the Validate class is that it allows you to easily set a message string on the thrown exception. This makes Validate more useful for validating user-generated data, as opposed to developer-managed interactions.

On JDK 1.4 or later systems, for development-level contracts, you may want to use assertions instead. For more information, see http://java.sun.com/j2se/1.4.2/docs/guide/lang/assert.html. If you have adopted JUnit (http://www.junit.org/) as a test framework, you may want to use that assertion facility instead (http://www.junit.org/junit/javadoc/3.8.1/junit/framework/Assert.html).

WordUtils

The WordUtils class in many ways serves as an extension of the already large StringUtils class. It works with whitespace-delimited words, mainly performing various capitalization operations. The capitalize method works only on the first letter of each word, whereas the capitalizeFully method works on all of the alphabetical characters. The uncapitalize method only works on a single character (there is no unCapitalizeFully method). This class also offers a wrap function, useful for console applications. For example, the code:

 String sample = "this is a GREAT System! "; System.out.println(WordUtils.capitalize(sample)); System.out.println(WordUtils.capitalizeFully(sample)); System.out.println(WordUtils.uncapitalize(sample)); System.out.println(WordUtils.swapCase(sample)); sample = sample + sample + sample + sample + sample; System.out.println(WordUtils.wrap(sample, 45)); 

. . . produces the result:

 This Is A GREAT System! This Is A Great System! this is a gREAT system! THIS IS A great sYSTEM! this is a GREAT System! this is a GREAT System! this is a GREAT System! this is a GREAT System! this is a GREAT System! 



    Apache Jakarta Commons(c) Reusable Java Components
    Real World Web Services
    ISBN: N/A
    EAN: 2147483647
    Year: 2006
    Pages: 137
    Authors: Will Iverson

    flylib.com © 2008-2017.
    If you may any questions please contact us: flylib@qtcs.net