<%@page contentType="text/html;charset=UTF-8" pageEncoding="ISO-8859-1" session="true"%>
<%@page errorPage="Exception.jsp"
%><%@page import="com.fujitsu.iflow.dbadapter.dataobjects.SearchStruct"
%><%@page import="com.fujitsu.iflow.dbadapter.dataobjects.SearchUdaStruct"
%><%@page import="com.fujitsu.iflow.model.bpm.BPMSession"
%><%@page import="com.fujitsu.iflow.model.bpmcore.BPMSessionImpl"
%><%@page import="com.fujitsu.iflow.model.util.QuickForm"
%><%@page import="com.fujitsu.iflow.model.util.URLEncoder"
%><%@page import="com.fujitsu.iflow.model.workflow.DataItem"
%><%@page import="com.fujitsu.iflow.model.workflow.DataItemRef"
%><%@page import="com.fujitsu.iflow.model.workflow.Filter"
%><%@page import="com.fujitsu.iflow.model.workflow.WFObjectFactory"
%><%@page import="com.fujitsu.iflow.model.workflow.WFObjectList"
%><%@page import="com.fujitsu.iflow.model.workflow.ProcessInstance"
%><%@page import="com.fujitsu.iflow.server.dataobjects.FilterEnum"
%><%@page import="com.fujitsu.iflow.server.dataobjects.ProcessInstanceStatesEnum"
%><%@page import="java.io.Writer"
%><%@page import="java.text.SimpleDateFormat"
%><%@page import="java.util.Date"
%><%@page import="java.util.Enumeration"
%><%@page import="java.util.StringTokenizer"
%><%@page import="java.util.Vector"
%><%@page import="javax.servlet.http.Cookie"
%><%@page import="java.text.DateFormat"
%><%
    request.setCharacterEncoding("UTF-8");request.getParameterNames(); //Need dummy call for WL9.1
    bps = (BPMSession) session.getAttribute("BPMSession");
    if (bps == null) {
        %><jsp:include page="PasswordPanel.jsp" flush="true"/><%
        return;
    }
    transportType = (String) session.getAttribute("TransportType");
%>
<html>
<head>
<title>Interstage Business Process Manager | Process Instance List</title>
<link href="styles/iflow.css" rel="stylesheet" type="text/css">
<script language="javascript" src="styles/clockscripts.js"></script>
<script>
function setSelection(piForm, selPage)
{
    piForm.pgNum.value = selPage;
    piForm.submit();
}
function sort(field, order)
{
    document.piForm.sort.value = field;
    document.piForm.asc.value = order;
    document.piForm.pgNum.value = 1;
    document.piForm.submit();
}
function trimString (str) {
  str = this != window? this : str;
  return str.replace(/^\s+/g, '').replace(/\s+$/g, '');
}
function save()
{
    document.saveForm.srchnm.value = trimString(document.saveForm.srchnm.value);
    if (document.saveForm.srchnm.value == null || document.saveForm.srchnm.value == "" ) {
        alert("Please specify a search name");
        document.saveForm.srchnm.focus();
        return;
    }
    if (document.saveForm.srchnm.value.indexOf(",") >= 0 ) {
        alert("Illegal character: ',' not allowed in search name");
        document.saveForm.srchnm.focus();
        return;
    }
    var savedSearches = document.saveForm.searchesStr.value.split(",");
    for (i=0; i < savedSearches.length; i++) {
        if (savedSearches[i].toLowerCase() == document.saveForm.srchnm.value.toLowerCase()) {
            alert("Could not save this search, since a search with the same name exists already");
            document.saveForm.srchnm.focus();
            return;
        }
    }
    document.piForm.srchnm.value = document.saveForm.srchnm.value;
    document.cookie = "SaveCookie=true";
    document.piForm.submit();
}
function bodyLoaded()
{
    // remove SaveCookie
    var date = new Date();
    date.setTime(date.getTime()-(24*60*60*1000));
    var expires = "; expires="+date.toGMTString();
    document.cookie = "SaveCookie=false"+expires;
}
</script>
</head>

