TablePortlet.java :  » Portal » stringbeans-3.5 » com » nabhinc » portlet » table » Java Open Source

Java Open Source » Portal » stringbeans 3.5 
stringbeans 3.5 » com » nabhinc » portlet » table » TablePortlet.java
/* 
 * (C) Copyright 2000 - 2003 Nabh Information Systems, Inc. 
 * 
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License 
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of 
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software 
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 * 
 */
 
package com.nabhinc.portlet.table;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Types;

import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.PortletConfig;
import javax.portlet.PortletException;
import javax.portlet.PortletPreferences;
import javax.portlet.PortletRequestDispatcher;
import javax.portlet.PortletSession;
import javax.portlet.RenderRequest;
import javax.portlet.RenderResponse;

import com.nabhinc.portlet.base.BasePortlet;
import com.nabhinc.util.StringUtil;
import com.nabhinc.util.db.DBUtil;

/**
 * This portlet generates tabular displays typically used
 * for showing emails, alerts, tasks, etc. The table data
 * is obtained directly from a relational database using
 * SQL strings set in the configuration.
 * 
 * @author Padmanabh Dabke
 * (c) 2003 Nabh Information Systems, Inc. All Rights Reserved.
 */
public class TablePortlet extends BasePortlet {

  // Constants that define attribute and parameter names
  public static final String TABLE_INFO_ATTRIB = "com.nabhinc.portlet.table.table_info";
  public static final String RESULT_SET_ATTRIB = "com.nabhinc.portlet.table.result_set";
  public static final String ERROR_MESSAGE_ATTRIB = "com.nabhinc.portlet.table.error_message";
  
  public static final String PAGE_NUMBER_PARAM = "page_number";
  public static final String SORT_TYPE_PARAM = "sort_type";
  public static final String ORDER_BY_PARAM = "order_by";
  public static final String SELECTED_ITEMS_PARAM = "selected_items";
  public static final String DISPLAY_STATE_PARAM = "display_state";
  public static final String ROW_ID_PARAM = "row_id";
  public static final String ROW_NAME_PARAM = "row_name";
  public static final String RESET_PARAM = "reset";
  
  public static final String LIST_SQL_INIT_PARAM = "listSQL";
  public static final String DATA_SOURCE_INIT_PARAM = "dataSource";
  public static final String COUNT_SQL_INIT_PARAM = "countSQL";
  public static final String EMPTY_TABLE_MSG_INIT_PARAM = "emptyTableMessage";
  public static final String INSERT_USER_INIT_PARAM = "insertUser";
  public static final String INSERT_PARAM_NAME_INIT_PARAM = "insertParamName";
  public static final String INSERT_PARAM_VALUE_INIT_PARAM = "insertParamValue";
  public static final String INSERT_PARAM_TYPE_INIT_PARAM = "insertParamType";
  public static final String HEADERS_INIT_PARAM = "headers";
  public static final String ACTION_LABEL_INIT_PARAM = "actionLabel";
  public static final String ACTION_RESTRICT_SQL_INIT_PARAM ="actionRestrictSQL";
  public static final String ACTION_SQL_INIT_PARAM= "actionSQL";
  public static final String ACTION_RESTRICT_MSG_INIT_PARAM = "actionRestrictMessage";
  public static final String ROW_DISPLAY_PAGE_INIT_PARAM = "rowDisplayPage";
  public static final String ROW_DISPLAY_PAGE_EXT_INIT_PARAM ="rowDisplayPageExternal";
  public static final String LINK_ID_PARAM_NAME_INIT_PARAM = "linkIDParamName";
  public static final String LINK_NAME_PARAM_NAME_INIT_PARAM = "linkNameParamName";
  public static final String LINK_COLUMN_INDEX_INIT_PARAM = "linkColumnIndex";
  public static final String LINK_EXCLUDED_VALUES_INIT_PARAM = "linkExcludedValues";
  public static final String LINK_NEW_WINDOW_INIT_PARAM = "linkNewWindow";
  public static final String LINK_WINDOW_HEIGHT_INIT_PARAM = "linkWindowHeight";
  public static final String LINK_WINDOW_WIDTH_INIT_PARAM = "linkWindowWidth";
  public static final String PRIMARY_KEY_INDEX_INIT_PARAM = "primaryKeyIndex";
  public static final String PRIMARY_KEY_TYPE_INIT_PARAM = "primaryKeyType";
  public static final String SORT_COLUMN_INIT_PARAM = "sortColumn";
  public static final String SORT_TYPE_INIT_PARAM = "sortType";
  public static final String COLUMN_NAMES_INIT_PARAM = "columnNames";
  public static final String COLUMN_FORMATS_INIT_PARAM = "columnFormats";
  public static final String COLUMN_TYPES_INIT_PARAM = "columnTypes";
  public static final String ROW_STATE_COLUMN_INDEX_INIT_PARAM = "rowStateColumnIndex";
  public static final String TABLE_DISPLAY_PAGE_INIT_PARAM = "tableDisplayPage";
  public static final String SET_ID_PAGE_INIT_PARAM = "setIDPage";
  public static final String ERROR_PAGE_INIT_PARAM = "errorPage";
  public static final String INCLUDE_NAME_INIT_PARAM = "includeName";
  public static final String IMAGE_FOLDER_INIT_PARAM = "imageFolder";
  public static final String CREATE_LABEL_INIT_PARAM = "createLabel";
  public static final String CREATE_PAGE_INIT_PARAM = "createPage";
  public static final String SEARCH_LABEL_INIT_PARAM ="searchLabel";
  public static final String SEARCH_PAGE_INIT_PARAM = "searchPage";
  
