Package com.centraview.administration.authorization

Source Code of com.centraview.administration.authorization.AuthorizationEJB

/*
* $RCSfile: AuthorizationEJB.java,v $    $Revision: 1.5 $  $Date: 2005/09/23 11:01:08 $ - $Author: mcallist $
*
* The contents of this file are subject to the Open Software License
* Version 2.1 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
* http://www.centraview.com/opensource/license.html
*
* Software distributed under the License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
* License for the specific language governing rights and limitations
* under the License.
*
* The Original Code is: CentraView Open Source.
*
* The developer of the Original Code is CentraView.  Portions of the
* Original Code created by CentraView are Copyright (c) 2004 CentraView,
* LLC; All Rights Reserved.  The terms "CentraView" and the CentraView
* logos are trademarks and service marks of CentraView, LLC.
*/


package com.centraview.administration.authorization;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;
import java.util.TreeMap;
import java.util.Vector;

import javax.ejb.EJBException;
import javax.ejb.SessionBean;
import javax.ejb.SessionContext;

import org.apache.log4j.Logger;

import com.centraview.common.CVDal;
import com.centraview.common.CVUtility;
import com.centraview.common.IntMember;
import com.centraview.common.StringMember;
import com.centraview.valuelist.ValueListParameters;
import com.centraview.valuelist.ValueListVO;

public class AuthorizationEJB implements SessionBean
{
  protected SessionContext ctx;
  private String dataSource = "";
  private static Logger logger = Logger.getLogger(AuthorizationEJB.class);

  public void setSessionContext(SessionContext ctx)
  {
    this.ctx=ctx;
  }


  public void ejbCreate()
  {
  }

  public void ejbRemove()
  {
  }

  public void ejbActivate()
  {
  }

  public void ejbPassivate()
  {
  }


  public int addSecurityProfile(String profileName, ModuleFieldRightMatrix mfrx) throws AuthorizationException
  {

    CVDal cvdl = new CVDal(dataSource);
    cvdl.setSql("authorization.insertsecurityprofile");
    cvdl.setString(1,profileName);
    cvdl.executeUpdate();

    int profileId = cvdl.getAutoGeneratedKey();
    insertSecurityProfile(profileId, mfrx, cvdl);
  return profileId;
  }

  public void updateSecurityProfile(int profileId, String profileName, ModuleFieldRightMatrix mfrx) throws AuthorizationException
  {
    CVDal cvdl = new CVDal(dataSource);
    try
    {
      cvdl.setSql("authorization.updatesecurityprofile");
      cvdl.setString(1, profileName);
      cvdl.setInt(2, profileId);
      cvdl.executeUpdate();

      cvdl.clearParameters();
      cvdl.setSql("authorization.deletemoduleauthorization");
      cvdl.setInt(1, profileId);
      cvdl.executeUpdate();

      cvdl.clearParameters();
      cvdl.setSql("authorization.deletefieldauthorization");
      cvdl.setInt(1, profileId);
      cvdl.executeUpdate();

      this.insertSecurityProfile(profileId, mfrx, cvdl);
    }
    finally
    {
      cvdl.destroy();
      cvdl = null;
    }
  }

  public HashMap getSecurityProfile(int profileId) throws AuthorizationException
  {

    CVDal cvdl = new CVDal(dataSource);
    HashMap retHm = null;
    try
    {
      ModuleFieldRightMatrix mfrm = this.getBlankFieldRightMatrix(ModuleFieldRightMatrix.NONE_RIGHT);
      // Now set the rights on the modules based on the profile.
      // in the Database
      cvdl.setSql("authorization.getsecurityprofilemodule");
      cvdl.setInt(1,profileId);
      Collection col = cvdl.executeQuery();
      Iterator it = col.iterator();
      retHm = new HashMap();

      if (it.hasNext())
      {
        HashMap dhm = null;
        while (it.hasNext())
        {
          dhm = (HashMap)it.next();
          Integer moduleId = new Integer(((Number)dhm.get("moduleid")).intValue());
          Integer rights = new Integer(((Number)dhm.get("privilegelevel")).intValue());
          mfrm.setModuleRight(moduleId, rights);
        }

        retHm.put("profileid",(Long)dhm.get("profileid"));
        retHm.put("profilename",(String)dhm.get("profilename"));

        // Populate the fields HashMap of HashMaps with only the ones listed in the
        // profile in the database.
        cvdl.clearParameters();
        cvdl.setSql("authorization.getsecurityprofilefield");
        cvdl.setInt(1,profileId);
        Collection wookie = cvdl.executeQuery();
        Iterator chewy = wookie.iterator();
        while(chewy.hasNext())
        {
          dhm = (HashMap)chewy.next();
          mfrm.setFieldRight((String)dhm.get("modulename"),(String)dhm.get("name"),((Number)(dhm.get("privilegelevel"))).intValue());
        }
        retHm.put("modulefieldrightmatrix",mfrm);
      }
    } catch (Exception e){
      logger.error("[Exception][AuthorizationEJB.getSecurityProfile] Exception Thrown: ",e);
    }
    finally
    {
      cvdl.destroy();
      cvdl = null;
    }

    return retHm;

  }


  public ModuleFieldRightMatrix getUserSecurityProfileMatrix(int individualId) throws AuthorizationException
  {
    CVDal cvdl = new CVDal(dataSource);
    ModuleFieldRightMatrix retMfrx = null;
    try
    {
      retMfrx = this.getBlankFieldRightMatrix(ModuleFieldRightMatrix.NONE_RIGHT);
      cvdl.setSql("authorization.getuserallsecurityprofilemodule");
      cvdl.setInt(1,individualId);
      Collection col = cvdl.executeQuery();
      Iterator it = col.iterator();

      if (it.hasNext())
      {
        while (it.hasNext())
        {
          HashMap dhm=(HashMap)it.next();
          Integer moduleId = new Integer(((Number)dhm.get("moduleid")).intValue());
          Integer right = new Integer(((Number)dhm.get("privilegelevel")).intValue());
          retMfrx.setModuleRight(moduleId, right);
        }

        cvdl.clearParameters();
        cvdl.setSql("authorization.getuserallsecurityprofilefield");
        cvdl.setInt(1,individualId);
        Collection colf = cvdl.executeQuery();
        Iterator itf = colf.iterator();
        while(itf.hasNext())
        {
          HashMap dhm = (HashMap)itf.next();
          retMfrx.setFieldRight((String)dhm.get("modulename"),(String)dhm.get("fieldname"),((Number)dhm.get("privilegelevel")).intValue());
        }
      }
    }
    catch (Exception e)
    {
      logger.error("[Exception][AuthorizationEJB.getUserSecurityProfileMatrix] Exception Thrown: ",e);
    }
    finally
    {
      cvdl.destroy();
      cvdl = null;
    }
    return retMfrx;
  }

  public ModuleFieldRightMatrix getUserSecurityProfileMatrix(String moduleName, int individualId, boolean byListName) throws AuthorizationException
  {
    CVDal cvdl = new CVDal(dataSource);
    ModuleFieldRightMatrix retMfrx= null;
    try
    {
      retMfrx = this.getBlankFieldRightMatrix(ModuleFieldRightMatrix.NONE_RIGHT);
      cvdl.setSql("authorization.getusersecurityprofilemodule");
      cvdl.setInt(1,individualId);
      cvdl.setString(2,moduleName);

      Collection col = cvdl.executeQuery();
      Iterator it = col.iterator();

      if (it.hasNext())
      {
        while (it.hasNext())
        {
          HashMap dhm=(HashMap)it.next();
          retMfrx.setVisibleModule((String)dhm.get("name"));
        }

        cvdl.clearParameters();
        cvdl.setSql("authorization.getusersecurityprofilefield");
        cvdl.setInt(1,individualId);
        cvdl.setString(2,moduleName);
        Collection colf = cvdl.executeQuery();
        Iterator itf = colf.iterator();
        while(itf.hasNext())
        {
          HashMap dhm = (HashMap)itf.next();
          if (byListName == true && dhm.get("listcolname") != null)
          {
            String lname = (String)dhm.get("listcolname");
            if(lname.length() > 0)
              retMfrx.setFieldRight((String)dhm.get("modulename"),lname,((Number)dhm.get("privilegelevel")).intValue());

          } else
          {
            retMfrx.setFieldRight((String)dhm.get("modulename"),(String)dhm.get("fieldname"),((Number)dhm.get("privilegelevel")).intValue());
          }
        }

      }
    }finally
    {
      cvdl.destroy();
      cvdl = null;
    }

    return retMfrx;

  }

  /**
   * Returns true if the given individualID has privilege
   * to view the given moduleName. Returns false if the
   * user does not have privilege to view the given module.
   * <strong>Customer users and Admin users are treated as
   * special cases, this method will always return true if
   * the given individualID is a Customer or Admin user.</strong>
   *
   * @param moduleName The String representation of the module
   * which we are asking about (check the "module" table for
   * correct value.)
   * @param individualID The individualID of the user we are
   * asking about.
   * @return boolean: true for "yes", false for "no"
   */
  public boolean isModuleVisible(String moduleName, int individualID) throws AuthorizationException
  {
    CVDal cvdl = new CVDal(this.dataSource);

    try
    {
      if (this.isUserCustomerOrAdministrator(cvdl, individualID))
      {
        return true;
      }
      // now get the user's security profile from the database
      // and check to see whether they have access to the
      // specified moduleName or not.
      cvdl.setSql("authorization.getusersecurityprofilemodule");
      cvdl.setInt(1, individualID);
      cvdl.setString(2, moduleName);

      Collection results = cvdl.executeQuery();
      Iterator iter = results.iterator();
      if (iter.hasNext())
      {
        return(true);
      }else{
        return(false);
      }
    }finally{
      cvdl.destroy();
      cvdl = null;
    }
  }   // end isModuleVisible() method


