Monday, July 9, 2012

Formatting a number to currency in Java


import java.text.NumberFormat;
// Get a currency formatter for the current locale.
NumberFormat fmt = NumberFormat.getCurrencyInstance();
System.out.println(fmt.format(120.00));
If your current locale is in the US, the println will print $120.00
Another example:
import java.text.NumberFormat;
import java.util.Locale;
Locale locale = new Locale("en", "UK");
NumberFormat fmt = NumberFormat.getCurrencyInstance(locale);
System.out.println(fmt.format(120.00));
This will print: £120.00

Monday, June 13, 2011

Accessing ADF ViewObject's property in Groovy

Use this to access any field in ViewObject

"adf.object.viewObject.yourPropertyName"

Wednesday, March 2, 2011

Getting context path in serlvets

if (servletContext.getMajorVersion() == 2
&& servletContext.getMinorVersion() <= 4) {
return servletContext.getServletContextName();
} else {
return servletContext.getContextPath();
}

Getting objects created in current java thread

There are two ways to resolve object dependency in java e.g. objects created in one method will be needed in other method in the same thread request. One way of resolving this dependency is that you pass newly created objects as parameter to method but this approach has drawback e.g. if you have created an object in one method, then that method is calling another which is calling another method and that method requires object created in first method then using first approach you will have to pass object in the parameter of second method and then second method will pass it to third method as parameter. As second method does not require it but we will have to pass it to resolve dependency of third method.
Second and most efficient approach is using ThreadLocal class. You can set object in first method to this class by this:
threadLocal.set(contextObject);
Now in third method you can get this object using this:
threadLocal.get();
Usually this approach is used with objects which are current request's context related e.g. FacesContext object is the key object in JSF and is required to use it anywhere in the request. so JSF creates instance of FacesContext in each request and set it to ThreadLocal. and then later on returns it from ThreadLocal.



Tuesday, March 1, 2011

Getting java web classloader

J2EE 1.3 (and later) containers are required to make the web application class loader visible through the context class loader of the current thread. You can access it like this:
ClassLoader cl = Thread.currentThread().getContextClassLoader();