<body class="bodyClass" onload="bodyLoaded()">
<center>
<%!
    BPMSession bps = null;
    String transportType = null;
        String srchnm = null;
    int filterId = Filter.MyActiveProcesses;
    int pageNumber = 1;
    int pageSize = 20;
    ProcessInstance[] tasks = new ProcessInstance[0];
    String tableTitle = "My Active Process Instances";
    String sortField = "Id";
    String sortAsc = "true";
    String filterName = "";
    String planName = "";
    String piName = "";
    String piopStr = "";
    String assigneeName = "";
    String asnopStr = "";
    String udaFilters = "";
    SearchUdaStruct[] searchUdaStruct = null;
    String displayUdasStr = "";
    String displayUdas[] = null;
    String displayFieldsStr = "";
    String displayFields[] = null;
    final String defaultFields = "Id,Process Instance Name,Process Definition,Date Started,Status,Owner(s)";
    String hFrmCrt = "";

    String hToCrt = "";
    boolean trace=false;
%>
<%

    session.removeAttribute("Forms");
    session.removeAttribute("completedTasks");

    // SETUP GLOBALS
    // No search specified: Entry from "Process Instances" tab or from ProcessHeader menu selection
    String pageNumberStr = request.getParameter("pgNum");
    if (pageNumberStr == null || pageNumberStr.trim().length() == 0) {
        // no pageNumber : Entry from "Process Instances" tab. Look for default search.
        srchnm = getDefaultSearch();
        if(srchnm == null){
            // Default search not found. Use default values.
            setDefaultValues();
        }
    }
    else {
        readParams(request);
    }

    cleanupGlobals();

    // Save search if the cookie is set
    Cookie cookies[] = request.getCookies();
    String doSave="false";
    if (cookies != null) {
        for (int i = 0; i < cookies.length; i++) {
           if (cookies[i].getName().equals("SaveCookie")) {
               doSave = cookies[i].getValue();
           }
        }
    }
    if (doSave.equals("true")) {
        SearchStruct s = new SearchStruct();
        s.userId = bps.getUserName();
        s.queryName = srchnm;
        s.queryType = SearchStruct.TYPE_PI;
        s.preDefFilter = Integer.toString(filterId);
        s.pdNames = planName;
        s.piNames = piName;
        s.piOp = piopStr;
        s.assignees = assigneeName;
        s.asnOp = asnopStr;
        s.sortBy = sortField;
        s.sortOrder = sortAsc;
        s.pageSize = pageSize;
        s.udaFilter = searchUdaStruct;
        s.disUdas = displayUdasStr;
        s.disColums = displayFieldsStr;
        s.createdStartDate = hFrmCrt;
        s.createdEndDate = hToCrt;
        bps.createSearch(s);
    }
    // Now get the process instances
    tasks = getProcessInstances(filterId, pageNumber, pageSize, sortField, sortAsc, trace, out);

    // Now display
    String[] bcolor = {"evenrow","oddrow"};
    int nextColor = 0;
    String rowColor = bcolor[nextColor];
    session.setAttribute("TabIndex","1");

%>
  <jsp:include page="Header.jsp" flush="true"/><br>
  <jsp:include page="ProcessListHeader.jsp" flush="true"/>


  <table width="100%" height="100%" border="0" cellpadding="0" cellspacing="0">
    <td valign="top">
      <table width="90%" border="0" cellpadding="2" cellspacing="2" align="center" class="tableclass">
        <tr>
          <form name="piForm" method="post" action="ProcessList.jsp">
            <input type="hidden" name="pgNum" value="<%= pageNumber %>">
            <input type="hidden" name="filterId" value="<%= filterId %>">
            <input type="hidden" name="sort" value="<%= sortField %>">
            <input type="hidden" name="asc" value="<%= sortAsc %>">
            <input type="hidden" name="pd" value="<%= planName %>">
            <input type="hidden" name="pin" value="<%= piName %>">
            <input type="hidden" name="piop" value="<%= piopStr %>">
            <input type="hidden" name="asn" value="<%= assigneeName %>">
            <input type="hidden" name="asnop" value="<%= asnopStr %>">
            <input type="hidden" name="pg" value="<%= pageSize %>">
            <input type="hidden" name="srchnm" value="<%= srchnm %>">
            <input type="hidden" name="dspUda" value="<%= displayUdasStr %>">
            <input type="hidden" name="dspFields" value="<%= displayFieldsStr %>">
            <input type="hidden" name="filterUdas" value="<%=udaFilters%>">
            <input type="hidden" name="hFrmCrt" value="<%=hFrmCrt%>">
            <input type="hidden" name="hToCrt" value="<%=hToCrt%>">

            <td align="left">