  private void insertmarketingRecordPermission(int indId, int recordType, int recordId, int privilege, CVDal cvdl)
  {
    //cvdl.clearParameters();
    cvdl.setInt(1,indId);
    cvdl.setInt(2,recordType);
    cvdl.setInt(3,privilege);
    cvdl.setInt(4,recordId);
    cvdl.executeUpdate();
  }

  public void saveMarketingRecordPermission(String recordType, int recordId, int view[], int modify[], int delete[], int publicFlag) throws AuthorizationException
  {
    if (recordType == null ||  recordType.length() == 0) {
      throw new AuthorizationException(AuthorizationException.INVALID_DATA,"RecordType not prvided");
    }

    if (recordId <= 0 ) {
      throw new AuthorizationException(AuthorizationException.INVALID_DATA,"RecordID < 0");
    }

    CVDal cvdl = new CVDal(dataSource);

    try {
      if (publicFlag < 0) {
        // if flag < 0, then we're setting all list members
        // to "Public" status. Therefore, we need to delete
        // all settings from recordauthorisation table, and
        // insert records into publicrecords table.

        // first, delete all records from recordauthorisation
        // delete individuals from recordauthorisation

        cvdl.setSql("authorization.deleteindividualrecordpermission");
        cvdl.setString(1, "Individual");
        cvdl.setInt(2, recordId);
        cvdl.executeUpdate();
        cvdl.clearParameters();

        cvdl.setSql("authorization.deleterecordpermission");
        cvdl.setString(1,recordType);
        cvdl.setInt(2,recordId);
        cvdl.executeUpdate();
        cvdl.clearParameters();

        // delete entities from recordauthorisation
        cvdl.setSql("authorization.deleteentityrecordpermission");
        cvdl.setString(1, "Entity");
        cvdl.setInt(2, recordId);
        cvdl.executeUpdate();
        cvdl.clearParameters();

        String moduleid = this.getModuleIdByModuleName(recordType);
        this.setRecordToPublic(moduleid, recordId);

        // next, set all records to public
        this.insertMarketingMemberPublicRecords(recordId);   // recordId = ListID
      }else{
        // if flag >= 0, then we're not setting list members
        // to "Public" status. Therefore, we need to delete
        // all records from publicrecords table, and insert
        // the appropriate records into recordauthorisation table.

        // first, delete all records from publicrecords
        this.deleteMarketingMemberPublicRecords(recordId);   // recordId = ListID
        this.deleteRecordFromPublic(recordType,recordId);
       
        String moduleid = this.getModuleIdByModuleName(recordType);
        // then, continue with Naresh's code
        cvdl.setSql("authorization.deleterecordpermission");
        cvdl.setString(1,recordType);
        cvdl.setInt(2,recordId);
        cvdl.executeUpdate();
        cvdl.clearParameters();

        cvdl.setSql("authorization.deleteindividualrecordpermission");
        cvdl.setString(1, "Individual");
        cvdl.setInt(2, recordId);
        cvdl.executeUpdate();
        cvdl.clearParameters();

        cvdl.setSql("authorization.deleteentityrecordpermission");
        cvdl.setString(1, "Entity");
        cvdl.setInt(2, recordId);
        cvdl.executeUpdate();
        cvdl.clearParameters();
       
        ArrayList authorisationQueryList = new ArrayList();

        if (view != null) {
          for (int i=0;i<view.length;i++) {
            String authorisationQuery = "insert into recordauthorisation(individualid,recordid,privilegelevel,recordtypeid) "+
            "values("+view[i]+","+recordId +","+ ModuleFieldRightMatrix.VIEW_RIGHT+","+ moduleid+")";
           
            authorisationQueryList.add(authorisationQuery);
            authorisationQuery = null;
            authorisationQuery = "insert INTO recordauthorisation "+
                 " (individualid,recordid,recordtypeid,privilegelevel) select "+view[i]+
           ", individualid , 15 , "+ModuleFieldRightMatrix.VIEW_RIGHT+"  from individual where list="+ recordId;
            authorisationQueryList.add(authorisationQuery);
            authorisationQuery = null;
            authorisationQuery = "insert INTO recordauthorisation "+
           " (individualid,recordid,recordtypeid,privilegelevel) select "+view[i]+
           ", entityid , 14 , "+ModuleFieldRightMatrix.VIEW_RIGHT+"  from entity where list="+ recordId;
            authorisationQueryList.add(authorisationQuery);
          }
        }

        if (modify != null) {
          for (int i=0; i<modify.length; i++) {
            String authorisationQuery = "insert into recordauthorisation(individualid,recordid,privilegelevel,recordtypeid) "+
            "values("+modify[i]+","+recordId +","+ ModuleFieldRightMatrix.UPDATE_RIGHT+","+ moduleid+")";
           
            authorisationQueryList.add(authorisationQuery);
            authorisationQuery = null;
            authorisationQuery = "insert INTO recordauthorisation "+
             " (individualid,recordid,recordtypeid,privilegelevel) select "+modify[i]+
             ", individualid , 15 , "+ModuleFieldRightMatrix.UPDATE_RIGHT+"  from individual where list="+ recordId;
            authorisationQueryList.add(authorisationQuery);
            authorisationQuery = null;
            authorisationQuery = "insert INTO recordauthorisation "+
           " (individualid,recordid,recordtypeid,privilegelevel) select "+modify[i]+
           ", entityid , 14 , "+ModuleFieldRightMatrix.UPDATE_RIGHT+"  from entity where list="+ recordId;
            authorisationQueryList.add(authorisationQuery);     
          }
        }

        if (delete != null) {
          for (int i=0; i<delete.length; i++) {
            String authorisationQuery = "insert into recordauthorisation(individualid,recordid,privilegelevel,recordtypeid) "+
            "values("+delete[i]+","+recordId +","+ ModuleFieldRightMatrix.DELETE_RIGHT+","+ moduleid+")";
           
            authorisationQueryList.add(authorisationQuery);
            authorisationQuery = null;
            authorisationQuery = "insert INTO recordauthorisation "+
            " (individualid,recordid,recordtypeid,privilegelevel) select "+delete[i]+
            ", individualid , 15 , "+ModuleFieldRightMatrix.DELETE_RIGHT+"  from individual where list="+ recordId;
           
            authorisationQueryList.add(authorisationQuery);
            authorisationQuery = null;
            authorisationQuery = "insert INTO recordauthorisation "+
            " (individualid,recordid,recordtypeid,privilegelevel) select "+delete[i]+
            ", entityid , 14 , "+ModuleFieldRightMatrix.DELETE_RIGHT+"  from entity where list="+ recordId;
            authorisationQueryList.add(authorisationQuery);
          }
        }
       
        try {
          int[] batchResult = cvdl.batchProcess(authorisationQueryList);
          cvdl.clearParameters();
        } catch (Exception e) {
          logger.error("[Exception] AuthorizationEJB.saveMarketingRecordPermission: " , e);
        }
      }   // end if (flag < 0)
    }catch(Exception e){
      logger.error("[Exception][AuthorizationEJB.saveMarketingRecordPermission] Exception Thrown: ",e);
      throw new AuthorizationException(AuthorizationException.INVALID_DATA, "Unknown error occured");
    }finally{
      cvdl.destroy();
      cvdl = null;
    }
  }


  public void saveCurrentDefaultPermission(String recordType, int recordId, int uid) throws AuthorizationException
  {

    String moduleid = this.getModuleIdByModuleName(recordType);
    int flag = 0;

      if (this.getUserDefaultPermission(uid).equalsIgnoreCase("Yes"))
      {
        this.setRecordToPublic(moduleid, recordId);
        flag = 1;
      }
      HashMap hm = new HashMap();
      hm = getDefaultRecordPermission(uid);

      Vector viewVect = null;
      Vector updateVect = null;
      Vector deleteVect = null;

      int arrView[] = null;
      int arrModify[] = null;
      int arrDelete[] = null;

    if (hm != null)
    {
        viewVect = (Vector) hm.get("VIEW");
        updateVect = (Vector) hm.get("UPDATE");
        deleteVect = (Vector) hm.get("DELETE");
      }

      if (deleteVect == null) {

         deleteVect = new Vector();
      }
      deleteVect.addElement(new Long(uid));

      arrView = new int[viewVect.size()];
      arrModify = new int[updateVect.size()];
      arrDelete = new int[deleteVect.size()];

      Iterator it = null;
      int j = 0;

    if (viewVect != null)
    {
        it = viewVect.iterator();
    while (it.hasNext())
     {
          arrView[j] = ( (Long) it.next()).intValue();
          j = j + 1;
        }
      }

    if (updateVect != null)
    {
        it = updateVect.iterator();
        j = 0;
     while (it.hasNext())
     {
          arrModify[j] = ( (Long) it.next()).intValue();
          j = j + 1;
        }
      }

    if (deleteVect != null)
    {
        it = deleteVect.iterator();
        j = 0;
     while (it.hasNext())
     {
          arrDelete[j] = ( (Long) it.next()).intValue();
          j = j + 1;
        }
      }

    this.saveRecordPermission(uid,flag,recordType, recordId, arrView, arrModify, arrDelete);
  }

  public void setUserDefaultPermissions(int uid, String value) throws AuthorizationException
  {
    CVDal cvdl = new CVDal(dataSource);
    try
    {
      cvdl.setSql("authorization.setallrecordspublicfordefaultprivileges");
      cvdl.setString(1, value);
      cvdl.setInt(2, uid);
      cvdl.executeUpdate();

    }
    catch(Exception e){
      logger.error("[Exception][AuthorizationEJB.setUserDefaultPermissions] Exception Thrown: ",e);
      throw new AuthorizationException(AuthorizationException.INVALID_DATA, "Unknown error occured");
    }finally{
      cvdl.destroy();
      cvdl = null;
    }
  }