  public static final String ROWS_PER_PAGE_PREF = "rowsPerPage";
  public static final String DEFAULT_ROWS_PER_PAGE = "10";
  
  // Standard values for request parameters
  public static final String DISPLAY_STATE_ROW = "row";
  public static final String DISPLAY_STATE_CREATE = "create";
  public static final String DISPLAY_STATE_SEARCH = "search";
  public static final String DISPLAY_STATE_TABLE = "table";
  
  public static final String SORT_TYPE_ASCENDING = "ascending";
  public static final String SORT_TYPE_DESCENDING = "descending";
  
  private TableInfo tpTableInfo = new TableInfo();

  public static class TableInfo {
    public String dataSource = null;
    public String listSQL = null;
    public String countSQL = null;
    public String actionSQL = null;
    public String actionRestrictSQL = null;
    public String actionRestrictMessage = "Some of the items could not be deleted due to delete restrictions.";
    public String actionLabel = null;
    public int primKeyIndex = -1;
    public int primKeyType = java.sql.Types.VARCHAR;
    public String sortCol = null;
    public boolean sortDir = true;
    public int linkIndex = -1;
    public String[] headers = null;
    public String[] columns = null;
    public int[] columnTypes = null;
    public String[] columnFormats = null;
    public int currentPage = -1;
    public boolean insertUser = false;
    public String emptyMessage = "";
    public boolean showNewWindow = false;
    public int newWindowHeight = -1;
    public int newWindowWidth = -1;
    public int rowStateIndex = -1;
    public boolean includeName = false;
    public String insertParamName = null;
    public String insertParamValue = null;
    public int insertParamType = Types.INTEGER;
    public String linkIDParamName = null;
    public String linkNameParamName = null;
    public String[] linkExcludedValues = null;
    public String setIDJSP = "/portlets/table/setID.jsp";
    public String tableDisplayJSP = "/portlets/table/table.jsp";
    public String errorJSP = "/portlets/table/error.jsp";
    public String rowDisplayJSP = null;
    public String imageFolder = "/images";
    public String createLabel = null;
    public String createJSP = null;
    public String searchLabel = null;
    public String searchJSP = null;
    public boolean isRowDisplayJSPExternal = false;

  }