<%
    String btnOption = "";
    if (pageNumber > 1) {
        btnOption = "onClick=\"setSelection(this.form, " + (pageNumber-1) +")\"";
    }
    else {
        btnOption = "disabled";
    }
%>
              <input value="Prev Page" <%= btnOption %> type="button" class="core-button">
              &nbsp;&nbsp;
<%
    if (tasks.length != pageSize)
        btnOption = "disabled";
    else
        btnOption = "onClick=\"setSelection(this.form, " + (pageNumber+1) +")\"";
%>
                <input value="Next Page" <%= btnOption %> type="button" class="core-button">
                &nbsp;&nbsp;
              </td>
            </form>
            <td align="right">
              <form name="main" method="GET" action="AdvSearch.jsp">
                <input type="hidden" name="qtype" value="PI"/>
                <input value="Advanced Search..." type="submit" class="core-button">
              </form>
            </td>
        </tr>
        <tr>
          <td colspan="2">
            <TABLE bgcolor="#CCCCCC" border="0" cellpadding="4" cellspacing="1" class="tableClass" width="100%" align="center">
              <tr align="center" class="headrow">
                <td bgcolor="#EEEEEE" style="filter:progid:DXImageTransform.Microsoft.Gradient(startColorStr='#FFFFFF', endColorStr='#6699CC', gradientType='1')"><font color="#000000" size="2"><%=tableTitle%></font></td>
              </tr>
            </table>
            <TABLE bgcolor="#CCCCCC" border="0" cellpadding="4" cellspacing="1" class="tableClass" width="100%" align="center">
              <tr align="center" class="headrow" bgcolor="#0066CC">
<%
    for (int i = 0; i < displayFields.length; i++)
    {
        String fieldName = displayFields[i].trim();
%>
                <th>
                    <TABLE bgcolor="#0066CC" border="0" cellpadding="0" cellspacing="0">
                        <tr align="center" class="headrow" bgcolor="#0066CC">
                            <td rowspan="2"><%=fieldName%>&nbsp;</td>
<%
                            if (!fieldName.equals("Owner(s)")) {
%>
                            <td><input type="image" src="images/asc.gif" onclick="sort('<%=fieldName%>', true)"></td>
                        </tr>
                        <tr>
                            <td><input type="image" src="images/desc.gif" onclick="sort('<%=fieldName%>', false)"></td>
<%
                            }
                            else {
%>
                        </tr>
                        <tr>
<%
                            }
%>
                        </tr>
                    </TABLE>
                </th>
<%
    }

    for (int i = 0; i < displayUdas.length; i++)
    {
        int pos = displayUdas[i].indexOf("(");
        String udaName = displayUdas[i].substring(0, pos).trim();
        String udaType = displayUdas[i].substring(pos+1, displayUdas[i].indexOf(")")).trim();
%>
                <th>
                    <TABLE bgcolor="#0066CC" border="0" cellpadding="0" cellspacing="0">
                        <tr align="center" class="headrow" bgcolor="#0066CC">
                            <td><%=udaName%>&nbsp;</td>
                            <td><input type="image" src="images/asc.gif" onclick="sort('<%=displayUdas[i]%>', true)"></td>
                        </tr>
                        <tr align="center" class="headrowsmall" bgcolor="#0066CC">
                            <td>&nbsp;(<%=udaType%>)&nbsp;</td>
                            <td><input type="image" src="images/desc.gif" onclick="sort('<%=displayUdas[i]%>', false)"></td>
                        </tr>
                    </TABLE>
                </th>
<%
    }