  public String getUserDefaultPermission(int uid) throws AuthorizationException
  {
    CVDal cvdl = new CVDal(dataSource);
    try
    {
      cvdl.setSql("authorization.getallrecordspublicfordefaultprivileges");
      cvdl.setInt(1, uid);

      Collection col1 = cvdl.executeQuery();
      HashMap hm = new HashMap();
      String str = "";
      Iterator it = col1.iterator();
      if (it.hasNext())
      {
          hm = (HashMap)it.next();
      }
      if (hm.get("preference_value") != null)
      {
        str = hm.get("preference_value").toString();
      }

      return str;
    }
    catch(Exception e){
      logger.error("[Exception][AuthorizationEJB.getUserDefaultPermissions] Exception Thrown: ",e);
      throw new AuthorizationException(AuthorizationException.INVALID_DATA, "Unknown error occured");
    }finally{
      cvdl.destroy();
      cvdl = null;
    }
  }

  public void deleteUserDefaultPrivileges(int uid) throws AuthorizationException
  {
    CVDal cvdl = new CVDal(dataSource);
    try
    {
      cvdl.setSql("authorization.deleteuserdefaultprivileges");
      cvdl.setInt(1, uid);
      cvdl.executeUpdate();
    }
    catch(Exception e){
      logger.error("[Exception][AuthorizationEJB.deleteUserDefaultPrivileges] Exception Thrown: ",e);
      throw new AuthorizationException(AuthorizationException.INVALID_DATA, "Unknown error occured");
    }finally{
      cvdl.destroy();
      cvdl = null;
    }
  }

  public void setRecordToPublic(String moduleid, int recordid) throws AuthorizationException
  {
    CVDal cvdl = new CVDal(dataSource);
    try
    {
      cvdl.setSql("authorization.insertintopublicrecords");
      cvdl.setString(1, moduleid);
      cvdl.setInt(2, recordid);
      cvdl.executeUpdate();
    }
    catch(Exception e){
      logger.error("[Exception][AuthorizationEJB.setRecordToPublic] Exception Thrown: ",e);
      throw new AuthorizationException(AuthorizationException.INVALID_DATA, "Unknown error occured");
    }finally{
      cvdl.destroy();
      cvdl = null;
    }
  }

  /**
   * Finds and returns the moduleID (as a String) of the module name
   * passed to the method. If the method is not found,
   * 0 will be returned.
   *
   * @param modulename The name of the module being checked.
   *
   * @return If the module exists, the moduleID, otherwise, 0.
   *
   * @throws AuthorizationException Something went terribly wrong.
   */
  public String getModuleIdByModuleName(String modulename) throws AuthorizationException
  {
    CVDal cvdl = new CVDal(dataSource);
    String moduleid = "0";
    try
    {
      cvdl.setSql("authorization.getmoduleidbymodulename");
      cvdl.setString(1, modulename);
      Collection col1 = cvdl.executeQuery();
      HashMap hm = new HashMap();

      Iterator iter = col1.iterator();
      if (iter.hasNext())
      {
        hm = (HashMap) iter.next();
        if (hm.get("moduleid") != null)
        {
          moduleid = hm.get("moduleid").toString();
        } //end of if statement (hm.get("moduleid") != null)
      } //end of if statement (iter.hasNext())
    } //end of try block
    catch(Exception e)
    {
      logger.error("[Exception] AuthorizationEJB.getModuleIdByModuleName: "
          , e);
      throw new AuthorizationException(
        AuthorizationException.INVALID_DATA, "Unknown error occured");
    } //end of catch block (Exception)
    finally
    {
      cvdl.destroy();
      cvdl = null;
    } //end of finally block
    return moduleid;
  } //end of getModuleIdByModuleName method

  /**
   * Finds and returns the moduleID (as a String) of the module primary table
   * passed to the method. If the module is not found,
   * 0 will be returned.
   *
   * @param primaryTable The primary table of the module being checked.
   *
   * @return If the module exists, the moduleID, otherwise, 0.
   *
   * @throws AuthorizationException Something went terribly wrong.
   */
  public String getModuleIdByPrimaryTable(String primaryTable) throws AuthorizationException
  {
    CVDal cvdl = new CVDal(dataSource);
    String moduleid = "0";
    try
    {
      cvdl.setSqlQuery("SELECT moduleid FROM module WHERE "
          + "UPPER(primarytable) LIKE UPPER('%" + primaryTable + "%')");
      Collection col1 = cvdl.executeQuery();
      HashMap hm = new HashMap();

      Iterator iter = col1.iterator();
      if (iter.hasNext())
      {
        hm = (HashMap) iter.next();
        if (hm.get("moduleid") != null)
        {
          moduleid = hm.get("moduleid").toString();
        } //end of if statement (hm.get("moduleid") != null)
      } //end of if statement (iter.hasNext())
    } //end of try block
    catch(Exception e)
    {
      logger.error("[Exception] AuthorizationEJB.getModuleIdByModuleName: "
          , e);
      throw new AuthorizationException(
        AuthorizationException.INVALID_DATA, "Unknown error occured");
    } //end of catch block (Exception)
    finally
    {
      cvdl.destroy();
      cvdl = null;
    } //end of finally block
    return moduleid;
  } //end of getModuleIdByPrimaryTable method

  public String getRecordFromPublic(String modulename, int recordid) throws AuthorizationException
  {
    CVDal cvdl = new CVDal(dataSource);
    try
    {
      String moduleid = this.getModuleIdByModuleName(modulename);

      cvdl.setSql("authorization.getrecordfrompublicrecords");
      cvdl.setString(1, moduleid);
      cvdl.setInt(2, recordid);

      Collection col1 = cvdl.executeQuery();
      HashMap hm = new HashMap();
      String str = "No";
      Iterator it = col1.iterator();
      if (it.hasNext())
      {
          str = "Yes";
      }

      return str;
    }
    catch(Exception e){
      logger.error("[Exception][AuthorizationEJB.getRecordFromPublic] Exception Thrown: ",e);

      throw new AuthorizationException(AuthorizationException.INVALID_DATA, "Unknown error occured");
    }finally{
      cvdl.destroy();
      cvdl = null;
    }

  }


  public void deleteRecordFromPublic(String moduleName, int recordid) throws AuthorizationException
  {
    CVDal cvdl = new CVDal(dataSource);
    try
    {
    String moduleID = this.getModuleIdByModuleName(moduleName);
      cvdl.setSql("authorization.deletefrompublicrecords");
      cvdl.setString(1, moduleID);
      cvdl.setInt(2, recordid);
      cvdl.executeUpdate();
    }
    catch(Exception e){
      logger.error("[Exception][AuthorizationEJB.deleteRecordFromPublic] Exception Thrown: ",e);
      throw new AuthorizationException(AuthorizationException.INVALID_DATA, "Unknown error occured");
    }finally{
      cvdl.destroy();
      cvdl = null;
    }
  }

  public void deleteRecordsFromRecordAuthorization(String moduleName, int recordid) throws AuthorizationException
  {
    CVDal cvdl = new CVDal(dataSource);
    try
    {
      // deleterecordpermission gets the moduleId and does the delete in a
      // single query.
      cvdl.setSql("authorization.deleterecordpermission");
      cvdl.setString(1, moduleName);
      cvdl.setInt(2, recordid);
      cvdl.executeUpdate();
    } catch(Exception e) {
      logger.error("[deleteRecordsFromRecordAuthorization] Exception thrown.", e);
      throw new AuthorizationException(AuthorizationException.INVALID_DATA, "Unknown error occured");
    } finally {
      cvdl.destroy();
      cvdl = null;
    }
  }


  /**
   * This method updates the recordauthorisation table, basically a record is
   * uniquely identified by its moduleId (or recordType) and its recordId.
   * When saving a record permission any existing permission is first deleted
   * and then the new ones are inserted.  The permissions are based on the three
   * int arrays which contain individualIds that should have those specific rights
   * as the local name of that variable (view, modify, delete)
   *
   * This method also uses public records flag.  If the flag is less than zero
   * someone that indicates that it is a public record and therefore the
   * recordauthorisation table has all remnants of this record removed
   * and the public flag is set for this record, otherwise it will Build a batch
   * query to do the potentially many inserts for this particular record into
   * the recordauthorisation table.
   *
   * @param uid I believe this is the individualId but it appears to be unused.
   * @param flag the public record flag
   * @param recordType
   * @param recordId
   * @param view
   * @param modify
   * @param delete
   * @throws AuthorizationException
   */
  public void saveRecordPermission(int uid, int flag, String recordType, int recordId, int view[], int modify[], int delete[]) throws AuthorizationException
  {
    if (recordType == null || recordType.length() == 0)
    {
      throw new AuthorizationException(AuthorizationException.INVALID_DATA, "Record type not provided.");
    }
    if (recordId <= 0)
    {
      throw new AuthorizationException(AuthorizationException.INVALID_DATA, "RecordID not provided.");
    }
    CVDal cvdl = new CVDal(dataSource);
    try
    {
      String moduleid = this.getModuleIdByModuleName(recordType);
      // always delete the records, as we will just re-insert if we need to.
      this.deleteRecordsFromRecordAuthorization(recordType, recordId);
      if (flag < 0)
      {
        // somehow flag < 0 means we are changing this to a public record.
        this.setRecordToPublic(moduleid, recordId);
      } else {
        if (flag != 1)
        {
          this.deleteRecordFromPublic(recordType, recordId);
        }
        // This list will hold all the queries to be batch processed.
        ArrayList authorisationQueryList = new ArrayList();
        // Individual Ids that should be able to view the record
        if (view != null)
        {
          for (int i = 0; i < view.length; i++)
          {
            String authorisationQuery = "INSERT INTO recordauthorisation(individualid,recordid,privilegelevel,recordtypeid) " + "VALUES(" + view[i] + "," + recordId + "," + ModuleFieldRightMatrix.VIEW_RIGHT + "," + moduleid + ")";
            authorisationQueryList.add(authorisationQuery);
          }
        }
        // Individual Ids that should be able to modify the record
        if (modify != null)
        {
          for (int i = 0; i < modify.length; i++)
          {
            String authorisationQuery = "INSERT INTO recordauthorisation(individualid,recordid,privilegelevel,recordtypeid) " + "VALUES(" + modify[i] + "," + recordId + "," + ModuleFieldRightMatrix.UPDATE_RIGHT + "," + moduleid + ")";
            authorisationQueryList.add(authorisationQuery);
          }
        }
        // Individual Ids that should be able to delete the record
        if (delete != null)
        {
          for (int i = 0; i < delete.length; i++)
          {
            String authorisationQuery = "INSERT INTO recordauthorisation(individualid,recordid,privilegelevel,recordtypeid) " + "VALUES(" + delete[i] + "," + recordId + "," + ModuleFieldRightMatrix.DELETE_RIGHT + "," + moduleid + ")";
            authorisationQueryList.add(authorisationQuery);
          }
        }
        try
        {
          // Do the batch processing.
          int[] batchResult = cvdl.batchProcess(authorisationQueryList);
        } catch (Exception e) {
          logger.error("[saveRecordPermission] Exception thrown doing the batch process.", e);
        }
      }
    } catch (Exception e) {
      logger.error("[saveRecordPermission] Exception thrown.", e);
      throw new AuthorizationException(AuthorizationException.INVALID_DATA, "Unknown error occured");
    } finally {
      cvdl.destroy();
      cvdl = null;
    }
  } // end saveRecordPermission() method

