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 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 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 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 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.
The Logger is an easy to use class for logging information of different severities in code (ranging from debugging information to fatal errors). There are many logging APIs that are always evolving... this provides a proxy to a suitable one (Log4J at present).
The system property logger.provider can specify which logging system you wish to use. The following log providers are currently available:
The following is an example of how you can start your app server with one of
these providers:
java -Dlogger.provider=com.opensymphony.provider.log.FullLogProvider ...
public class MyClass {
private static final Logger logger = new Logger(MyClass.class);
public void doSomething() { logger.debug("doing something"); try { someThing(); logger.debug("done something"); } catch (SomeException e) { logger.error("something went wrong", e); } }
public void blah(Thingy t) { if (logger.isDebugEnabled()) logger.debug("thingy is " + t.showMe()); .... }
}
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 l = DataUtil.getLong(new Long(10)); // l == 10 int i = DataUtil.getInt(null); // i == 0