%>
              </tr>
              <%
   for (int i = 0; i < tasks.length; i++)
   {
        rowColor = bcolor[nextColor];
        nextColor = (nextColor + 1)%2;

        ProcessInstance pi = tasks[i];
        DataItem[] data = pi.getDataItems();
        Vector worklistDataVect = new Vector();
         for (int m = 0; m < data.length; m++) {
              if (data[m].isWorkListUDA()) {
                  worklistDataVect.addElement(data[m]);
              }
        }
        DataItem[] dataItems = new DataItem[worklistDataVect.size()];
        worklistDataVect.copyInto(dataItems);

        String processName = pi.getName();
        String piId = String.valueOf(pi.getId());
        int piState = pi.getState();
        String piStateStr = null;
        if (piState == -1)
            piStateStr = "Completed";
        else
            piStateStr = ProcessInstanceStatesEnum.from_int(piState).toString();

        String taskURL = "ProcessInstance.jsp?piId="+String.valueOf(pi.getId());
        taskURL = response.encodeURL(taskURL);
        String[] piOwners = pi.getOwners();
%>
              <tr class="<%=rowColor%>">
<%
       for (int k = 0; k < displayFields.length; k++)
       {
            String displayField = displayFields[k];
            debug(" K = : " + k + " displayFields : " + displayField);

            if (displayField.equals("Id")) {
%>
                <td> <a href="<% QuickForm.writeHtml(out, taskURL );%>">
                  <% QuickForm.writeHtmlWithNBSPs(out, piId); %>
                  </a>
                </td>
<%
            }
            if (displayField.equals("Process Instance Name")) {
%>
                <td> <a href="<% QuickForm.writeHtml(out, taskURL );%>">
                  <% QuickForm.writeHtmlWithNBSPs(out, processName); %>
                  </a>
                </td>
<%
            }
            if (displayField.equals("Process Definition")) {
%>
                <td>
                  <% QuickForm.writeHtmlWithNBSPs(out, pi.getPlanName()); %>
                </td>
<%
            }
            if (displayField.equals("Date Started")) {
%>
                <td nowrap> <script> showDate('<%=pi.getCreationTime()%>'); </script> </td>
<%
            }
            if (displayField.equals("Status")) {
%>
                <td> <%=piStateStr%> </td>
<%
            }
            if (displayField.equals("Owner(s)")) {
%>
              <td width="20%" >
                <% for(int j=0; j<piOwners.length; j++){%>
                <% QuickForm.writeHtml(out, piOwners[j]); %>
                <% if(j!=piOwners.length-1) out.print(","); %>

                <%}%>
              </td>
<%
            }
        }
        for (int k = 0; k < displayUdas.length; k++)
        {
            int pos = displayUdas[k].indexOf("(");
            String udaName = displayUdas[k].substring(0, pos).trim();
            String udaType = displayUdas[k].substring(pos+1, displayUdas[k].indexOf(")")).trim();

            boolean foundUda = false;
            for (int m=0; m < dataItems.length; m++) {
                if (udaName.equals(dataItems[m].getName().trim()) &&
                    udaType.equalsIgnoreCase(dataItems[m].getType()) )
                {
                    String udaValue = dataItems[m].getValue();
                    if (udaValue == null)
                        udaValue = "";
                    if (dataItems[m].getType().equals(DataItemRef.TYPE_DATE)) {
%>
                <td nowrap> <script> showDate('<%=udaValue%>'); </script> </td>
<%
                    }
                    else {
%>
                <td><% QuickForm.writeHtml(out, udaValue); %></td>
<%
                    }
                    foundUda = true;
                    break;
                }
            }
            if (!foundUda) {
%>
                <td><% QuickForm.writeHtml(out, ""); %></td>
<%
            }
        }
    }

%>
              </tr>
            </TABLE>
          </td>
        </tr>
        <tr>
            <td align="left">
              <form name="saveForm">
<%
                SearchStruct[] searches = null;
                if(!("LE".equalsIgnoreCase(transportType)))
                {
                   searches = bps.getAllSearchs(bps.getUserName(), SearchStruct.TYPE_PI);
                }
                String searchesStr = "";
                if(searches != null)
                {
                   for(int kk=0; kk < searches.length; kk++)
                      searchesStr = searchesStr + searches[kk].queryName + ",";
                }
%>
                <input type="hidden" name="searchesStr" value="<%= searchesStr %>">
                <input name="srchnm" type="text" size="40" maxlength="64">
                <input value="Save this Search" type="button" class="core-button" onclick="save()">
              </form>
            </td>
        </tr>
      </table>