  public void saveDefaultPermissions(int flag, int ownerId, int view[], int modify[],int delete[]) throws AuthorizationException
  {
    CVDal cvdl = new CVDal(dataSource);

    if (flag < 0)
    {
      this.setUserDefaultPermissions(ownerId,"Yes");
      this.deleteUserDefaultPrivileges(ownerId);
    }
    else
    {
      this.setUserDefaultPermissions(ownerId,"No");
      try {
        cvdl.setSql("authorization.deletedefaultpermissions");
        cvdl.setInt(1, ownerId);
        cvdl.executeUpdate();

        cvdl.clearParameters();
        cvdl.setSql("authorization.insertdefaultpermissions");

        if (view != null) {
          for (int i = 0; i < view.length; i++) {
            insertDefaultPermissions(view[i], ownerId,
                                     ModuleFieldRightMatrix.VIEW_RIGHT, cvdl);
          }
        }

        if (modify != null) {
          for (int i = 0; i < modify.length; i++) {
            insertDefaultPermissions(modify[i], ownerId,
                                     ModuleFieldRightMatrix.UPDATE_RIGHT, cvdl);
          }
        }

        if (delete != null) {
          for (int i = 0; i < delete.length; i++) {
            insertDefaultPermissions(delete[i], ownerId,
                                     ModuleFieldRightMatrix.DELETE_RIGHT, cvdl);
          }
        }
      }
      catch (Exception e) {
        logger.error(
            "[Exception][AuthorizationEJB.saveDefaultPermissions] Exception Thrown: " ,
            e);
        throw new AuthorizationException(AuthorizationException.INVALID_DATA,
                                         "Unknown error occured");
      }
      finally {
        cvdl.destroy();
        cvdl = null;
      }
    }
  }   // end saveDefaultPermissions() method

  public HashMap getRecordPermission(String recordType, int recordId) throws AuthorizationException
  {
    HashMap retMap = null;
    Vector viewVect = new Vector();
    Vector updateVect = new Vector();
    Vector deleteVect =  new Vector();

    if(recordType == null ||  recordType.length() == 0)
      throw new AuthorizationException(AuthorizationException.INVALID_DATA,"RecordType not provided");
    if(recordId <= 0)
      throw new AuthorizationException(AuthorizationException.INVALID_DATA,"RecordID < 0");

    CVDal cvdl = new CVDal(dataSource);

    try
    {
      cvdl.setSql("authorization.getrecordpermission");
      cvdl.setString(1,recordType);
      cvdl.setInt(2,recordId);
      Collection col = cvdl.executeQuery();
      Iterator it = col.iterator();


      while(it.hasNext())
      {
        if(null == retMap)
          retMap = new HashMap();
        HashMap dbVal = (HashMap)it.next();

        int pl = ((Number)(dbVal.get("privilegelevel"))).intValue();
        if(pl==ModuleFieldRightMatrix.VIEW_RIGHT)
          viewVect.add(dbVal.get("individualid"));
        else if(pl==ModuleFieldRightMatrix.UPDATE_RIGHT)
          updateVect.add(dbVal.get("individualid"));
        else if(pl==ModuleFieldRightMatrix.DELETE_RIGHT)
          deleteVect.add(dbVal.get("individualid"));
      }

      if (retMap != null)
      {
        retMap.put("VIEW",viewVect);
        retMap.put("UPDATE",updateVect);
        retMap.put("DELETE",deleteVect);
      }
    }

    catch(Exception e)
    {
      logger.error("[Exception][AuthorizationEJB.getRecordPermission] Exception Thrown: ",e);
      throw new AuthorizationException(AuthorizationException.INVALID_DATA, "Unknown error occured");
    } finally
    {
      cvdl.destroy();
      cvdl = null;
    }
    return retMap;
  }

  /**
   * Returns the record permission value for one user, for one record only.
   * @param indId  The user whose permissions we are asking about.
   * @param moduleName The name of the module that the record we are asking about is in.
   * @param recordId The ID of the record which we are asking about.
   * @return int representation of the permission value for this user for this record.
   */
  public int getRecordPermission(int indId, String moduleName, int recordId) throws AuthorizationException
  {
    CVDal cvdl = new CVDal(dataSource);

    int retVal = 0;

    try
    {
      String tableName = null;
      String ownerField = null;
      String primaryKeyField = null;

      int owner = 0;

      cvdl.setSql("authorization.getmoduletableowner");
      cvdl.setString(1,moduleName);

      Collection col = cvdl.executeQuery();
      Iterator it = col.iterator();
      if (it.hasNext())
      {
        HashMap hm = (HashMap)it.next();
        tableName = (String)hm.get("primarytable");
        ownerField = (String)hm.get("ownerfield");
        primaryKeyField = (String)hm.get("primarykeyfield");
      }else{
        // if entry for module not foound then return false
        retVal = ModuleFieldRightMatrix.NONE_RIGHT;
      }

      cvdl.clearParameters();

      if ((ownerField != null) && (tableName != null) && (primaryKeyField !=null))
      {
      // get the owner of the record
      String tempSQL = "select " + ownerField + " from " + tableName + " where " + primaryKeyField + "=" + recordId;

      cvdl.setSqlQuery(tempSQL);
      col = cvdl.executeQuery();
      it = col.iterator();

      if (it.hasNext())
      {
        HashMap hashMap = (HashMap) it.next();

        //Number owner = (Number) hashMap.get(ownerField);
        Collection colSet = hashMap.values();
        Iterator itc = colSet.iterator();

          while (itc.hasNext())
          {
          Number fldVal = (Number) (itc.next());
            if (fldVal.intValue() == indId)
            {
            retVal = ModuleFieldRightMatrix.DELETE_RIGHT;
            break;
          }
        }

        /*
                 Long owner = (Long)(((HashMap)it.next()).get(ownerField));
                 if (owner.intValue() == indId)
                 {
          // user is the owner
          retVal =  ModuleFieldRightMatrix.DELETE_RIGHT;
                 }
         */
        //else
      }
      }

      // check for public field
      // I am commenting the Bottom Code because getRecordFromPublic needs the modulename and not the moduleid.
      //String moduleid = this.getModuleIdByModuleName(moduleName);
      if (this.getRecordFromPublic(moduleName,recordId).equals("Yes"))
      {
        retVal = ModuleFieldRightMatrix.UPDATE_RIGHT;
      }


        if(retVal==0)
        {
          // if user not owner then see if he has right
          cvdl.setSql("authorization.getuserrecordpermission");
          cvdl.setString(1,moduleName);
          cvdl.setInt(2,recordId);
          cvdl.setInt(3,indId);

          col = cvdl.executeQuery();
          it = col.iterator();

        if (it.hasNext())
        {
            retVal = ((Number)(((HashMap)it.next()).get("privilegelevel"))).intValue();
        }else{
          if((ownerField != null) && (tableName != null) && (primaryKeyField !=null))
          {
            cvdl.clearParameters();
            String tempSQL = "select " + ownerField + " from " + tableName + " where " + primaryKeyField + "=" + recordId;
            cvdl.setSqlQuery(tempSQL);
            col = cvdl.executeQuery();
            if(col != null && col.size() != 0){
                it = col.iterator();

                owner = ((Number)(((HashMap)it.next()).get("Owner"))).intValue();

                cvdl.clearParameters();
                cvdl.setSql("authorization.getuserdefaultrecordpermission");
                cvdl.setInt(1, owner);
                cvdl.setInt(2, indId);

                col = cvdl.executeQuery();
                it = col.iterator();

                if (it.hasNext())
                {
                  retVal = ((Number)(((HashMap)it.next()).get("PrivilegLevel"))).intValue();
                }else{
                  retVal = ModuleFieldRightMatrix.NONE_RIGHT;
                }
              }
          }else{
              retVal = ModuleFieldRightMatrix.NONE_RIGHT;
            }
          }
      }else{
             retVal = ModuleFieldRightMatrix.NONE_RIGHT;
          }
    }catch(Exception e){
      logger.error("[Exception][AuthorizationEJB.getRecordPermission(): " , e);
      throw new AuthorizationException(AuthorizationException.INVALID_DATA, "Unknown error occured");
    }finally{
      cvdl.destroy();
      cvdl = null;
          }
    return retVal;
  }   // end getRecordPermission() method


