Posted on Leave a comment

Add Connection Pool with auto connection cleanup functionality for Tomcat 7 and MySQL

Tomcat Logo

Since we don’t want to use external classes or libraries to handle database connections for our web applications we should stick to what comes built-in with the container server – in my case Apache Tomcat 7 and MySQL database server.

To keep the database connection pooling and cleanup functionality on the server-side you can use the following approach:

1.) In your web-app’s META-INF/context.xml add

<?xml version="1.0" encoding="UTF-8"?>
<Context antiJARLocking="true" path="/some-project">

    <Resource name="jdbc/your-db-resource" 
              validationQuery="SELECT 1"

2.) In your WEB-INF/web.xml add reference to JDNI resource from above:


Also make sure to put the corresponding mysql connector library jar into tomcat/lib folder so that you don’t you an exception like so:

WARNING: Unexpected exception resolving reference
java.sql.SQLException: com.mysql.jdbc.Driver
at org.apache.tomcat.jdbc.pool.PooledConnection.connectUsingDriver(
at org.apache.tomcat.jdbc.pool.PooledConnection.connect(
at org.apache.tomcat.jdbc.pool.ConnectionPool.createConnection(
at org.apache.tomcat.jdbc.pool.ConnectionPool.borrowConnection(
at org.apache.tomcat.jdbc.pool.ConnectionPool.init(
at org.apache.tomcat.jdbc.pool.ConnectionPool.(
at org.apache.tomcat.jdbc.pool.DataSourceProxy.pCreatePool(
at org.apache.tomcat.jdbc.pool.DataSourceProxy.createPool(
at org.apache.tomcat.jdbc.pool.DataSourceFactory.createDataSource(
at org.apache.tomcat.jdbc.pool.DataSourceFactory.getObjectInstance(
at org.apache.naming.factory.ResourceFactory.getObjectInstance(
at javax.naming.spi.NamingManager.getObjectInstance(
at org.apache.naming.NamingContext.lookup(
at org.apache.naming.NamingContext.lookup(
at org.apache.naming.NamingContext.lookup(
at org.apache.naming.NamingContext.lookup(
at org.apache.catalina.core.NamingContextListener.addResource(
at org.apache.catalina.core.NamingContextListener.createNamingContext(
at org.apache.catalina.core.NamingContextListener.lifecycleEvent(
at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(
at org.apache.catalina.util.LifecycleBase.fireLifecycleEvent(
at org.apache.catalina.core.StandardContext.startInternal(
at org.apache.catalina.util.LifecycleBase.start(
at org.apache.catalina.core.ContainerBase$
at org.apache.catalina.core.ContainerBase$
at java.util.concurrent.FutureTask$Sync.innerRun(
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(
at java.util.concurrent.ThreadPoolExecutor$
Caused by: java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
at Method)
at java.lang.ClassLoader.loadClass(
at java.lang.ClassLoader.loadClass(
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(
at org.apache.tomcat.jdbc.pool.PooledConnection.connectUsingDriver(
… 29 more
Oct 31, 2012 11:23:25 AM org.apache.catalina.core.NamingContextListener addResource
WARNING: Failed to register in JMX: javax.naming.NamingException: com.mysql.jdbc.Driver
Oct 31, 2012 11:23:25 AM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler [“http-bio-8086”]
Oct 31, 2012 11:23:25 AM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler [“ajp-bio-8009”]
Oct 31, 2012 11:23:25 AM org.apache.catalina.startup.Catalina start
INFO: Server startup in 794 ms

That’s it!

A sample connection wrapper class would be:

package at.kerstner;

import java.sql.Connection;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;

abstract class DBConnection {

    public static Connection getConnection() {
        Connection conn = null;
        try {
            Context initContext = new InitialContext();
            Context envContext = (Context) initContext.lookup("java:/comp/env");
            DataSource ds = (DataSource) envContext.lookup("jdbc/your-db-resource");
            conn = ds.getConnection();
        } catch (Exception e) {
            System.err.println("Failed to get connection: " + e.getMessage());
        return conn;

Also make sure to have a look at my other post concerning problems when loading the resource factory class.

Posted on 2 Comments

Tomcat 7 Fails to load Resource Factory class

Tomcat Logo

In case you get the exception Could not load resource factory class when trying to retrieve the Connection object from the JDBC connection resource pool based on the factory class org.apache.tomcat.jdbc.pool.DataSourceFactory make sure to check if tomcat-jdbc.jar is installed in the tomcat/lib directory. Please note that this file is not installed by default on most *nix systems. You can download tomcat-jdbc.jar from Maven or other sources.

Posted on 3 Comments

Serving Files using Jersey Web Service (JAX-RS)

Jersey Logo

There are a lot of tutorials out there explaining how to send binary data (i.e. application/octet-stream) as response for Jersey web services (Java JAX-RS). Two possible solutions are based on either returning a Response or StreamingObject containing the appropriate binary data stream.

Below you find a simple example for both scenarios:

//either inject response via context
private HttpServletResponse response;

//or return Response as shown below

 * @param content
 * @return
@Consumes("text/plain; charset=UTF-8")
public Response getAttachment(
  @QueryParam("file") String fileName) {
  try {
    if (fileName == null) {
      System.err.println("No such item");
      return Response.status(Response.Status.BAD_REQUEST).build();

    // either set response injected above
    //response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
    //TODO: write file content to response.getOutputStream();
    //return response;

    // OR: use a custom StreamingOutput and set to Response
    StreamingOutput stream = new StreamingOutput() {
      public void write(OutputStream output) throws IOException {
        try {
          // TODO: write file content to output;
        } catch (Exception e) {

    return Response.ok(stream, "image/png") //TODO: set content-type of your file
            .header("content-disposition", "attachment; filename = "+ fileName)

  System.err.println("No such attachment");

  return Response.status(Response.Status.BAD_REQUEST).build();

  } catch (Exception e) {
     return Response.status(Response.Status.BAD_REQUEST).build();

Additional checks have been ommitted for better readability. You should definitely check parameter fileName and not use it directly to serve files 😉

Pretty easy, right?

Posted on 9 Comments

Convert GPS Coordinates to Address using Google Geocoding API using Java

Google Logo

Google Maps makes it easy to convert addresses to their corresponding GPS coordinates using the Geocoding API. But what if you want to do the reverse, i.e. convert GPS coordinates to the corresponding address? Simple, just use Google’s ReverseGeocoding functionality.

Below you find a simple Java example of how to use the API to convert GPS coordinates to addresses:

package at.kerstner.geocoding;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;

 * @param lng
 * @param lat
 * @return
    private String getAddressByGpsCoordinates(String lng, String lat)
            throws MalformedURLException, IOException, org.json.simple.parser.ParseException {
        URL url = new URL(""
                + lat + "," + lng + "&sensor=true");
        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
        String formattedAddress = "";

        try {
            InputStream in = url.openStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(in));
            String result, line = reader.readLine();
            result = line;
            while ((line = reader.readLine()) != null) {
                result += line;

            JSONParser parser = new JSONParser();
            JSONObject rsp = (JSONObject) parser.parse(result);

            if (rsp.containsKey("results")) {
                JSONArray matches = (JSONArray) rsp.get("results");
                JSONObject data = (JSONObject) matches.get(0); //TODO: check if idx=0 exists
                formattedAddress = (String) data.get("formatted_address");

            return "";
        } finally {
            return formattedAddress;

The example above retrieves the formatted address of the first result found. Additional checks have been omitted for better readability.

The API response has the following format:

"formatted_address":"Entenplatz 1, 8020 Graz, Austria",



You also might want to checkout for an easy way to handle and convert coordinates and preview them on a map.

Posted on 2 Comments

Setting Custom Portlet Titles in Liferay

Liferay Logo

Setting custom portlet titles in Liferay can be a little tricky. Changing the title via the portlet configuration in the frontend is easy but when it comes to reading the custom title property programmatically things seem to get a little messy.

Setting the Title

So, first of set your portlet title as usual via the portlet configuration in the frontend. That’s the easy part.

Determining Portle Title Programmatically

Then, in order to determine custom portlet titles use the following code:

ThemeDisplay themeDisplay = ((ThemeDisplay) request
String portletId = themeDisplay.getPortletDisplay().getId();
javax.portlet.PortletPreferences portletSetup = PortletPreferencesFactoryUtil
  .getLayoutPortletSetup(themeDisplay.getLayout(), portletId);
String portletCustomTitle = themeDisplay.getPortletDisplay()
portletCustomTitle = portletSetup.getValue("portletSetupTitle_"
  + themeDisplay.getLanguageId(), portletCustomTitle);

This code will determine the current portlet’s ID, get its preferences, determine the current namespace and finally retrieve the custom portlet title.

In case you need to read other custom portlet properties simply look up their keys in the database and use the portletSetup.getValue(“yourKey_”, …) option as shown previously.

Posted on Leave a comment

Bugfix for urbanairship-java SDK Connection Still Allocated

Apart from another bug reported in there also exists a bug related to the internal use of BasicClientConnManager for sending HTTP requests.

The Cause

When trying to send multiple HTTP requests using sullis urbanairship-java SDK (occasionally) an IllegalStateException is thrown. This is caused due to the fact that the version does not release open connections properly. You will get an exception similar to the one shown below:

java.lang.IllegalStateException: Invalid use of BasicClientConnManager: connection still allocated.
Make sure to release the connection before allocating another one.
        at org.apache.http.impl.conn.BasicClientConnectionManager.getConnection(
        at org.apache.http.impl.conn.BasicClientConnectionManager$1.getConnection(
        at org.apache.http.impl.client.DefaultRequestDirector.execute(
        at org.apache.http.impl.client.AbstractHttpClient.execute(
        at org.apache.http.impl.client.AbstractHttpClient.execute(
        at org.apache.http.impl.client.AbstractHttpClient.execute(
        at com.urbanairship.UrbanAirshipClient.execute(
        at com.urbanairship.UrbanAirshipClient.get(
        at com.urbanairship.UrbanAirshipClient.getDevice(
        ... (and many more)

The Fix

The fix is pretty easy. First and foremost make sure to use an apache-commons-httpclient version newer or equals than 4.2, since from this version onwards it offers a releaseConnection() that makes our life much easier (link: ). Then, in add method.releaseConnection(), as shown below:

protected HttpResponse execute(HttpRequestBase method) {
  try {
    method.setHeader(new BasicHeader("Accept", "application/json"));
    HttpResponse rsp = getHttpClient().execute(method);
    checkResponse(method, rsp);
    return rsp;
  } catch (RuntimeException rtex) {
    throw rtex;
  } catch (Exception ex) {
    throw new RuntimeException(ex);

That’s it! Enjoy 🙂

Posted on Leave a comment

Bugfix für urbanairship-java SDK JsonParseExceptionBugfix for urbanairship-java SDK JsonParseException

There (still) exists a bug in urbanairship-java SDK related to parsing valid ISO8601 dates. The original bug report can be found here: GSon date parsing error.

The Cause

ISO8601 states that for date-time strings the separator “T” can be left out. Unfortunately the urbanairship-java SDK expects only fully qualified ISO8601 strings. Thus, when it receives a (perfectly valid) date-time string such as the one shown below it throws a JsonParseException:

    "device_token": "XXX",
    "last_registration": "2012-12-27 08:24:33",
    "tz": null,
    "tags": [],
    "alias": null,
    "quiettime": {
        "start": null,
        "end": null
    "active": true,
    "badge": 0

The stacktrace caused by the JsonParseException thrown looks similiar like the one shown below: 2012-12-27 08:24:33
	at com.urbanairship.GsonFactory$CalendarAdapter.deserialize(
	at com.urbanairship.GsonFactory$CalendarAdapter.deserialize(
	at com.urbanairship.UrbanAirshipClient.fromJson(
	at com.urbanairship.UrbanAirshipClient.fromJson(
	at com.urbanairship.UrbanAirshipClient.get(
	at com.urbanairship.UrbanAirshipClient.getDevice(
	... many more

The problem is caused in the fromJSON function in

protected <T> T fromJson(final String json, final Class<T> clazz) {
  Gson gson = GsonFactory.create();
  return gson.fromJson(json, clazz); // PROBLEM HERE

The Fix

Luckily the fix is pretty easy. Open and update the PATTERN variable as follows:

public class ISO8601
	//public static final String PATTERN = "yyyy-MM-dd'T'HH:mm:ssZ"; //BUG HERE
	public static final String PATTERN = "yyyy-MM-dd HH:mm:ss"; //BUG FIXED    

That’s it. I’ve updated the bug report accordingly.

Posted on 1 Comment

Setting Custom Timezones in Liferay

Liferay Logo

By default Liferay uses UTC as timezone. In order to set custom timezones you may choose from the following options:

  1. Create an EXT-Plugin
  2. Specify timezone in Tomcat’s setenv script


Create an EXT-plugin (or use your existing one) and put in extyour-extdocrootWEB-INFext-implsrc using the following setting:


Be sure the deploy and restart Tomcat afterwards. Also, check via the Control Panel in Server Administration / System properies that the timezone attribute has been applied correctly.

Setenv Script

The other option is to set your desired timezone in Tomcat’s setenv script located in tomcat/bin by using the following command:


Depending on your operating system you will need to configure setenv.bat (Windows) or

Liferay Developer Studio

If you happen to use Liferay Developer Studio you can easily set your desired timezone using the server properties, as shown below:

Posted on Leave a comment

Custom Response Types in Jersey SecurityContext

Jersey Logo

Sometimes you might need to return custom response types in your SecurityContext implementation when using Jersey RESTFul web services. Basically, there are two options available to do so:

  1. Use and throw a WebApplicationException
  2. or write your own ExceptionMapper

Throw WebApplicationException

import com.liferay.portal.kernel.json.JSONFactoryUtil;
import com.liferay.portal.kernel.json.JSONObject;

public class MySecurityContext implements SecurityContext {

	private final User user;
	private final Session session;

	public MySecurityContext(User user, Session session) {
		this.user = user;
		this.session = session;

	public String getAuthenticationScheme() {
		return SecurityContext.BASIC_AUTH;

	public Principal getUserPrincipal() {
		return user;

	public boolean isSecure() {
		return false;

	public boolean isUserInRole(String role) {

		JSONObject jsonObj = JSONFactoryUtil.createJSONObject();

		if (null == session || !session.isActive()) {
			jsonObj.put("status", "failed");
			jsonObj.put("message", "Authentication failed"); denied =
					.type("application/json; charset=utf-8")

			throw new WebApplicationException(denied);

		try {
			return user.getRoles().contains(role);
		} catch (Exception e) {

		return false;

Custom ExceptionMapper

The other (even nicer option) is to write your own ExceptionMapper:

public MyMapper implements ExceptionMapper<WebApplicationException> {
   public Response toResponse(WebApplicationException ex) {
     Response r = ex.getResponse();
     if (r.getStatus() == 403 && r.getEntity() == null) {
      return Response.fromResponse(r).entity(
        new Viewable("/403response", null)).build();
     } else {
       return r;
Posted on 1 Comment

Setting Custom User Model Attributes in Liferay

Liferay Logo

Oftentimes you will need to extend Liferay’s built-in User model by adding custom attributes, such as a list of preferred settings. Fortunately, Liferay provides developers with an ExpandoBridge implementation to do so.

Thus, in order to add custom attributes simply use the Custom Fields option via the Control Panel (or programmatically). Search for the User model and add your custom field(s). In order to programmatically access these properties you now have two options. First, you may iterate over all custom fields set, or access custom fields through their key.

Access List of Custom Attributes

The following code snippet shows how to access the list of custom attributes set:

Map<String, Serializable> customAttributes = userLiferay
Iterator<String> it = customAttributes.keySet().iterator();

while (it.hasNext()) {
  String attribute =;
  Serializable attributeValue = customAttributes.get(attribute);
  System.out.println("user custom attribute " + attribute + "="
    + attributeValue);

When getting NULL instead of your desired value when using getAttribute be sure to check for corrects permissions.

Access Specific Custom Attribute

The other option is to access specific custom fields by using its key through ExpandoValueLocalServiceUtil, as shown below:

String userBookmarksString = (String) ExpandoValueLocalServiceUtil
    userExpBridge.getClassName(), "CUSTOM_FIELDS",
    "yourCustomField", userExpBridge.getClassPK());

Updating Custom Attributes

Finally, in case you need to update a custom field use the following code:

ExpandoValue expVal = ExpandoValueLocalServiceUtil
    userExpBridge.getClassName(), "CUSTOM_FIELDS",
    "yourCustomField", userExpBridge.getClassPK());

That’s it!

Posted on 1 Comment

Determining Absolute Path for FileEntry in Liferay

Liferay Logo

In case you are wondering how to determine the absolute path to FileEntry objects in Liferay (i.e. Document and Media Library elements) here is how it works.

First, add the following to your


Then, to calculate the absolute path for a FileEntry use the following code:

private String getDLFileAbsPath(FileEntry fileEntry) 
throws PortalException, SystemException {
  return PropsUtils.get("dl.hook.file.system.root.dir") + "/" 
    + fileEntry.getCompanyId() + "/"
    + fileEntry.getFolderId() + "/"
    + ((DLFileEntry) fileEntry.getModel()).getName() + "/"
    + fileEntry.getVersion();

Note that in order to get the foldername where your FileEntry resides you need to cast FileEntry to DLFileEntry, as shown above.

Posted on Leave a comment

Dynamically determine Structure IDs in Liferay

Liferay Logo

When using multiple Web Content (aka JournalArticle) structures in Liferay managing their corresponding IDs via configuration files can become a tedious task. Luckily, there is an easy way to determine structure IDs dynamically based on their title, like the following code snippet demonstrates:

private static String STRUCTUREID = null;

private String getStructureId() {
  try {
    if (STRUCTUREID != null) {
      return STRUCTUREID; // already set

    DynamicQuery dynamicQuery = DynamicQueryFactoryUtil.forClass(
      "%\">Your Structure Title</>%"));
  @SuppressWarnings("unchecked") //optional
  List<JournalStructure> structures = JournalStructureLocalServiceUtil.
    dynamicQuery(dynamicQuery, 0, 1);

  if (structures.size() < 1) {
    System.out.println("No structure found");
    return null;

  STRUCTUREID = structures.get(0).getStructureId();

  System.out.println("Structure ID=" + STRUCTUREID);


} catch (SystemException e) {
    return null;
Posted on 3 Comments

Determine latest version of Web Content in Liferay

Liferay Logo

Most of the time when using Liferay’s Web Content (i.e. JournalArticle) you will want to determine the latest version to be displayed to your users. The following code snippet shows a simple solution to do so:

List<JournalArticle> articles = JournalArticleLocalServiceUtil.getStructureArticles(GROUPID, STRUCTUREID);
ListIterator<JournalArticle> it = articles.listIterator();
List<String> checkedArticleIds = new ArrayList<String>();

while (it.hasNext()) {
  JournalArticle article =;

  if (checkedArticleIds.contains(article.getArticleId())) {
    continue; // previous article version already checked

  JournalArticle articleLastVersion = JournalArticleLocalServiceUtil.getLatestArticle(GROUPID, article.getArticleId());


  System.out.println("Added articleId " + article.getArticleId() + " with version " + article.getVersion());