  public void init(PortletConfig config) throws PortletException {
    super.init(config);

    String temp = null;

    // Get required parameters: listSQL

    temp = config.getInitParameter(LIST_SQL_INIT_PARAM);
    if (temp == null) {
      error("init", "Missing required init parameter: " + LIST_SQL_INIT_PARAM + ".");
      throw new PortletException("Missing list SQL specification");
    } else {
      tpTableInfo.listSQL = temp;
    }

    // Get required parameters: countSQL

    temp = config.getInitParameter(COUNT_SQL_INIT_PARAM);
    if (temp == null) {
      error("init", "Missing required init parameter: countSQL.");
      throw new PortletException("Missing count SQL specification");
    } else {
      tpTableInfo.countSQL = temp;
    }

    temp = config.getInitParameter(EMPTY_TABLE_MSG_INIT_PARAM);
    if (temp != null)
      tpTableInfo.emptyMessage = temp;

    temp = config.getInitParameter(INSERT_USER_INIT_PARAM);
    if ("true".equalsIgnoreCase(temp))
      tpTableInfo.insertUser = true;

    tpTableInfo.insertParamName =
      config.getInitParameter(INSERT_PARAM_NAME_INIT_PARAM);
    tpTableInfo.insertParamValue =
      config.getInitParameter(INSERT_PARAM_VALUE_INIT_PARAM);
    tpTableInfo.insertParamType =
      getSQLType(config.getInitParameter(INSERT_PARAM_TYPE_INIT_PARAM));

    // Get table headers
    temp = config.getInitParameter(HEADERS_INIT_PARAM);
    if (temp != null) {
      tpTableInfo.headers = StringUtil.split(temp, ",");
    } else {
      error("init", "Missing table headers");
      throw new PortletException("Missing required init parameter: " + HEADERS_INIT_PARAM + ".");
    }

    // Set datasource if specified
    temp = config.getInitParameter(DATA_SOURCE_INIT_PARAM);
    if (temp != null) {
      tpTableInfo.dataSource = temp;
    } else {
      error("init", "Missing SQL datasource name.");
      throw new PortletException("Missing required init parameter: " + DATA_SOURCE_INIT_PARAM + ".");
    }

    // Set action related parameters
    tpTableInfo.actionLabel = config.getInitParameter(ACTION_LABEL_INIT_PARAM);
    tpTableInfo.actionSQL = config.getInitParameter(ACTION_SQL_INIT_PARAM);
    tpTableInfo.actionRestrictSQL = config.getInitParameter(ACTION_RESTRICT_SQL_INIT_PARAM);
    String tempActionMsg = config.getInitParameter(ACTION_RESTRICT_MSG_INIT_PARAM);
    if (tempActionMsg != null) tpTableInfo.actionRestrictMessage = tempActionMsg;
    
    // Set table link related parameters
    tpTableInfo.rowDisplayJSP = config.getInitParameter(ROW_DISPLAY_PAGE_INIT_PARAM);
    if ("true".equalsIgnoreCase(config.getInitParameter(ROW_DISPLAY_PAGE_EXT_INIT_PARAM))) {
      tpTableInfo.isRowDisplayJSPExternal = true;      
    }
    tpTableInfo.linkIDParamName =
      config.getInitParameter(LINK_ID_PARAM_NAME_INIT_PARAM);
    if (tpTableInfo.linkIDParamName == null ||
      "".equals(tpTableInfo.linkIDParamName))
      tpTableInfo.linkIDParamName = TablePortlet.ROW_ID_PARAM;
    
    tpTableInfo.linkNameParamName =
      config.getInitParameter(LINK_NAME_PARAM_NAME_INIT_PARAM);
    if (tpTableInfo.linkNameParamName == null ||
      "".equals(tpTableInfo.linkNameParamName))
      tpTableInfo.linkNameParamName = TablePortlet.ROW_NAME_PARAM;
    
    temp =config.getInitParameter(LINK_EXCLUDED_VALUES_INIT_PARAM);
    if (temp != null)
      tpTableInfo.linkExcludedValues = StringUtil.split(temp, ","); 
    
    temp = config.getInitParameter(LINK_COLUMN_INDEX_INIT_PARAM);
    if (temp == null) {
      tpTableInfo.linkIndex = -1;
    } else {
      tpTableInfo.linkIndex = Integer.parseInt(temp);
    }

    temp = config.getInitParameter(LINK_NEW_WINDOW_INIT_PARAM);
    if (temp != null
      && (!(temp.equals("")))
      && temp.equalsIgnoreCase("true")) {
      tpTableInfo.showNewWindow = true;
      temp = config.getInitParameter(LINK_WINDOW_HEIGHT_INIT_PARAM);
      if (temp != null && (!"".equals(temp))) {
        tpTableInfo.newWindowHeight = Integer.parseInt(temp);
      }
      temp = config.getInitParameter(LINK_WINDOW_WIDTH_INIT_PARAM);
      if (temp != null && (!"".equals(temp))) {
        tpTableInfo.newWindowWidth = Integer.parseInt(temp);
      }
    }

    // Get identifier column if specified
    temp = config.getInitParameter(PRIMARY_KEY_INDEX_INIT_PARAM);
    if (temp != null) {
      tpTableInfo.primKeyIndex = Integer.parseInt(temp);
    }
    temp = config.getInitParameter(PRIMARY_KEY_TYPE_INIT_PARAM);
    if (temp != null) {
      tpTableInfo.primKeyType = getSQLType(temp);
    }

    // Try setting up sorting related stuff
    tpTableInfo.sortCol = config.getInitParameter(SORT_COLUMN_INIT_PARAM);
    temp = config.getInitParameter(SORT_TYPE_INIT_PARAM);
    if (temp != null && SORT_TYPE_DESCENDING.equals(temp.toLowerCase()))
      tpTableInfo.sortDir = false;

    temp = config.getInitParameter(COLUMN_NAMES_INIT_PARAM);
    if (temp == null) {
      tpTableInfo.columns = new String[tpTableInfo.headers.length];
      for (int i = 0; i < tpTableInfo.columns.length; i++) {
        tpTableInfo.columns[i] = null;
      }
    } else {
      tpTableInfo.columns = StringUtil.split(temp, ",");
      if (tpTableInfo.columns.length < tpTableInfo.headers.length) {
        error(
          "init",
          "Number of columns must be greater than or equal to number of headers");
        throw new PortletException("Number of columns != number of headers");
      }
      for (int i = 0; i < tpTableInfo.columns.length; i++) {
        if ("null".equals(tpTableInfo.columns[i])
          || "".equals(tpTableInfo.columns[i])) {
          tpTableInfo.columns[i] = null;
        }
      }
    }

    temp = config.getInitParameter(COLUMN_FORMATS_INIT_PARAM);
    if (temp == null) {
      tpTableInfo.columnFormats = new String[tpTableInfo.headers.length];
      for (int i = 0; i < tpTableInfo.columnFormats.length; i++) {
        tpTableInfo.columnFormats[i] = null;
      }
    } else {
      tpTableInfo.columnFormats = StringUtil.split(temp, ",");
      if (tpTableInfo.columnFormats.length
        != tpTableInfo.headers.length) {
        error(
          "init",
          "Number of column formats is not equal to number of headers");
        throw new PortletException("Number of column formats != number of headers");
      }
      for (int i = 0; i < tpTableInfo.columnFormats.length; i++) {
        if ("null".equals(tpTableInfo.columnFormats[i])
          || "".equals(tpTableInfo.columnFormats[i])) {
          tpTableInfo.columnFormats[i] = null;
        }
      }
    }

    temp = config.getInitParameter(COLUMN_TYPES_INIT_PARAM);
    if (temp == null) {
      tpTableInfo.columnTypes = new int[tpTableInfo.columns.length];
      for (int i = 0; i < tpTableInfo.columnFormats.length; i++) {
        tpTableInfo.columnTypes[i] = java.sql.Types.VARCHAR;
      }
    } else {
      String[] cTypes = StringUtil.split(temp, ",");
      if (cTypes.length != tpTableInfo.columns.length) {
        error(
          "init",
          "Number of column types is not equal to number of column names");
        throw new PortletException("Number of column types != number of column names");
      }
      tpTableInfo.columnTypes = new int[cTypes.length];
      for (int i = 0; i < cTypes.length; i++) {
        tpTableInfo.columnTypes[i] = getSQLType(cTypes[i]);
      }
    }

    temp = config.getInitParameter(ROW_STATE_COLUMN_INDEX_INIT_PARAM);
    if (temp != null) {
      tpTableInfo.rowStateIndex = Integer.parseInt(temp);
    }

    temp = config.getInitParameter(TABLE_DISPLAY_PAGE_INIT_PARAM);
    if (temp != null) {
      tpTableInfo.tableDisplayJSP = temp;
    }

    temp = config.getInitParameter(SET_ID_PAGE_INIT_PARAM);
    if (temp != null) {
      tpTableInfo.setIDJSP = temp;
    }

    temp = config.getInitParameter(ERROR_PAGE_INIT_PARAM);
    if (temp != null) {
      tpTableInfo.errorJSP = temp;
    }

    if (config.getInitParameter(INCLUDE_NAME_INIT_PARAM) != null) {
      tpTableInfo.includeName = true;
    }

    temp = config.getInitParameter(IMAGE_FOLDER_INIT_PARAM);
    if (temp != null) {
      tpTableInfo.imageFolder = temp;
    }
    
    tpTableInfo.createLabel = config.getInitParameter(CREATE_LABEL_INIT_PARAM);
    tpTableInfo.createJSP = config.getInitParameter(CREATE_PAGE_INIT_PARAM);
    tpTableInfo.searchLabel = config.getInitParameter(SEARCH_LABEL_INIT_PARAM);
    tpTableInfo.searchJSP = config.getInitParameter(SEARCH_PAGE_INIT_PARAM);

  }