  public HashMap getDefaultRecordPermission(int uid) throws AuthorizationException
  {
    HashMap retMap = new HashMap();

    Vector viewVect = new Vector();
    Vector updateVect = new Vector();
    Vector deleteVect =  new Vector();

    CVDal cvdl = new CVDal(dataSource);

    try
    {
      cvdl.setSql("authorization.getdefaultrecordpermission");
      cvdl.setInt(1,uid);

      Collection sqlResults = cvdl.executeQuery();
      if (sqlResults != null){
      Iterator iter = sqlResults.iterator();

      while (iter.hasNext())
      {
      HashMap sqlRow = (HashMap)iter.next();

      int pl = ((Number)(sqlRow.get("PrivilegeLevel"))).intValue();

      if (pl == ModuleFieldRightMatrix.VIEW_RIGHT)
      {
        viewVect.add(sqlRow.get("IndividualId"));
      }else if(pl==ModuleFieldRightMatrix.UPDATE_RIGHT){
        updateVect.add(sqlRow.get("IndividualId"));
      }else if(pl==ModuleFieldRightMatrix.DELETE_RIGHT){
        deleteVect.add(sqlRow.get("IndividualId"));
      }
      }   // end while (iter,hasNext()

      if (retMap != null)
      {
      retMap.put("VIEW",   viewVect);
      retMap.put("UPDATE", updateVect);
      retMap.put("DELETE", deleteVect);
        }
    }
    }catch(Exception e){
      logger.error("[Exception][AuthorizationEJB.getRecordPermission] Exception Thrown: " , e);
      throw new AuthorizationException(AuthorizationException.INVALID_DATA, "Unknown error occured");
    }finally{
      cvdl.destroy();
      cvdl = null;
    }
    return(retMap);
  }   // end getDefaultRecordPermission() method






  public HashMap getDefaultPermissions(int ownerId) throws AuthorizationException
  {
    HashMap retMap = null;

    Vector viewVect = new Vector();
    Vector updateVect = new Vector();
    Vector deleteVect =  new Vector();

    CVDal cvdl = new CVDal(dataSource);

    try
    {
      cvdl.setSql("authorization.getdefaultpermissions");
      cvdl.setInt(1, ownerId);
      Collection col = cvdl.executeQuery();

      Iterator it = col.iterator();

      while (it.hasNext())
      {
        if (null == retMap)
        {
          retMap = new HashMap();
        }
        HashMap dbVal = (HashMap)it.next();

        int pl = ((Number)(dbVal.get("PrivilegeLevel"))).intValue();

        if (pl==ModuleFieldRightMatrix.VIEW_RIGHT)
        {
          viewVect.add(dbVal.get("IndividualId"));
        }else if (pl==ModuleFieldRightMatrix.UPDATE_RIGHT){
          updateVect.add(dbVal.get("IndividualId"));
        }else if (pl==ModuleFieldRightMatrix.DELETE_RIGHT){
          deleteVect.add(dbVal.get("IndividualId"));
        }
      }

      if (retMap != null)
      {
        retMap.put("VIEW",viewVect);
        retMap.put("UPDATE",updateVect);
        retMap.put("DELETE",deleteVect);
      }
    }catch(Exception e){
      logger.error("[Exception][AuthorizationEJB.getDefaultPreferences] Exception Thrown: ",e);
      throw new AuthorizationException(AuthorizationException.INVALID_DATA, "Unknown error occured");
    }finally{
      cvdl.destroy();
      cvdl = null;
    }
    return retMap;
  }   // end getDefaultPermissions() method


  /**
   * Answers the question "can the user do this operation on this record?".
   * Returns true if the given user can perform the given operation type
   * on the given recordID of the given modulename. Returns false otherwise
   *
   * @param indId The IndividualID of the user who we are asking about
   * @param moduleName The module name String of the module which the record is associated with
   * @param recordId The recordID of the record we are asking about
   * @param privilegeLevel The privilege level ID that we are asking if the user can perform on the given record (10=Delete, 20=Update, 30=View, 40=None)
   * @return boolean - true for "Yes", false for "No"
   */
  public boolean canPerformRecordOperation(int indId, String moduleName, int recordId, int privilegeLevel) throws AuthorizationException
  {

    CVDal cvdl = new CVDal(dataSource);
    boolean retVal = false;

    try
    {
      if (isUserCustomerOrAdministrator(cvdl, indId))
      {
        return true;
      }
      String tableName = null;
      String ownerField = null;
      String primaryKeyField = null;

      cvdl.setSql("authorization.getmoduletableowner");
      cvdl.setString(1,moduleName);
      Collection col = cvdl.executeQuery();

      // entry for this module found
      Iterator it = col.iterator();
      if (it.hasNext())
      {
        HashMap hm = (HashMap)it.next();
        tableName = (String)hm.get("primarytable");
        ownerField = (String)hm.get("ownerfield");
        primaryKeyField = (String)hm.get("primarykeyfield");
      }else{
        // if entry for module not found then return false
        retVal = false;
      }

      cvdl.setSqlQueryToNull();

      // get the owner of the record
      String tempSQL = "select " + ownerField + " from " + tableName + " where " + primaryKeyField + "=" + recordId;
      cvdl.setSqlQuery(tempSQL);
      col = cvdl.executeQuery();

      it = col.iterator();
      if (it.hasNext())
      {
        HashMap hashMap = (HashMap) it.next();
        //Number owner = (Number) hashMap.get(ownerField);
        Collection colSet = hashMap.values();

        Iterator itc = colSet.iterator();
        while (itc.hasNext())
        {
          Number fldVal = (Number)(itc.next());
          if (fldVal.intValue() == indId)
          {
            retVal =  true;
            break;
          }
        }

        if (retVal == false && privilegeLevel != 10)
        {
          // if user is not the owner, then see if the record is public
          cvdl.setSqlQueryToNull();
          cvdl.setSqlQuery("SELECT p.recordid, p.moduleid FROM publicrecords p LEFT JOIN module m ON (p.moduleid=m.moduleid) WHERE p.recordid=? AND m.name=?");
          cvdl.setInt(1, recordId);
          cvdl.setString(2, moduleName);
          Collection sqlResults = cvdl.executeQuery();

          if (sqlResults != null)
          {
            Iterator sqlIter = sqlResults.iterator();
            if (sqlIter.hasNext())
            {
              retVal = true;
            }
          }
        }

        if (retVal == false)
        {
          // if user not owner then see if he has right
          cvdl.setSqlQueryToNull();
          cvdl.setSql("authorization.getuserrecordpermission");
          cvdl.setString(1,moduleName);
          cvdl.setInt(2,recordId);
          cvdl.setInt(3,indId);
          col = cvdl.executeQuery();

          it = col.iterator();
          if (it.hasNext())
          {
            HashMap recordAuth = (HashMap)it.next();
            Number pl = (Number)recordAuth.get("privilegelevel");
            if (pl.intValue() <= privilegeLevel)
            {
              retVal = true;
            }
          }else{
            retVal = false;
          }
        }   // end if (retVal == false)

      }else{
        retVal = false;
      }
    }catch(Exception e){
      logger.error("[Exception][AuthorizationEJB.canPerformRecordOperation] Exception Thrown: ",e);
      throw new AuthorizationException(AuthorizationException.INVALID_DATA, "Unknown error occured");
    }finally{
      cvdl.destroy();
      cvdl = null;
    }
    return retVal;
  }   // end canPerformRecordOperation()


  public void setAuthorizationType(HashMap authFields)
  {

    CVDal dl = new CVDal(dataSource);

    try
    {
      // INSERT INTO `authorizationsettings`  (userAuthType, server, port, username, password, usernameField, passwordField, authField) values(?, ?, ?, ?, ?, ?, ?, ?)
        dl.setSql("administration.configuration.setauthorizationsettings");

      dl.setString(1,(String)authFields.get("userAuthType"));
      dl.setString(2,(String)authFields.get("server"));
      dl.setString(3,(String)authFields.get("port"));
      dl.setString(4,(String)authFields.get("username"));
      dl.setString(5,(String)authFields.get("password"));
      dl.setString(6,(String)authFields.get("usernameField"));
      dl.setString(7,(String)authFields.get("passwordField"));
      dl.setString(8,(String)authFields.get("authField"));

      dl.executeUpdate();
    }
    catch(Exception e)
    {
      logger.error("[Exception][AuthorizationEJB.setAuthorizationType] Exception Thrown: ",e);
    }
    finally
    {
      dl.destroy();
      dl = null;
    }

  }


  public HashMap getAuthorizationType()
  {
    HashMap authFields = new HashMap();

    CVDal dl = new CVDal(dataSource);

    try
    {
      // SELECT * FROM `authorizationsettings`
      dl.setSql("administration.configuration.getauthorizationsettings");

      Collection  col  = (Collection)dl.executeQuery();
      Iterator it = col.iterator();

      if (col != null)
      {
        Object obj;

        while (it.hasNext())
        {
          obj = it.next();
          if ( obj != null )
          {
            HashMap hm  = (HashMap)obj;
            authFields.put("userAuthType", (String)hm.get("userAuthType"));
            authFields.put("server", (String)hm.get("server"));
            authFields.put("port", (String)hm.get("port"));
            authFields.put("username", (String)hm.get("username"));
            authFields.put("password", (String)hm.get("password"));
            authFields.put("usernameField", (String)hm.get("usernameField"));
            authFields.put("passwordField", (String)hm.get("passwordField"));
            authFields.put("authField", (String)hm.get("authField"));

          }
        }
      }


    }
    catch(Exception e)
    {
      logger.error("[Exception][AuthorizationEJB.getAuthorizationType] Exception Thrown: ",e);
    }
    finally
    {
      dl.destroy();
      dl = null;
    }

    return authFields;
  }