<%!
    public
    int
    getFieldIdFromFieldName(
        String fieldName)
    {
        int fieldId=WFObjectList.LISTFIELD_PROCESSINSTANCE_NAME;
        if (fieldName.equals("Process Instance Name"))
            fieldId = WFObjectList.LISTFIELD_PROCESSINSTANCE_NAME;
        if (fieldName.equals("Process Definition"))
            fieldId = WFObjectList.LISTFIELD_PLAN_NAME;
        if (fieldName.equals("Date Started"))
            fieldId = WFObjectList.LISTFIELD_PROCESSINSTANCE_CREATEDTIME;
        if (fieldName.equals("Status"))
            fieldId = WFObjectList.LISTFIELD_PROCESSINSTANCE_STATE;
        if (fieldName.equals("Owner(s)"))
            fieldId = WFObjectList.LISTFIELD_PROCESSINSTANCE_OWNER ;
        if (fieldName.equals("Id"))
            fieldId = WFObjectList.LISTFIELD_PROCESSINSTANCE_ID;
        return fieldId;
    }

    public
    String
    getFilterTitleFromId(
        int filterId)
    {
        String filterTitle = "My Active Process Instances";
        switch(filterId){
            case Filter.MyActiveProcesses:
                filterTitle = "My Active Process Instances";
                break;
            case Filter.MyInactiveProcesses:
                filterTitle = "My Inactive Process Instances";
                break;
            case Filter.AllActiveProcesses:
                filterTitle = "All Active Process Instances";
                break;
            case Filter.AllInactiveProcesses:
                filterTitle = "All Inactive Process Instances";
                break;
            case Filter.AllProcesses:
                filterTitle = "All Process Instances";
                break;
            case Filter.AllProcessesInErrorState:
                filterTitle = "Process Instances in Error State";
                break;
        }
        return filterTitle;
    }

    public
    String
    convertUDAOperationString(
        String displayOperator)
    {
        String internalOperator = displayOperator;
        if (displayOperator.equals("In")) {
            internalOperator = WFObjectList.SQLOP_IN;
        }
        else if (displayOperator.equals("Like")) {
            internalOperator = WFObjectList.SQLOP_LIKE;
        }
        else if (displayOperator.equals("Not Like")) {
            internalOperator = WFObjectList.SQLOP_NOTLIKE;
        }
        return internalOperator;
    }

    public
    String
    convertOperationString(
        String displayOperator)
    {
        String internalOperator = WFObjectList.SQLOP_EQUALTO;
        if (displayOperator.equals("Equal To")) {
            internalOperator = WFObjectList.SQLOP_EQUALTO;
        }
        else if (displayOperator.equals("Greater Than")) {
            internalOperator = WFObjectList.SQLOP_GREATERTHAN;
        }
        else if (displayOperator.equals("Greater Than Or Equal To")) {
            internalOperator = WFObjectList.SQLOP_GREATERTHANOREQUALTO;
        }
        else if (displayOperator.equals("Less Than")) {
            internalOperator = WFObjectList.SQLOP_LESSTHAN;
        }
        else if (displayOperator.equals("Less Than Or Equal To")) {
            internalOperator = WFObjectList.SQLOP_LESSTHANOREQUALTO;
        }
        else if (displayOperator.equals("In")) {
            internalOperator = WFObjectList.SQLOP_IN;
        }
        else if (displayOperator.equals("Not Equal To")) {
            internalOperator = WFObjectList.SQLOP_NOTEQUALTO;
        }
        else if (displayOperator.equals("Like")) {
            internalOperator = WFObjectList.SQLOP_LIKE;
        }
        else if (displayOperator.equals("Not Like")) {
            internalOperator = WFObjectList.SQLOP_NOTLIKE;
        }
        return internalOperator;
    }

    public
    ProcessInstance[]
    getProcessInstances(
        int filterId,
        int batchNumber,
        int batchSize,
        String sortField,
        String sortAsc,
        boolean trace,
        Writer out)
        throws Exception
    {
        debug("filterId="+filterId + " batchNumber="+batchNumber + " batchSize="+batchSize + " sortField="+sortField +
              " sortAsc="+sortAsc);

        WFObjectList list = WFObjectFactory.getWFObjectList(((BPMSessionImpl)bps)._wfs);
        addFilters(list);

        ProcessInstance[] processList = new ProcessInstance[0];
        try {
            Object[] objList = null;
            boolean sortAscBool;
            if (sortAsc.equals("true")) {
              sortAscBool = true;
            }
            else if (sortAsc.equals("false")) {
              sortAscBool = false;
            }
            else {
              sortAscBool = true;
            }
            int sortFieldInt;
            if (sortField != null && sortField.trim().length() > 0) {
                int pos = sortField.indexOf("(");
                if(pos == -1){
                   sortFieldInt = getFieldIdFromFieldName(sortField.trim());
                    if (!(sortFieldInt == WFObjectList.LISTFIELD_PROCESSINSTANCE_ID && sortAscBool == true)) {
                        debug("\n in getProcessInstances, adding sort order field="+sortFieldInt + " order="+sortAscBool);
                        list.addSortOrder(sortFieldInt, sortAscBool);
                    }
                }else{
                    String udaName = sortField.substring(0, pos).trim();
                    String udaType = sortField.substring(pos+1, sortField.indexOf(")")).trim();
                    list.addSortOrder(udaName, udaType, sortAscBool);
                }
            }

            list.openBatchedList(filterId);
            objList = list.getNextBatch(batchSize);

            if (objList != null) {
                debug("\n in getProcessInstances, got FIRST batch of "+objList.length + " process instances");
            }
            else {
                debug("\n in getProcessInstances, for FIRST batch, objList is null");
            }
            if (batchNumber > 1) {
                for (int i=1; i<batchNumber; i++) {
                    objList = list.getNextBatch(batchSize);
                    if (objList != null) {
                        debug("\n in getProcessInstances, for batch number ="+i+ ", got " + objList.length + " process instances");
                    }
                    else {
                        debug("\n in getProcessInstances, for batch number ="+i+ ", objList is null");
                    }
                }
            }

            if (objList != null && objList.length > 0) {
                processList = new ProcessInstance[objList.length];
                for (int i=0; i<objList.length; i++) {
                    processList[i] = (ProcessInstance)objList[i];
                }
            }

        }
        finally {
            if (list != null)
                list.closeList();
        }
        return processList;
    }

    public void debug (String msg)
    {
        if (trace) {
            System.out.println(msg);
        }
    }

    public String getDefaultSearch() throws Exception
    {
        String srchName = null;
        SearchStruct defaultSearch = null;
        if(!("LE".equalsIgnoreCase(transportType)))
        {
            defaultSearch = bps.getDefaultSearchQuery(bps.getUserName(), SearchStruct.TYPE_PI);
        }
        if(defaultSearch != null){
            srchName = defaultSearch.queryName + " (Default)";
            String filterIdStr = defaultSearch.preDefFilter;
            filterId = new Integer(filterIdStr).intValue();
            planName = defaultSearch.pdNames;
            piName = defaultSearch.piNames;
            piopStr = defaultSearch.piOp;
            assigneeName = defaultSearch.assignees;
            asnopStr = defaultSearch.asnOp;
            sortField = defaultSearch.sortBy;
            sortAsc = defaultSearch.sortOrder;
            pageSize = defaultSearch.pageSize;
            searchUdaStruct = defaultSearch.udaFilter;
            udaFilters = "";
            if(searchUdaStruct != null ) {
                for(int i = 0; i < searchUdaStruct.length; i++) {
                    udaFilters += searchUdaStruct[i].name+" ("+
                                  searchUdaStruct[i].type+") "+
                                  searchUdaStruct[i].operation+" "+
                                  searchUdaStruct[i].value;
                    if(i != searchUdaStruct.length - 1){
                        udaFilters += ",";
                    }
                }
            }

            displayUdasStr = defaultSearch.disUdas;
            if ((displayUdasStr != null) && (displayUdasStr.trim().length() > 0)) {
                displayUdas = displayUdasStr.split(",");
            }
            else {
                displayUdas = new String[0];
                displayUdasStr = "";
            }

            displayFieldsStr = defaultSearch.disColums;
            if (displayFieldsStr == null) {
                displayFieldsStr = defaultFields;
            }
            displayFields = displayFieldsStr.split(",");

            hFrmCrt = defaultSearch.createdStartDate;
            hToCrt = defaultSearch.createdEndDate;

            tableTitle = "Advanced Search - " + srchName;
        }

        return srchName;
    }

    public void readParams(HttpServletRequest request) throws Exception
    {
        String filterIdStr = request.getParameter("filterId");
        filterId = new Integer(filterIdStr).intValue();

        srchnm = request.getParameter("srchnm");
        if (srchnm == null || srchnm.trim().length() == 0) {
            tableTitle = getFilterTitleFromId(filterId);
        }
        else if (srchnm.equals("--new--")) {
            tableTitle = "New Advanced Search";
        }
        else {
            tableTitle = "Advanced Search - " + srchnm;
        }

        sortField = request.getParameter("sort");
        sortAsc = request.getParameter("asc");
        planName = request.getParameter("pd");
        piName = request.getParameter("pin");
        piopStr = request.getParameter("piop");
        assigneeName = request.getParameter("asn");
        asnopStr = request.getParameter("asnop");
        String pageSizeStr = request.getParameter("pg");
        if (pageSizeStr != null) {
            pageSize = Integer.parseInt(pageSizeStr);
        }
        udaFilters = request.getParameter("filterUdas");
        displayUdasStr = request.getParameter("dspUda");
        if ((displayUdasStr != null) && (displayUdasStr.trim().length() > 0)) {
            displayUdas = displayUdasStr.split(",");
        }
        else {
            displayUdas = new String[0];
            displayUdasStr = "";
        }
        displayFieldsStr = request.getParameter("dspFields");
        if (displayFieldsStr == null) {
            displayFieldsStr = defaultFields;
        }
        displayFields = displayFieldsStr.split(",");
        hFrmCrt = request.getParameter("hFrmCrt");
        hToCrt = request.getParameter("hToCrt");
        String pageNumberStr = request.getParameter("pgNum");
        if (pageNumberStr != null) {
            pageNumber = Integer.parseInt(pageNumberStr);
        }
    }

    public void setDefaultValues() throws Exception
    {
        filterId = Filter.MyActiveProcesses;
        tableTitle = getFilterTitleFromId(filterId);
        pageSize = 20;
        tasks = new ProcessInstance[0];
        sortField = "Id";
        sortAsc = "true";
        filterName = "";
        planName = "";
        piName = "";
        piopStr = "";
        assigneeName = "";
        asnopStr = "";
        udaFilters = "";
        searchUdaStruct = null;
        displayUdasStr = "";
        displayUdas = new String[0];
        displayFieldsStr = defaultFields;
        displayFields = displayFieldsStr.split(",");
        hFrmCrt = "";
        hToCrt = "";
    }

    public void cleanupGlobals() throws Exception
    {
        if(pageNumber == 0){
            pageNumber = 1;
        }
        if (sortField != null && !sortField.equals("-- Select --") ) {
            if (sortAsc == null) {
                sortAsc = "true";
            }
        }
        else {
            sortField = "Id";
            sortAsc = "true";
        }
        if(planName == null){
            planName = "";
        }
        if(piName == null){
            piName = "";
        }
        if(piopStr == null){
            piopStr = "";
        }
        if(assigneeName == null){
            assigneeName = "";
        }
        if(asnopStr == null){
            asnopStr = "";
        }
        if(pageSize == 0){
            pageSize = 20;
        }
        if(srchnm == null){
            srchnm = "";
        }
        if(displayUdasStr == null){
            displayUdasStr = "";
        }
        if(displayFieldsStr == null){
            displayFieldsStr = "";
        }
        if(udaFilters == null){
            udaFilters = "";
        }
        if(hFrmCrt == null){
            hFrmCrt = "";
        }
        if(hToCrt== null){
            hToCrt = "";
        }
    }

    public void addFilters(WFObjectList list) throws Exception {
        if (planName != null && planName.trim().length() > 0 && !planName.equals("-- Select --")) {
            debug("\n adding planName filter '" + planName + "'");
            list.addFilter(WFObjectList.LISTFIELD_PLAN_NAME, WFObjectList.SQLOP_EQUALTO, "'" + planName + "'");
        }
        if (piName != null && piName.trim().length() > 0) {
            String piop = convertOperationString(piopStr);
            debug("\n adding piName filter " + piop + "'" + piName + "'");
            if (piop.equals(WFObjectList.SQLOP_IN)) {
                list.addFilter(WFObjectList.LISTFIELD_PROCESSINSTANCE_NAME, piop, processOperandForIn(piName));
            } else {
                list.addFilter(WFObjectList.LISTFIELD_PROCESSINSTANCE_NAME, piop, "'" + piName + "'");
            }
        }
        if (assigneeName != null && assigneeName.trim().length() > 0) {
            String asnop = convertOperationString(asnopStr);
            debug("\n adding owner filter " + asnop + "'" + assigneeName + "'");
            if (asnop.equals(WFObjectList.SQLOP_IN)) {
                list.addFilter(WFObjectList.LISTFIELD_PROCESSINSTANCE_OWNER, asnop, processOperandForIn(assigneeName));
            } else {
                list.addFilter(WFObjectList.LISTFIELD_PROCESSINSTANCE_OWNER, asnop, "'" + assigneeName + "'");
            }
        }
        if (hFrmCrt != null && hFrmCrt.trim().length() > 0) {
            debug("\n adding filter FROM LISTFIELD_PROCESSINSTANCE_CREATEDTIME");
            list.addFilter(WFObjectList.LISTFIELD_PROCESSINSTANCE_CREATEDTIME, WFObjectList.SQLOP_GREATERTHANOREQUALTO, "'" + hFrmCrt + "'");
        }
        if (hToCrt != null && hToCrt.trim().length() > 0) {
            debug("\n adding filter TO LISTFIELD_PROCESSINSTANCE_CREATEDTIME");
            list.addFilter(WFObjectList.LISTFIELD_PROCESSINSTANCE_CREATEDTIME, WFObjectList.SQLOP_LESSTHANOREQUALTO, "'" + hToCrt + "'");
        }
        if (udaFilters != null && udaFilters.trim().length() > 0) {
            debug("\n udaFilters=" + udaFilters);

            String[] udaFilter = udaFilters.split(";");
            searchUdaStruct = new SearchUdaStruct[udaFilter.length];
            for (int i = 0; i < udaFilter.length; i++) {
                String oneUdaFilter = udaFilter[i];
                debug("\n worklist -- oneUdaFilter=" + oneUdaFilter);

                int posOpenParen = oneUdaFilter.indexOf("(");
                String udaName = oneUdaFilter.substring(0, posOpenParen).trim();
                int posCloseParen = oneUdaFilter.indexOf(")");
                String udaType = oneUdaFilter.substring(posOpenParen + 1, posCloseParen).trim();
                int posSpace = oneUdaFilter.lastIndexOf(" ");
                String udaOpStr = oneUdaFilter.substring(posCloseParen + 2, posSpace).trim();
                ;
                String udaOp = convertUDAOperationString(udaOpStr);
                String originalUdaValue = oneUdaFilter.substring(posSpace).trim();
                String udaValue = originalUdaValue;
                if (udaOp.equals(WFObjectList.SQLOP_IN)) {
                    udaValue = processOperandForIn(udaValue);
                } else {
                    udaValue = "'" + udaValue + "'";
                }

                debug("\n udaName=" + udaName);
                debug("\n udaType=" + udaType);
                debug("\n udaOp=" + udaOp);
                debug("\n udaValue=" + udaValue);
                debug("\n adding UDA filter #2");
                list.addFilter(udaName, udaType, udaOp, udaValue);

                SearchUdaStruct suda = new SearchUdaStruct();
                suda.name = udaName;
                suda.type = udaType;
                suda.operation = udaOpStr;
                suda.value = originalUdaValue;

                searchUdaStruct[i] = suda;
            }
        }
    }

    public String processOperandForIn(String operand) throws Exception {
        StringTokenizer st = new StringTokenizer(operand, ",", true);
        StringBuffer sb = new StringBuffer();
        sb.append("(");
        while (st.hasMoreTokens()) {
            String token = st.nextToken();
            if (token.equals(",")) {
                sb.append(token);
            } else {
                sb.append("'");
                sb.append(token);
                sb.append("'");
            }
        }
        sb.append(")");
        return sb.toString();
    }

%>
    </td>
    </tr>
  </table>
</center>
</body>
</html>