  private int getSQLType(String str) {
    if (str == null)
      return java.sql.Types.VARCHAR;
    str = str.toUpperCase();
    if (str.equals("VARCHAR"))
      return java.sql.Types.VARCHAR;
    else if (str.equals("INTEGER"))
      return java.sql.Types.INTEGER;
    else if (str.equals("DECIMAL"))
      return java.sql.Types.DECIMAL;
    else if (str.equals("NUMERIC"))
      return java.sql.Types.NUMERIC;
    else if (str.equals("BOOLEAN"))
      return java.sql.Types.BOOLEAN;
    else if (str.equals("SMALLINT"))
      return java.sql.Types.SMALLINT;
    else if (str.equals("DATE"))
      return java.sql.Types.DATE;
    else if (str.equals("TIME"))
      return java.sql.Types.TIME;
    else if (str.equals("TIMESTAMP"))
      return java.sql.Types.TIMESTAMP;
    else if (str.equals("FLOAT"))
      return java.sql.Types.FLOAT;
    else if (str.equals("DOUBLE"))
      return java.sql.Types.DOUBLE;
    else if (str.equals("ARRAY"))
      return java.sql.Types.ARRAY;
    else if (str.equals("BIGINT"))
      return java.sql.Types.BIGINT;
    else if (str.equals("BINARY"))
      return java.sql.Types.BINARY;
    else if (str.equals("BIT"))
      return java.sql.Types.BIT;
    else if (str.equals("BLOB"))
      return java.sql.Types.BLOB;
    else if (str.equals("CHAR"))
      return java.sql.Types.CHAR;
    else if (str.equals("CLOB"))
      return java.sql.Types.CLOB;
    else if (str.equals("LONGVARBINARY"))
      return java.sql.Types.LONGVARBINARY;
    else if (str.equals("LONGVARCHAR"))
      return java.sql.Types.LONGVARCHAR;
    else if (str.equals("JAVA_OBJECT"))
      return java.sql.Types.JAVA_OBJECT;
    else
      return java.sql.Types.VARCHAR;
  }