  public ValueListVO getSecurityProfileList(int individualId, ValueListParameters parameters)
  {
    ArrayList list = new ArrayList();
    boolean applyFilter = false;
    CVDal cvdl = new CVDal(this.dataSource);
    try {
      String filter = parameters.getFilter();
      if (filter != null && filter.length() > 0) {
        String str = "CREATE TEMPORARY TABLE securityProfileListfilter " + filter;
        cvdl.setSqlQuery(str);
        cvdl.executeUpdate();
        cvdl.setSqlQueryToNull();
        applyFilter = true;
      }
      int numberOfRecords = 0;
      String str = "SELECT COUNT(*) AS count FROM securityprofile";
      cvdl.setSqlQuery(str);
      Collection countCollection = cvdl.executeQuery();
      cvdl.setSqlQueryToNull();
      Iterator i = countCollection.iterator();
      if (i.hasNext()) {
        HashMap row = (HashMap)i.next();
        Number count = (Number)row.get("count");
        numberOfRecords = count.intValue();
      }
      parameters.setTotalRecords(numberOfRecords);
      String select = "SELECT sp.profileId, sp.profilename, count(usp.individualId) AS numberOfusers ";
      StringBuffer from = new StringBuffer("FROM securityprofile AS sp LEFT OUTER JOIN usersecurityprofile usp ON sp.profileId = usp.profileId ");
      StringBuffer where = new StringBuffer("WHERE 1=1 ");
      String groupBy = "GROUP BY sp.profileId ";
      String orderBy = "ORDER BY " + String.valueOf(parameters.getSortColumn() + " " + parameters.getSortDirection());
      String limit = parameters.getLimitParam();
      StringBuffer query = new StringBuffer();
      query.append(select);
      query.append(from);
      if (applyFilter) {
        query.append(", securityProfileListFilter AS lf ");
      }
      query.append(where);
      if (applyFilter) {
        query.append("AND u.userId = lf.userId ");
      }
      query.append(groupBy);
      query.append(orderBy);
      query.append(limit);
      cvdl.setSqlQuery(query.toString());
      list = cvdl.executeQueryList(1);
      if (numberOfRecords < 1) {
        parameters.setTotalRecords(list.size());
      }
      if (applyFilter) {
        cvdl.setSqlQueryToNull();
        cvdl.setSqlQuery("DROP TABLE securityProfileListFilter");
        cvdl.executeUpdate();
      }
    } finally {
      cvdl.destroy();
      cvdl = null;
    }
    return new ValueListVO(list, parameters);
  }

  /**
   *
   * @param indID
   * @param hashmap
   * @return
   */
  public SecurityProfileList getSecurityProfileList(int indID, HashMap hashmap)
  {
    Integer intStart = (Integer)hashmap.get("startATparam");
    Integer intEnd = (Integer)hashmap.get("EndAtparam");
    String strSearch = (String)hashmap.get("searchString");
    String strSortMem = (String)hashmap.get("sortmem");
    Character chrSortType = (Character)hashmap.get("sortType");
    char charSort = chrSortType.charValue();
    int intStartParam = intStart.intValue();
    int intEndParam = intEnd.intValue();
    int beginIndex = Math.max(intStartParam - 100, 1);
    int endindex = intEndParam + 100;
    SecurityProfileList spList = new SecurityProfileList();
    spList.setSortMember(strSortMem);
    CVDal cvdl = new CVDal(dataSource);
    Collection colList = null;
    if (strSearch != null && strSearch.startsWith("ADVANCE:")) {} else {
      String sortType = "ASC";
      if (charSort == 'A')
        sortType = "ASC";
      else
        sortType = "DESC";
      cvdl.setDynamicQuery("securityprofile.getsecurityprofilelist", sortType, strSortMem, beginIndex, endindex);
      colList = cvdl.executeQuery();
      cvdl.clearParameters();
      cvdl.setSql("securityprofile.allsecurityprofilecount");
      cvdl.executeQuery();
      Collection count = cvdl.executeQuery();
      Iterator itCount = count.iterator();
      HashMap hmx = (HashMap)itCount.next();
      Integer endCount = (Integer)hmx.get("allsecurityprofilecount");
      cvdl.clearParameters();
      int totalCount = endCount.intValue();
      spList.setTotalNoOfRecords(totalCount);
    }
    if (colList != null) {
      Iterator it = colList.iterator();
      int i = 0;
      while (it.hasNext()) {
        //ALLSQL.put("securityprofile.getsecurityprofilelist","select
        // sp.profileid ProfileID,sp.profilename
        // ProfileName,count(usp.individualid) NoOfUsers from
        // usersecurityprofile usp, securityprofile sp where sp.profileid =
        // usp.profileid group by usp.profileid order by '"+ sortFFMember +"'
        // "+sortType+" LIMIT "+(beginIndex-1)+ ", "+(endIndex+1));
        i++;
        HashMap hm = (HashMap)it.next();
        int spID = ((Long)hm.get("ProfileID")).intValue();
        try {
          IntMember intProfleID = new IntMember("ProfileID", spID, 10, "", 'T', false, 10);
          StringMember strProfileName = null;
          IntMember intUserCount = null;
          if ((hm.get("ProfileName") != null))
            strProfileName = new StringMember("ProfileName", (String)hm.get("ProfileName"), 10, "", 'T', true);
          else
            strProfileName = new StringMember("ProfileName", null, 10, "", 'T', true);
          if ((hm.get("NoOfUsers") != null))
            if (hm.get("NoOfUsers") instanceof Long)
              intUserCount = new IntMember("NoOfUsers", ((Long)hm.get("NoOfUsers")).intValue(), 10, "", 'T', false, 10);
            else
              intUserCount = new IntMember("NoOfUsers", ((Integer)hm.get("NoOfUsers")).intValue(), 10, "", 'T', false, 10);
          else
            intUserCount = new IntMember("NoOfUsers", 0, 10, "", 'T', false, 10);
          SecurityProfileListElement splistelement = new SecurityProfileListElement(spID);
          splistelement.put("ProfileID", intProfleID);
          splistelement.put("ProfileName", strProfileName);
          splistelement.put("NoOfUsers", intUserCount);
          StringBuffer stringbuffer = new StringBuffer("00000000000");
          stringbuffer.setLength(11);
          String s3 = (new Integer(i)).toString();
          stringbuffer.replace(stringbuffer.length() - s3.length(), stringbuffer.length(), s3);
          String s4 = stringbuffer.toString();
          spList.put(s4, splistelement);
        } catch (Exception e) {
          logger.error("[Exception][AuthorizationEJB.getSecurityProfileList] Exception Thrown: ", e);
        }
      }
    }
    spList.setListType("SecurityProfile");
    spList.setBeginIndex(beginIndex);
    spList.setEndIndex(spList.size());
    return spList;
  }


  private void insertSecurityProfile(int securityProfileId, ModuleFieldRightMatrix mfrx, CVDal cvdl)
  {
    TreeMap moduleRight = mfrx.getModuleRights();
    Set moduleIds = moduleRight.keySet();
    Iterator it = moduleIds.iterator();
    int right;
    while (it.hasNext())
    {
      Integer moduleId = (Integer)it.next();
      HashMap moduleInfo = (HashMap)moduleRight.get(moduleId);
      Integer rightInteger = (Integer)moduleInfo.get("rights");
      String moduleName = (String)moduleInfo.get("name");
      if (rightInteger == null)
      { // if there isn't a rights value there is no record to insert
        continue;
      }
      right = rightInteger.intValue();
      cvdl.clearParameters();
      // INSERT INTO moduleauthorisation (profileid,privilegelevel,moduleid) values (?,?,?)
      cvdl.setSql("authorization.insertmoduleauthorization");
      //no use of this field cause an entry in this table means
      // the user can see this the module
      cvdl.setInt(1, securityProfileId);
      cvdl.setInt(2, right);
      cvdl.setInt(3, moduleId.intValue());
      cvdl.executeUpdate();

      HashMap fieldHashMap = mfrx.getFieldRights(moduleName);

      if (fieldHashMap != null)
      {
        Iterator fieldKeys = fieldHashMap.keySet().iterator();
        while (fieldKeys.hasNext())
        {
          String fieldName = (String)fieldKeys.next();
          Integer privilegeInteger = (Integer)fieldHashMap.get(fieldName);
          if (privilegeInteger == null)
          {
            continue;
          }
          int privilege = privilegeInteger.intValue();
          // INSERT INTO fieldauthorisation (profileid,privilegelevel,fieldid)
          // select ?,?,b.mapid as fieldid from modulefieldmapping b
          // where a.moduleid=b.moduleid and a.name=? and b.name=?"
          cvdl.setSql("authorization.insertfieldauthorization");
          cvdl.setInt(1, securityProfileId);
          cvdl.setInt(2, privilege);
          cvdl.setString(3, moduleName);
          cvdl.setString(4, fieldName);
          cvdl.executeUpdate();
        }
      }
    }
  }




  private void insertRecordPermission(int indId, String recordType, int recordId, int privilege, CVDal cvdl)
  {
    //cvdl.clearParameters();
    cvdl.setInt(1,indId);
    cvdl.setInt(2,recordId);
    cvdl.setInt(3,privilege);
    cvdl.setString(4,recordType);

    cvdl.executeUpdate();
  }

  private void insertDefaultPermissions(int indId, int ownerId, int privilege, CVDal cvdl)
  {
    //cvdl.clearParameters();
    cvdl.setInt(1,ownerId);
    cvdl.setInt(2,indId);
    cvdl.setInt(3,privilege);

    cvdl.executeUpdate();
  }

   public void updateMarketingRecordOwner(String moduleName, int listID, int individualID)
   {
      CVDal cvdl = new CVDal(dataSource);

      try
      {

         Vector retVec = null;
         cvdl.setSqlQuery("SELECT moduleid, name, primarytable, ownerfield, primarykeyfield FROM module WHERE name=?");
         cvdl.setString(1, moduleName);
         Collection col = cvdl.executeQuery();

         Iterator it = col.iterator();
         if (it.hasNext())
         {
            HashMap hm = (HashMap)it.next();
            cvdl.clearParameters();
            cvdl.setSqlQuery("UPDATE " + (String)hm.get("primarytable") + " SET " + (String)hm.get("ownerfield") + "=? WHERE " + "list" + "=?");
            cvdl.setInt(1, individualID);
            cvdl.setInt(2, listID);
            cvdl.executeUpdate();
         }
      }finally{
         cvdl.destroy();
         cvdl = null;
      }
   }


