OSCore - OSCore Utility Classes
The following is a brief description of the different utility classes provided by OSCore. Along with each short description is some example Java code that takes advantage of some of the features provided by each utility class. However, we recommend that you read the JavaDocs to completely discover all the methods and features each class provides.
- TextUtils - useful functions for manipulating Strings. Examples include: extracting primitive types, verifying e-mail addresses, splitting and joining, escaping characters, hyperlinking text, indentation, etc.
- XMLUtils - common XML functions such as parsing and printing DOM documents, performing XSL transformations and selecting nodes using XPATH.
- EJBUtils - common EJB and JNDI based functions such as looking up and narrowing home interfaces and looking up entity-beans directly.
- BeanUtils - useful methods for accessing values of objects using reflection.
- MultipartException - a special type of Exception designed to be subclassed for holding many child Exceptions. Useful if validation can throw many Exceptions and they all need to be wrapped up into and report (for example).
- Data - an Object wrapper for binary data.
- OrderedMap - a java.util.Map implementation that retains the order items were added in.
- DataUtil - a small class that helps convert Objects to their primitive types.
- DateUtil - a small class for handling ISO 8601 International Date formats.
TextUtils
TextUtils provides helpers for common operations on text (mainly Strings and numbers).
int a = TextUtils.parseInt("1"); // returns 1
int b = TextUtils.parseInt("-45345"); // returns -45345
int c = TextUtils.parseInt("abc"); // returns 0 (instead of throwing exception)
long d = TextUtils.parseLong("12345678901234");
float fl = TextUtils.parseFloat("123.456");
double db = TextUtils.parseDouble("12345678.901234");
boolean e = TextUtils.parseBoolean("yes"); // true
boolean f = TextUtils.parseBoolean("true"); // true
boolean g = TextUtils.parseBoolean("1"); // true
boolean h = TextUtils.parseBoolean("false"); // false
boolean i = TextUtils.parseBoolean("blah"); // false
int p = TextUtils.parseInt( TextUtils.extractNumber("$1,000,000 only!") ); // 1000000
String lower = TextUtils.noNull(myStr).toLowerCase(); // prevent NullPointerException // if myStr is null by returning ""
boolean v1 = TextUtils.verifyEmail("joe@bloggs.com"); // true
boolean v2 = TextUtils.verifyEmail("a.b-d.c@def.ghi.co.jp"); // true
boolean v3 = TextUtils.verifyEmail("nothing@blah"); // false
boolean v4 = TextUtils.verifyEmail("la la la"); // false
java.awt.Color col = TextUtils.hexToColor("#ff3300");
String hexCol = TextUtils.colorToHex( col.darker() );
EJBUtils
EJBUtils simply provides some shortcuts for common EJB/JNDI operations (namely looking up JNDI bound objects and narrowing them).
// standard method
Context ctx = new InitialContext();
Object obj = ctx.lookup("java:comp/env/ejb/MyBean");
MyBeanHome myBeanHome = (MyBeanHome)PortableRemoteObject.narrow( obj, MyBeanHome.class );
// shortcut
MyBeanHome myBeanHome = (MyBeanHome) EJBUtils.lookup("ejb/MyBean", MyBeanHome.class);
XMLUtils
XMLUtils provides common operations for parsing, printing, navigating, manipulating and transforming XML data. XMLUtils acts a wrapper to JAXP providers.
Document doc1 = XMLUtils.parse( new File("blah.xml") ); // parse from file
Document doc2 = XMLUtils.parse( new URL("http://blah.com/blah.xml") ); // parse from URL
Document doc3 = XMLUtils.parse( myReader ); // parse from Reader
..... // and so on...
// parse XML directly from String Document doc = XMLUtils.parse( "<test name='blah'><nodes><x>hello</x><x>world</x></nodes></test>" );
// retrieve first <x> node Element xTag = (Element)XMLUtils.xpath( doc, "/test/nodes/x" );
// get contents of <x> tag ('hello')
String hello = XMLUtils.getElementText( xTag );
// return all <x> tags NodeList xTags = XMLUtils.xpathList( doc, "/test/nodes/x" );
// create new document with root tag of <mydoc name='blah'>
Document newDoc = XMLUtils.newDocument("mydoc");
newDoc.getDocumentElement().setAttribute("name","blah");
// pretty-print DOM document into String String final = XMLUtils.print(newDoc);
// perform XSL transformation, caching the compiled XSL
XMLUtils.transform( new FileReader("input.xml"),
new FileReader("input.xsl"),
new FileWriter("output.html") );
// clone the contents of xTag into a brand new document Document anotherDoc = XMLUtils.newDocument(); XMLUtils.cloneNode( xTag, anotherDoc, true );
BeanUtils
BeanUtils provides a simple interface to accessing properties of an object. It is particularly useful for developing JSP Tags that need to read/write bean values.
//// setup fictional Person object for example
Person person = new Person();
person.setName("Bob");
person.setEmail("b@ob.com");
person.setAge(43);
person.setPassword("blah");
// add Address object to person
Address address = new Address();
address.setNumber(12);
address.setStreet("Bobby Street");
address.setTown("Bobsville");
address.setCountry("US");
person.setAddress(address);
// add Child objects to Collection
person.getChildren().add( new Child("Jane" );
person.getChildren().add( new Child("Bob Jnr" );
//// end of example setup
// access simple properties String name = (String) BeanUtils.getValue( person, "name" ); // returns "Bob" String email = (String) BeanUtils.getValue( person, "email" ); // returns "b@ob.com" Address addr = (Address) BeanUtils.getValue( person, "address" ); // returns Address object Integer age = (Integer) BeanUtils.getValue( person, "age" ); // returns 43
// access nested properties String town = (String) BeanUtils.getValue( person, "address.town" ); // returns "Bobsville" Integer number = (Integer) BeanUtils.getValue( person, "address.number" ); // returns 12
// access Collection (notice how methods and elements in Collections/arrays can be accessed) Integer childCount = (Integer) BeanUtils.getValue( person, "children.size()" ); // returns 2 Iterator allChildren = (Iterator) BeanUtils.getValue( person, "children.iterator()" ); // returns iteration of all children Child firstChild = (Child) BeanUtils.getValue( person, "children[0]" ); // returns 'Jane'
// set values
BeanUtils.setValue( person, "name", "Bobby" ); // person.setName("Bobby")
BeanUtils.setValue( person, "age", new Integer(44) ); // person.setAge(44)
BeanUtils.setValue( person, "address.town", "Newsville" );
// person.getAddress().setTown("Newsville");
// accessing properties in bulk
Map personFields = BeanUtils.getValues( person, null ); // return Map containing name/value
// pairs of all properties of person.
Map someFields = BeanUtils.getValues( person, {"name","email"} ); // return Map containing name/value
// pairs of 'name' and 'email' properties
// only.
DataUtil
The DataUtil class offers a few static methods that convert objects that represent a primitive in to an actual primitive. If the object passed in is null, a default primitive value is returned (usually 0).
long myLong = DataUtil.getLong(new Long(10)); // myLong == 10 int myInt = DataUtil.getInt(null); // myInt == 0
DateUtil
The Internet is a truly International method of communicating - there are no political or cultural boundaries drawn on the www page you call up - the page could have been stored in the Smithsonian Institute or on a small server in a basement in Ulan Bator, Mongolia. Often, you have no way of telling. So, if anyone in the world can read your page, why not ensure that any date references on that page can be read correctly and unambiguously by that person, by using the ISO 8601:1988 International Date Format.
The basic format is: "CCYYMMDDThhmmsssss±nnn"
| Characters used in place of digits or signs | |
|---|---|
| [Y] | represents a digit used in the time element year |
| [M] | represents a digit used in the time element month |
| [D] | represents a digit used in the time element day |
| [T] | place holder denoting time |
| [h] | represents a digit used in the time element hour |
| [m] | represents a digit used in the time element minute |
| [s] | represents a digit used in the time element second |
| [n] | represents digit(s), constituting a positive integer or zero |
| [±] | represents a plus sign [+] if in combination with the following element a positive value or zero needs to be represented, or a minus sign [] if in combination with the following element a negative value needs to be represented. |
The expanded format includes formating: "CCYY-MM-DDThh:mm:ss,sss±nnn"
