Thursday, May 17, 2012

RowIdTableDecorator for Display Tag

/**
 * RowIdDisplayTagDecorator.java

 * Creation Date: May 16, 2012
 */
package com.kalai;

import java.io.InputStream;
import java.util.Properties;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.displaytag.decorator.TableDecorator;

/**
 * RowIdDisplayTagDecorator is an extension of displaytag library's TableDecorator. When DisplayTag table in jsp makes use of this decorator, generates the row id
 * appending the columns that are configured on the displaytaguniquecolumns.properties with property key columns and values separated by ~ . <br>
 * Examples <br>
 * [displaytaguniquecolumns.properties - columns=column1~column2]<br>
 * [Lets say the column values for column1 and column2 are col1value and col2value respectively, than the row generated for the table looks like &lt;tr
 * id="rowcol1valuecol2value"> ] <br>
 * [if configured columns are not evaluated, it generates row id with index &lt;tr id="row0">, &lt;tr id="row1">]
 *
 * @author (Kalai)
 *
 */
public class RowIdDisplayTagDecorator extends TableDecorator
{
  private static String[] iUniqueColumns = null;
  private static Logger sLogger = Logger.getLogger(RowIdDisplayTagDecorator.class);

  /**
   * Loads the properties file that has the unique columns that makes a row uniqueness on the html table during inspection of the table
   */
  static
  {
    Properties displayUniqueColumnProperties = new Properties();
    try
    {
    
      InputStream propertiesFileStream = RowIdDisplayTagDecorator.class.getClassLoader().getResourceAsStream("displaytaguniquecolumns.properties");
      displayUniqueColumnProperties.load(propertiesFileStream);
      String columnvalues = displayUniqueColumnProperties.getProperty("columns");
      if (StringUtils.isNotBlank(columnvalues))
      {
        iUniqueColumns = columnvalues.split("~");
      }

    }
    catch (Exception exception)
    {
      sLogger.error(exception.toString());
    }

  }

  @Override
  /**
   * Adds the row id the the current row object using the columns configured to identify row uniquely to enable html table inspection based on row id
   * If no columns configured, it generates id indexed from 0 - size of the table rows
   */
  public String addRowId()
  {
    StringBuilder builder = new StringBuilder("row");
    try
    {
      for (String column : iUniqueColumns)
      {
        builder.append(evaluate(column).toString());
      }

    }
    catch (Exception exception)
    {
      sLogger.error(exception.toString());
      builder.append(Integer.toString(getListIndex()));
    }
    return builder.toString();
  }

}