  public void updateOwner(String moduleName, int recordID, int individualID)
  {
    CVDal cvdl = new CVDal(dataSource);

    try
    {

      Vector retVec = null;
      cvdl.setSqlQuery("SELECT moduleid, name, primarytable, ownerfield, primarykeyfield FROM module WHERE name=?");
      cvdl.setString(1, moduleName);
      Collection col = cvdl.executeQuery();

      Iterator it = col.iterator();
      if (it.hasNext())
      {
        HashMap hm = (HashMap)it.next();
        cvdl.clearParameters();
        cvdl.setSqlQuery("UPDATE " + (String)hm.get("primarytable") + " SET " + (String)hm.get("ownerfield") + "=? WHERE " + (String)hm.get("primarykeyfield") + "=?");
        cvdl.setInt(1, individualID);
        cvdl.setInt(2, recordID);
        cvdl.executeUpdate();
      }
    }finally{
      cvdl.destroy();
      cvdl = null;
    }
  }

  public HashMap getOwner(String moduleName, int recordId)
  {
    CVDal cvdl = new CVDal(dataSource);

    try {
      Vector retVec = null;
      String extraUrlParameter ="";
      if(moduleName != null && moduleName.equals("Projects")){
      extraUrlParameter = " AND moduleid != 9 ";
      }
      cvdl.setSqlQuery("select moduleid,name,primarytable,ownerfield,primarykeyfield from module where name='" + moduleName + "'"+extraUrlParameter);
      Collection col = cvdl.executeQuery();
      Iterator it = col.iterator();
      if (it.hasNext()) {
        String pt = "";
        String of = "";
        HashMap hm = (HashMap)it.next();

        if (hm != null) {
          if ((hm.get("primarytable") != null) || (hm.get("ownerfield") != null)) {
            if ((!hm.get("primarytable").equals("")) || (!hm.get("ownerfield").equals(""))) {
              pt = (String)hm.get("primarytable");
              of = (String)hm.get("ownerfield");
            } else {
              return null;
            }
          } else {
            return null;
          }
        } else {
          return null;
        }
        cvdl.clearParameters();
        String selectQuery = "";
        if (moduleName.equals("Tasks")) {
          selectQuery = " select a.owner as id, concat(i.FirstName,' ',i.LastName) as name " + "from activity a, task t, individual i  where i.IndividualID = " + " a.owner and t.activityid = a.activityid and t.activityid=" + recordId;
        } else if (moduleName.equals("Opportunities")) {
          selectQuery = " select a.owner as id, concat(i.FirstName,' ',i.LastName) as name  from activity a, opportunity o, individual i  where i.IndividualID = a.owner and o.activityid = a.activityid and o.opportunityid=" + recordId;
        } else {
          selectQuery = " select " + pt + "." + of + " as id, concat(indowner.FirstName,' ',indowner.LastName) as name " + "from " + pt + ",individual indowner " + " where indowner.IndividualID = " + pt + "." + of + " and " + pt + "." + (String)hm.get("primarykeyfield") + "=" + recordId;
        }
        cvdl.setSqlQuery(selectQuery);
        Collection col1ec = cvdl.executeQuery();
        Iterator it1e = col1ec.iterator();
        if (it1e.hasNext()) {
          return (HashMap)it1e.next();
        }
      } // end if (it.hasNext())
    } catch (Exception e) {
      logger.error("[Exception][AuthorizationEJB] Exception thrown in getOwner(): ", e);
      throw new EJBException(e);
    } finally {
      cvdl.destroy();
      cvdl = null;
    }
    return null;
  } // end getOwner() method


  public HashMap getNoneRightFieldMethod(String moduleName, int individualId)
  {
    HashMap retHm = new HashMap();

    CVDal cvdl = new CVDal(dataSource);

    cvdl.setSql("authorization.getusersecurityprofilefieldselective");
    cvdl.setInt(1,individualId);
    cvdl.setString(2,moduleName);
    cvdl.setInt(3,ModuleFieldRightMatrix.NONE_RIGHT);

    Collection col = cvdl.executeQuery();
    Iterator it = col.iterator();
    if (it.hasNext() )
    {
      while(it.hasNext())
      {
        HashMap tempHm = (HashMap)it.next();
        retHm.put((String)tempHm.get("fieldname"),(String)tempHm.get("methodname"));
      }
    }
    cvdl.destroy();
    return retHm;

  }
  /**
   * @author Kevin McAllister <kevin@centraview.com>
   * This simply sets the target datasource to be used for DB interaction
   * @param ds A string that contains the cannonical JNDI name of the datasource
   */
   public void setDataSource(String ds) {
    this.dataSource = ds;
   }

  /**
   * delete security profile
   */
   public void deleteSecurityProfile(int pID,int indvID)
   {
     CVDal cvdl = new CVDal(dataSource);
    try
    {
    cvdl.setSql("authorization.deletesecurityprofile");
    cvdl.setInt(1,pID);
    cvdl.executeUpdate();

    cvdl.clearParameters();
    cvdl.setSql("authorization.deletemoduleauthorization");
    cvdl.setInt(1,pID);
    cvdl.executeUpdate();

    cvdl.clearParameters();
    cvdl.setSql("authorization.deletefieldauthorization");
    cvdl.setInt(1,pID);
    cvdl.executeUpdate();

    cvdl.clearParameters();
    cvdl.setSql("authorization.deleteusersecurityprofile");
    cvdl.setInt(1,pID);
    cvdl.executeUpdate();

     }finally
    {
      cvdl.destroy();
      cvdl = null;
    }
   }

  public ModuleFieldRightMatrix getBlankFieldRightMatrix(int defaultRights)
  {
    ModuleFieldRightMatrix mfrm = new ModuleFieldRightMatrix();
    CVDal cvdl = new CVDal(this.dataSource);
    try
    {
      cvdl.setSql("authorization.getallmodules");
      Collection col = cvdl.executeQuery();
      Iterator it = col.iterator();
      while (it.hasNext())
      {
        HashMap module = (HashMap)it.next();
        String moduleName = (String)module.get("name");
        Integer moduleId = new Integer(((Number)module.get("moduleid")).intValue());
        Object parentIdReturn = module.get("parentid");
        Integer parentId = null;
        parentId = (parentIdReturn != null) ? new Integer(((Number)parentIdReturn).intValue()) : new Integer(0);
        mfrm.addModule(moduleName, moduleId, parentId);
        mfrm.setModuleRight(moduleId, new Integer(defaultRights));
      }
      cvdl.clearParameters();
      String sql = "select m.name as modulename, fm.name as fieldname from module m, modulefieldmapping fm where m.moduleid = fm.moduleid;";
      cvdl.setSqlQuery(sql);
      col = cvdl.executeQuery();
      it = col.iterator();
      while (it.hasNext())
      {
        HashMap moduleField = (HashMap)it.next();
        String moduleName = (String)moduleField.get("modulename");
        String fieldName = (String)moduleField.get("fieldname");
        mfrm.setFieldRight(moduleName, fieldName, defaultRights);
      }
    }
    finally
    {
      cvdl.clearParameters();
      cvdl.destroy();
      cvdl = null;
    }
    return mfrm;
  }

  /**
   * Removes all records from `pubilcrecords` table which grant
   * the "Pubilc" status on any List Member record from a given
   * Marketing ListID. In essence, this method sets all list
   * member records for a given listID to *NOT* public.
   * @param listID The Marketing List ID for which we are changing
   * member permissions.
   * @return void
   */
  public void deleteMarketingMemberPublicRecords(int listID)
  {
    CVDal cvdl = new CVDal(this.dataSource);
    try
    {
      cvdl.setSqlQuery("DELETE p FROM publicrecords p, individual i WHERE p.recordid=i.individualid AND i.List=? AND p.moduleid=15");
      cvdl.setInt(1, listID);
      cvdl.executeUpdate();
      cvdl.clearParameters();

      cvdl.setSqlQuery("DELETE p FROM publicrecords p, entity e WHERE p.recordid=e.entityid AND e.List=? AND p.moduleid=14");
      cvdl.setInt(1, listID);
      cvdl.executeUpdate();
    }catch(Exception e){
      logger.error("[Exception][AuthorizationEJB] Exception thrown in deleteMarketingMemberPublicRecords(): " , e);
    }finally{
      cvdl.clearParameters();
      cvdl.destroy();
      cvdl = null;
    }
  }   // end deleteMarketingMemberPublicRecords() method

  /**
   * Inserts one record into `pubilcrecords` table for each
   * member record in the given Marketing ListID. In essence,
   * this method sets all list member records for a given listID
   * to be public.
   * @param listID The Marketing List ID for which we are changing
   * member permissions.
   * @return void
   */
  private void insertMarketingMemberPublicRecords(int listID)
  {
    CVDal cvdl = new CVDal(this.dataSource);
    try
    {
      cvdl.setSqlQuery("INSERT INTO publicrecords SELECT individualid, 15 FROM individual WHERE list=? UNION SELECT entityid, 14 FROM entity WHERE list=?");
      cvdl.setInt(1, listID);
      cvdl.setInt(2, listID);
      cvdl.executeUpdate();
    }catch(Exception e){
      logger.error("[Exception][AuthorizationEJB] Exception thrown in insertMarketingMemberPublicRecords(): " , e);
    }finally{
      cvdl.clearParameters();
      cvdl.destroy();
      cvdl = null;
    }
  }   // end insertMarketingMemberPublicRecords() method