  private String getSQLTypeString(int code) {

    switch (code) {
      case Types.VARCHAR :
        return "VARCHAR";
      case Types.INTEGER :
        return "INTEGER";
      case Types.DECIMAL :
        return "DECIMAL";
      case Types.NUMERIC :
        return "NUMERIC";
      case Types.BOOLEAN :
        return "BOOLEAN";
      case Types.SMALLINT :
        return "SMALLINT";
      case Types.DATE :
        return "DATE";
      case Types.TIME :
        return "TIME";
      case Types.TIMESTAMP :
        return "TIMESTAMP";
      case Types.FLOAT :
        return "FLOAT";
      case Types.DOUBLE :
        return "DOUBLE";
      case Types.ARRAY :
        return "ARRAY";
      case Types.BIGINT :
        return "BIGINT";
      case Types.BINARY :
        return "BINARY";
      case Types.BIT :
        return "BIT";
      case Types.BLOB :
        return "BLOB";
      case Types.CHAR :
        return "CHAR";
      case Types.CLOB :
        return "CLOB";
      case Types.LONGVARBINARY :
        return "LONGVARBINARY";
      case Types.LONGVARCHAR :
        return "LONGVARCHAR";
      case Types.JAVA_OBJECT :
        return "JAVA_OBJECT";
      default :
        return "VARCHAR";
    }
  }