  /**
   * This method checks if a user is a Customer or Administrator
   * if so returns true, else returns false.
   * @param cvdl
   * @param individualID
   * @return
   */
  private boolean isUserCustomerOrAdministrator(CVDal cvdl, int individualID)
  {
    cvdl.setSqlQueryToNull();
    // get the user type of the given individual id.
    cvdl.setSql("user.getUserType");
    cvdl.setInt(1, individualID);
    Collection userResults = cvdl.executeQuery();

    String userType = "";
    if (userResults != null)
    {
      Iterator userIter = userResults.iterator();
      while (userIter.hasNext())
      {
        HashMap userRow = (HashMap)userIter.next();
        if (userRow != null) {
          userType = (String)userRow.get("usertype");
          break;
        }
      }
    }

    if (logger.isDebugEnabled()) {
      logger.debug("[isUserCustomerOrAdministrator]: testing individualId: "+individualID
          +", userType: "+userType);
    }
    // now check to see if the user is a Customer
    // or Administrator type user - if so, then
    // return true (Customers don't have security
    // profile settings, and administrators have
    // access to EVERYTHING)
    if (CVUtility.notEmpty(userType))
    {
      if (userType.equals("CUSTOMER")) {
        return(true);
      } else if(userType.equals("ADMINISTRATOR")) {
        return(true);
      }
    }
    return false;
  } // end isUserCustomerOrAdministrator(CVDal cvdl, int individualID)


  /**
   * Process the individualList and EntityList and Set the permission according to the member permission which are set by the user
   *
   * @param individualIDList The collection of new imported individual.
   *
   * @param entityIDList  The collection of new imported entity.
   *
   * @param listID The list which we are importing individual and entity.
   *
   * @throws AuthorizationException Something went terribly wrong.
   */
  public void saveMarketingRecordPermission(ArrayList individualIDList, ArrayList entityIDList, int listID) throws AuthorizationException
  {

  CVDal cvdl = new CVDal(dataSource);
  try
  {
    // Process the ArrayList and collect a String of IndividualIds and entityIDs.
    String indvidualIDs = "";
    if (individualIDList != null){
      int count = individualIDList.size();
      for(int i = 0; i < count; i++){
        String tempRecordID = (String) individualIDList.get(i);
        if (i == (count - 1)){
          indvidualIDs += tempRecordID;
        }// end if (i == count - 1)
        else{
          indvidualIDs += tempRecordID +",";
        }// end of else block
      }// end for(int i = 0; i < count; i++)
    }// end if (individualIDList != null)

    String entityIDs = "";
    if (entityIDList != null){
      int count = entityIDList.size();
      for(int i = 0; i < count; i++){
        String tempRecordID = (String) entityIDList.get(i);
        if (i == (count - 1)){
          entityIDs += tempRecordID;
        }// end if (i == count - 1)
        else{
          entityIDs += tempRecordID +",";
        }// end else for if (i == count - 1)
      }// end for(int i = 0; i < count; i++)
    }// if (entityIDList != null)

    //Collect the Permission of MemberList by passing the ListId and Set the same permission on the new Imported Individual and entity
    HashMap hm = this.getRecordPermission("MarketingList", listID);
    Vector vecview = null;
    Vector vecmodify = null;
    Vector vecdelete = null;

    if (!this.getRecordFromPublic("MarketingList",listID).equalsIgnoreCase("Yes"))
    {
      if (hm != null)
      {
        vecview = (Vector) hm.get("VIEW");
        vecmodify = (Vector) hm.get("UPDATE");
        vecdelete = (Vector) hm.get("DELETE");
      }// end if (hm != null)

      if (vecview != null)
      {
        for (int i = 0; i < vecview.size(); i++)
        {
          int individualID = ((Number) vecview.elementAt(i)).intValue();
          if (!indvidualIDs.equals("")){
            this.insertmarketingRecordPermission(individualID, 15, indvidualIDs, ModuleFieldRightMatrix.VIEW_RIGHT, cvdl, 0);
          }// end if (!indvidualIDs.equals(""))
          if (!entityIDs.equals("")){
            this.insertmarketingRecordPermission(individualID, 14, entityIDs, ModuleFieldRightMatrix.VIEW_RIGHT, cvdl, 1);
          }// end if (!entityIDs.equals(""))
        }// end for (int i = 0; i < vecview.size(); i++)
      }// end if (vecview != null)

      if (vecmodify != null)
      {
        for (int i = 0; i < vecmodify.size(); i++)
        {
          int individualID = ((Number) vecmodify.elementAt(i)).intValue();
          if (!indvidualIDs.equals("")){
            this.insertmarketingRecordPermission(individualID, 15, indvidualIDs, ModuleFieldRightMatrix.UPDATE_RIGHT, cvdl, 0);
          }// end if (!indvidualIDs.equals(""))
          if (!entityIDs.equals("")){
            this.insertmarketingRecordPermission(individualID, 14, entityIDs, ModuleFieldRightMatrix.UPDATE_RIGHT, cvdl, 1);
          }// end if (!entityIDs.equals(""))
        }// end for (int i = 0; i < vecmodify.size(); i++)
      }// end if (vecmodify != null)

      if (vecdelete != null)
      {
        for (int i = 0; i < vecdelete.size(); i++)
        {
          int individualID = ((Number) vecdelete.elementAt(i)).intValue();
          if (!indvidualIDs.equals("")){
            this.insertmarketingRecordPermission(individualID, 15, indvidualIDs, ModuleFieldRightMatrix.DELETE_RIGHT, cvdl, 0);
          }// end if (!indvidualIDs.equals(""))
          if (!entityIDs.equals("")){
            this.insertmarketingRecordPermission(individualID, 14, entityIDs, ModuleFieldRightMatrix.DELETE_RIGHT, cvdl, 1);
          }// end if (!entityIDs.equals(""))
        }// end for (int i = 0; i < vecdelete.size(); i++)
      }// end if (vecdelete != null)

    }// end if (!this.getRecordFromPublic("MarketingList",listID).equalsIgnoreCase("Yes"))
    else{
        this.insertMarketingMemberPublicRecords(indvidualIDs,entityIDs,cvdl);   // recordId = ListID
    }// end else for if (!this.getRecordFromPublic("MarketingList",listID).equalsIgnoreCase("Yes"))

    }catch(Exception e){
      logger.error("[Exception][AuthorizationEJB.saveMarketingRecordPermission] Exception Thrown: ",e);
      throw new AuthorizationException(AuthorizationException.INVALID_DATA, "Unknown error occured");
    }finally{
      cvdl.destroy();
      cvdl = null;
    }
  }

  /**
   * Inserts one record into `pubilcrecords` table for each
   * member record in the given Entity and Individual. In essence,
   * this method sets all list member records for a given set of entity's and individual's
   * to be public.
   *
   * @param indvidualIDs The Individual ID for which we are changing the record permission to public.
   *
   * @param entityIDs The Entity ID for which we are changing the record permission to public.
   *
   * @param cvdl The database connection object which we use for carrying out the update to data
   * member permissions.
   *
   *
   * @return void
   */
  private void insertMarketingMemberPublicRecords(String indvidualIDs, String entityIDs, CVDal cvdl)
  {
    try
    {
    if (!indvidualIDs.equals("")){
      cvdl.setSqlQueryToNull();
      cvdl.setSqlQuery("INSERT INTO publicrecords SELECT individualid, 15 FROM individual WHERE individualid in ("+indvidualIDs+")");
      cvdl.executeUpdate();
      cvdl.clearParameters();
    }// end if (!indvidualIDs.equals(""))

    if (!entityIDs.equals("")){
      cvdl.setSqlQueryToNull();
      cvdl.setSqlQuery("INSERT INTO publicrecords SELECT entityid, 14 FROM entity WHERE entityid in ("+entityIDs+")");
      cvdl.executeUpdate();
      cvdl.clearParameters();
    }// end if (!entityIDs.equals(""))

    }catch(Exception e){
      logger.error("[Exception][AuthorizationEJB] Exception thrown in insertMarketingMemberPublicRecords(): " , e);
    }
  }   // end insertMarketingMemberPublicRecords() method

  /**
   * Inserts one record into `recordauthorisation` table for each
   * member record in the given Entity and Individual. In essence,
   * this method sets all list member records for a given set of entity's and individual's
   * to be View/Modified/Deleted
   *
   * @param indId The Individual's we will set permission for the individual.
   *
   * @param recordType The recordType its the module's id for which we are inserting this entity/Individual
   *
   * @param recordId The recordId its a collection of entity or individual seperated by comma.
   *
   * @param privilege The privilege which we are going to set on the entity or individual like view/Modify/Delete
   *
   * @param cvdl The database connection object which we use for carrying out the update to data.
   *
   * @param flag The flag to check we are inserting record for individual or entity on basis of value.
   *
   * @return void
   */
  private void insertmarketingRecordPermission(int indId, int recordType, String recordId, int privilege, CVDal cvdl, int flag)
  {
    try{
    cvdl.setSqlQueryToNull();
    if (flag == 0){
      cvdl.setSqlQuery("insert into recordauthorisation(individualid,recordid,recordtypeid,privilegelevel) select ?,individualid,?,?  from individual where individualid in ("+recordId+")");
    }// end if (flag == 0)
    else{
      cvdl.setSqlQuery("insert into recordauthorisation(individualid,recordid,recordtypeid,privilegelevel) select ?,entityid,?,?  from entity where entityid in ("+recordId+")");
    }// end else if (flag == 0)

    cvdl.setInt(1,indId);
    cvdl.setInt(2,recordType);
    cvdl.setInt(3,privilege);
    cvdl.executeUpdate();
    cvdl.clearParameters();
  }// end of try Block
  catch(Exception e){
    e.printStackTrace();
  }// end of catch Block
  } // end insertmarketingRecordPermission()

}
TOP

Related Classes of com.centraview.administration.authorization.AuthorizationEJB

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.