  public void processAction(
    ActionRequest request,
    ActionResponse actionResponse)
    throws PortletException, java.io.IOException {
      
    Connection conn = null;
    ResultSet countResults = null;
    ResultSet actionPrecondResults = null;
    PreparedStatement delSt = null;
    PreparedStatement countSt = null;
    PreparedStatement actionPrecondSt = null;
    boolean autoCommit = true;
    

    // Check if processAction is being called to set rows per page
    String action = request.getParameter("action");
    if ("edit_prefs".equals(action)) {
        int maxRows = -1;
        String maxRowsStr = request.getParameter("maxRows");
        boolean validRows = false;
        try {
            maxRows = Integer.parseInt(maxRowsStr);
            if (maxRows > 0) {
                validRows = true;
            }
        } catch (Exception ex) {
            // Ignore
        }
        
        if (validRows) {
            try {
                PortletPreferences pref = request.getPreferences();
                pref.setValue(ROWS_PER_PAGE_PREF, maxRowsStr);
                pref.store();
                actionResponse.setRenderParameter("success", "true");
            } catch (Exception ex) {
                actionResponse.setRenderParameter("error", "Failed to save preferences: " + ex.toString());
            }

        } else {
            actionResponse.setRenderParameter("error", "Invalid rows per page value.");
        }
      
    }

    
    if (tpTableInfo.insertParamName != null) {
      // Check if the request has a parameter by that name
      tpTableInfo.insertParamValue = request.getParameter(tpTableInfo.insertParamName);
      if (tpTableInfo.insertParamValue == null) {
        // Check if the request has that attribute
        tpTableInfo.insertParamValue = request.getPreferences().getValue(tpTableInfo.insertParamName, null);
      }
    }

    try {
      // Get database connection
      conn = DBUtil.getConnection(tpTableInfo.dataSource);
      autoCommit = conn.getAutoCommit();
      conn.setAutoCommit(false);
      
      // Perform database action for marked entries

      String[] markedEntries = request.getParameterValues(SELECTED_ITEMS_PARAM);
      if (markedEntries != null) {
        delSt =
          conn.prepareStatement(tpTableInfo.actionSQL);
        if (tpTableInfo.actionRestrictSQL != null) {
          actionPrecondSt = conn.prepareStatement(tpTableInfo.actionRestrictSQL);
        }
          
        int markPos = 1;
        if (tpTableInfo.insertUser) {
          delSt.setString(markPos, request.getRemoteUser());
          markPos++;
        }

        
        switch (tpTableInfo.primKeyType) {
          case java.sql.Types.INTEGER :
            for (int i = 0; i < markedEntries.length; i++) {
              if (actionPrecondSt != null) {
                actionPrecondSt.setInt(1, Integer.parseInt(markedEntries[i]));
                actionPrecondResults = actionPrecondSt.executeQuery();
                if (actionPrecondResults.next()) {
                  actionPrecondResults.close();
                  request.setAttribute(ERROR_MESSAGE_ATTRIB,
                  tpTableInfo.actionRestrictMessage);
                  continue;
                } else {
                  actionPrecondResults.close();
                }
              }
              delSt.setInt(
                markPos,
                Integer.parseInt(markedEntries[i]));
              delSt.execute();
            }
            break;
          case java.sql.Types.VARCHAR :
          default :
            for (int i = 0; i < markedEntries.length; i++) {
              if (actionPrecondSt != null) {
                actionPrecondSt.setString(1, markedEntries[i]);
                actionPrecondResults = actionPrecondSt.executeQuery();
                if (actionPrecondResults.next()) {
                  actionPrecondResults.close();
                  request.setAttribute(ERROR_MESSAGE_ATTRIB,
                  tpTableInfo.actionRestrictMessage);
                  continue;
                } else {
                  actionPrecondResults.close();
                }
              }
              delSt.setString(markPos, markedEntries[i]);
              delSt.execute();
            }
            break;
        }
      }
      
      countSt = conn.prepareStatement(tpTableInfo.countSQL);
      int markPos = 1;
      if (tpTableInfo.insertUser) {
        countSt.setString(markPos,request.getRemoteUser());
        markPos++;
      }
      if (tpTableInfo.insertParamName != null) {
        switch (tpTableInfo.insertParamType) {
          case java.sql.Types.INTEGER:
            countSt.setInt(markPos, Integer.parseInt(tpTableInfo.insertParamValue));
            break;
          default:
            countSt.setString(markPos, tpTableInfo.insertParamValue);
            break;
          }
          markPos++;
      }
      
      
      countResults = countSt.executeQuery();
      countResults.next();
      int rowCount = countResults.getInt(1);
      int rowsPerPage = Integer.parseInt(request.getPreferences().getValue(ROWS_PER_PAGE_PREF, DEFAULT_ROWS_PER_PAGE));
      int newNumPages = rowCount / rowsPerPage;
      if (rowCount % rowsPerPage == 0) newNumPages--;
      String pageNumStr = (String) request.getPortletSession().getAttribute(PAGE_NUMBER_PARAM);
      if (pageNumStr != null) {
        int pageNum = Integer.parseInt(pageNumStr);
        if (newNumPages < pageNum) {
          request.getPortletSession().setAttribute(PAGE_NUMBER_PARAM, Integer.toString(newNumPages));
        }
      }
      
      conn.commit();
    
    } catch (Exception ex) {
      try { conn.rollback(); } catch (Exception exx) {}
      throw new PortletException("Failed to execute table action.", ex);
    } finally {
      try { conn.setAutoCommit(autoCommit); } catch (Exception ex) {}
      DBUtil.close(countResults);
      DBUtil.close(actionPrecondResults);
      DBUtil.close(delSt);
      DBUtil.close(countSt);
      DBUtil.close(actionPrecondSt);
      DBUtil.close(conn);
    }
  }

  public void doView(RenderRequest request, RenderResponse response)
    throws PortletException, IOException {

    if (DISPLAY_STATE_ROW.equals(request.getParameter(DISPLAY_STATE_PARAM))) {
      try {
        PortletRequestDispatcher dispatcher =
          bpContext.getRequestDispatcher(tpTableInfo.rowDisplayJSP);
        dispatcher.include(request, response);
        return;
      } catch (IOException e) {
        throw new PortletException("Failed to include content from row display JSP.", e);
      } 

    } else if (DISPLAY_STATE_CREATE.equals(request.getParameter(DISPLAY_STATE_PARAM))) {
      try {
        PortletRequestDispatcher dispatcher =
          bpContext.getRequestDispatcher(tpTableInfo.createJSP);
        dispatcher.include(request, response);
        return;
      } catch (IOException e) {
        throw new PortletException("Failed to include content from create JSP.", e);
      }
    } else if (DISPLAY_STATE_SEARCH.equals(request.getParameter(DISPLAY_STATE_PARAM))) {
      try {
        PortletRequestDispatcher dispatcher =
          bpContext.getRequestDispatcher(tpTableInfo.searchJSP);
        dispatcher.include(request, response);
        return;
      } catch (IOException e) {
        throw new PortletException("Failed to include content from search JSP.", e);
      }
    }
    
    // Store table display parameters in portlet session.
    PortletSession pSession = request.getPortletSession();
    String sortType = request.getParameter(SORT_TYPE_PARAM);
    if (sortType != null) pSession.setAttribute(SORT_TYPE_PARAM, sortType);
    String orderBy = request.getParameter(ORDER_BY_PARAM);
    if (orderBy != null) pSession.setAttribute(ORDER_BY_PARAM, orderBy);
    String pageNumber = request.getParameter(PAGE_NUMBER_PARAM);
    if (pageNumber != null) pSession.setAttribute(PAGE_NUMBER_PARAM, pageNumber);
    
    java.sql.Connection conn = null;
    boolean insertParam = false;
    PortletPreferences pref = request.getPreferences();

    response.setContentType(request.getResponseContentType());
    
    String insertParamValue = null;
    int insertParamType = tpTableInfo.insertParamType;
    if (tpTableInfo.insertParamName != null) {
      insertParam = true;
      // Check if the request has a parameter by that name
      insertParamValue = request.getParameter(tpTableInfo.insertParamName);
      if (insertParamValue == null) {
        // Check if the request has that attribute
        insertParamValue = pref.getValue(tpTableInfo.insertParamName, null);
        if (insertParamValue == null) {
          insertParamValue = tpTableInfo.insertParamValue;
        }
      }
    }

    if (insertParam && insertParamValue == null) {
      try {
        PortletRequestDispatcher dispatcher =
          bpContext.getRequestDispatcher(tpTableInfo.setIDJSP);
        dispatcher.include(request, response);
      } catch (IOException e) {
        throw new PortletException("Failed to include content from display JSP.", e);
      }
      return;
    }

    orderBy = (String) pSession.getAttribute(ORDER_BY_PARAM);
    
    //String idParamName = tpTableInfo.linkIDParamName == null ? "id" : tpTableInfo.linkIDParamName;

    if (orderBy == null) {
      orderBy = tpTableInfo.sortCol;
    }
    boolean isAscending = true;
    
    sortType = (String) pSession.getAttribute(SORT_TYPE_PARAM);
    if (sortType == null) {
      isAscending = tpTableInfo.sortDir;    
    } else if (SORT_TYPE_DESCENDING.equals(sortType)) {
      isAscending = false;
    } 
    
    // String sortImg = "<IMG valign=\"middle\" src=\"" + tpTableInfo.imageFolder + "/" + sortType + ".gif\">";
    int pageNum = 0;
  
    String pageNumStr = request.getParameter(PAGE_NUMBER_PARAM);
    if (pageNumStr != null) {
      pageNum = Integer.parseInt(pageNumStr);
    }
    // int rowsPerPage = Integer.parseInt(request.getPreferences().getValue(ROWS_PER_PAGE_PREF, "10"));
    // int startIndex = pageNum * rowsPerPage;
    // int endIndex = startIndex + rowsPerPage - 1;
    String listSQL = tpTableInfo.listSQL;
    java.sql.ResultSet queryResults = null;
    
    try {
      // Get results to be displayed
      conn = DBUtil.getConnection(tpTableInfo.dataSource);
      if (orderBy != null) {
        listSQL = listSQL + " ORDER BY " + orderBy;
        // default order is ascending
        if (!isAscending) listSQL = listSQL + " DESC";
      }
      java.sql.PreparedStatement st = conn.prepareStatement(listSQL);
      int markPos = 1;
      if (tpTableInfo.insertUser) {
        st.setString(markPos,request.getRemoteUser());
        markPos++;
      }
      if (insertParam && listSQL.indexOf("?") > -1) {
          switch (insertParamType) {
             case java.sql.Types.INTEGER:
            st.setInt(markPos, Integer.parseInt(insertParamValue));
            break;
             default:
            st.setString(markPos, insertParamValue);
            break;
          }
          markPos++;
      }
  
      queryResults = st.executeQuery();
    } catch (Exception ex) {
      try {
        conn.close();
      } catch (Exception ex1) {}
      throw new PortletException("Failed to obtain table data from the database.",
      ex);
    }

    try {
      request.setAttribute(RESULT_SET_ATTRIB, queryResults);
      request.setAttribute(TABLE_INFO_ATTRIB, tpTableInfo);
      PortletRequestDispatcher dispatcher =
        bpContext.getRequestDispatcher(tpTableInfo.tableDisplayJSP);
      dispatcher.include(request, response);
    } catch (IOException e) {
      throw new PortletException("Failed to include content from display JSP.", e);
    } finally {
      try {
        conn.close();
      } catch (Exception ex1) {}
      
    }

  }

}
java2s.com  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.