Package com.centraview.note

Source Code of com.centraview.note.NoteEJB

/*
* $RCSfile: NoteEJB.java,v $    $Revision: 1.4 $  $Date: 2005/09/01 15:31:06 $ - $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.note;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;

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

import org.apache.log4j.Logger;

import com.centraview.administration.authorization.AuthorizationLocal;
import com.centraview.administration.authorization.AuthorizationLocalHome;
import com.centraview.administration.authorization.ModuleFieldRightMatrix;
import com.centraview.common.AuthorizationFailedException;
import com.centraview.common.CVDal;
import com.centraview.common.CVUtility;
import com.centraview.common.Constants;
import com.centraview.common.DateMember;
import com.centraview.common.EJBUtil;
import com.centraview.common.IntMember;
import com.centraview.common.StringMember;
import com.centraview.contact.helper.ContactHelperLocal;
import com.centraview.contact.helper.ContactHelperLocalHome;
import com.centraview.cvattic.CvAtticLocal;
import com.centraview.cvattic.CvAtticLocalHome;
import com.centraview.valuelist.ValueListParameters;
import com.centraview.valuelist.ValueListVO;

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

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

  public void ejbCreate()
  {}

  public void ejbRemove()
  {}

  public void ejbActivate()
  {}

  public void ejbPassivate()
  {}

  /**
   * Adds a new note to the database, sets the appropriate permissions on the
   * new record.
   * @param individualID The <code>individualID</code> of the user who is
   *          adding the note.
   * @param noteVO A NoteVO object representing the note to be added to the
   *          database.
   * @return int The new note ID
   * @throws NoteException
   */
  public int addNote(int individualID, NoteVO noteVO) throws NoteException, AuthorizationFailedException
  {
    if (!CVUtility.isModuleVisible("Notes", individualID, this.dataSource)) {
      throw new AuthorizationFailedException("Notes - addNote");
    }

    CVDal cvdal = new CVDal(dataSource);

    int noteID = 0;

    try {
      if (noteVO == null) {
        throw new NoteException(NoteException.INVALID_DATA, "Cannot add note. NoteVO is empty.");
      }

      if ((noteVO.getTitle() == null) || (noteVO.getTitle().length() == 0)) {
        throw new NoteException(NoteException.INVALID_DATA, "Title is Empty");
      }

      if (noteVO.getPriority() == null) {
        noteVO.setPriority(NoteVO.NP_MEDIUM);
      }

      if (noteVO.getCreatedBy() == 0) {
        noteVO.setCreatedBy(individualID);
      }

      if (noteVO.getOwner() == 0) {
        noteVO.setOwner(individualID);
      }

      cvdal.setSql("note.insertnote");
      cvdal.setString(1, noteVO.getTitle());
      cvdal.setString(2, noteVO.getDetail());
      cvdal.setString(3, noteVO.getPriority());
      cvdal.setInt(4, noteVO.getOwner());
      cvdal.setInt(5, noteVO.getRelateEntity());
      cvdal.setInt(6, noteVO.getRelateIndividual());
      cvdal.setInt(7, noteVO.getCreatedBy());

      cvdal.executeUpdate();

      noteID = cvdal.getAutoGeneratedKey();

      int projectID = noteVO.getProjectId();
      if (projectID != 0) {
        cvdal.setSqlQueryToNull();
        cvdal.setSqlQuery("insert into projectlink values(?,?,?)");
        cvdal.setInt(1, projectID);
        cvdal.setInt(2, 5);
        cvdal.setInt(3, noteID);
        cvdal.executeUpdate();
      }

      // For the purposes of Sync (CompanionLink), we need to have
      // a hack. :-( Basically, we're going to store Note data in two
      // places, causing redundant data in our database. We'll be
      // copying ALL notes for related to a single individual into
      // one record in the "syncnote" table;
      this.updateSyncNotes(noteVO, cvdal);

      // set default permissions on the new note
      InitialContext ic = CVUtility.getInitialContext();
      AuthorizationLocalHome authorizationHome = (AuthorizationLocalHome) ic.lookup("local/Authorization");
      AuthorizationLocal authorizationLocal = authorizationHome.create();
      authorizationLocal.setDataSource(dataSource);

      authorizationLocal.saveCurrentDefaultPermission("Notes", noteID, individualID);
    } catch (Exception e) {
      logger.error("[addNote]: Exception", e);
      throw new NoteException(NoteException.INSERT_FAILED, "Failed in note ejb while adding note");
    } finally {
      cvdal.destroy();
      cvdal = null;
    }

    return noteID;
  } // end addNote(int,NoteVO) method

  /**
   * Returns a fully-populated NoteVO object representing the note record that
   * matches the given <code>noteID</code>.
   * @param individualID The <code>individualID</code> of the user who is
   *          requesting the information.
   * @param noteID The ID of the note being requested.
   * @return A fully-populated NoteVO object representing the note record.
   * @throws NoteException
   */
  public NoteVO getNote(int individualID, int noteID) throws NoteException, AuthorizationFailedException
  {
    if (!CVUtility.canPerformRecordOperation(individualID, "Notes", noteID, ModuleFieldRightMatrix.VIEW_RIGHT, this.dataSource)) {
      throw new AuthorizationFailedException("User cannot access Notes module.");
    }

    NoteVO noteVO;

    CVDal cvdal = new CVDal(this.dataSource);

    try {
      cvdal.setSql("note.getnote");
      cvdal.setInt(1, noteID);

      Collection col = cvdal.executeQuery();

      if (col == null) {
        throw new NoteException(NoteException.GET_FAILED, "Could not find Note #" + noteID);
      }

      Iterator it = col.iterator();

      if (!it.hasNext()) {
        throw new NoteException(NoteException.GET_FAILED, "Could not find Note #" + noteID);
      }

      HashMap hm = (HashMap) it.next();

      noteVO = new NoteVO();
      noteVO.setNoteId(((Number) hm.get("NoteID")).intValue());
      noteVO.setTitle((String) hm.get("Title"));
      noteVO.setDetail((String) hm.get("Detail"));
      if (hm.get("priority") != null) {
        noteVO.setPriority((String) hm.get("priority"));
      }

      if (hm.get("Owner") != null) {
        noteVO.setOwner(((Number) hm.get("Owner")).intValue());
      }

      if (hm.get("Creator") != null) {
        noteVO.setCreatedBy(((Number) hm.get("Creator")).intValue());
      }

      if (hm.get("UpdatedBy") != null) {
        noteVO.setModifiedBy(((Number) hm.get("UpdatedBy")).intValue());
      }

      // Get Relations
      InitialContext ic = CVUtility.getInitialContext();
      ContactHelperLocalHome home = (ContactHelperLocalHome) ic.lookup("local/ContactHelper");
      ContactHelperLocal remote = home.create();
      remote.setDataSource(this.dataSource);

      if (hm.get("RelateEntity") != null) {
        int entityID = ((Long) hm.get("RelateEntity")).intValue();
        String entityName = remote.getEntityName(entityID);
        noteVO.setRelateEntity(entityID);
        noteVO.setRelateEntityName(entityName);
      }

      if (hm.get("RelateIndividual") != null) {
        int indvID = ((Long) hm.get("RelateIndividual")).intValue();
        String individualName = remote.getIndividualName(indvID);
        noteVO.setRelateIndividual(indvID);
        noteVO.setRelateIndividualName(individualName);
      }
      noteVO.setCreatedOn((Timestamp) hm.get("DateCreated"));
      noteVO.setModifiedOn((Timestamp) hm.get("DateUpdated"));
      noteVO.fillAuditDetails(this.dataSource);
    } catch (Exception e) {
      logger.error("[getNote]: Exception", e);
      throw new NoteException(NoteException.GET_FAILED, "Failed in NoteEJB while getting Note");
    } finally {
      cvdal.destroy();
      cvdal = null;
    }
    return noteVO;
  } // end getNote(int,int) method

  /**
   * Updates a given note record in the database. The note to be updated is
   * determined by the NoteVO object that is passed in.
   * @param individualID The <code>individualID</code> of the user who is
   *          updating the record.
   * @param noteVO A fully populated <code>NoteVO</code> object representing
   *          the note to be updated.
   * @return void
   * @throws NoteException
   */
  public void updateNote(int individualID, NoteVO noteVO) throws NoteException, AuthorizationFailedException
  {
    if (!CVUtility.canPerformRecordOperation(individualID, "Notes", noteVO.getNoteId(), ModuleFieldRightMatrix.UPDATE_RIGHT, this.dataSource)) {
      throw new AuthorizationFailedException("User does note have permission to update this Note record.");
    }

    CVDal cvdal = new CVDal(this.dataSource);

    try {
      if (noteVO == null) {
        throw new NoteException(NoteException.INVALID_DATA, "Cannot update Note record. NoteVO is empty.");
      }

      if ((noteVO.getTitle() == null) || (noteVO.getTitle().length() == 0)) {
        throw new NoteException(NoteException.INVALID_DATA, "Title is Empty");
      }

      if (noteVO.getPriority() == null) {
        noteVO.setPriority(NoteVO.NP_MEDIUM);
      }

      if (noteVO.getModifiedBy() == 0) {
        noteVO.setModifiedBy(individualID);
      }

      if (noteVO.getOwner() == 0) {
        noteVO.setOwner(individualID);
      }

      NoteVO oldNoteVO = this.getNote(individualID, noteVO.getNoteId());
      noteVO = (NoteVO) CVUtility.replaceVO(oldNoteVO, noteVO, "Notes", individualID, this.dataSource);

      cvdal.setSql("note.updatenote");
      cvdal.setString(1, noteVO.getTitle());
      cvdal.setString(2, noteVO.getDetail());
      cvdal.setString(3, noteVO.getPriority());
      cvdal.setInt(4, noteVO.getRelateEntity());
      cvdal.setInt(5, noteVO.getRelateIndividual());
      cvdal.setInt(6, noteVO.getModifiedBy());
      cvdal.setInt(7, noteVO.getNoteId());
      cvdal.executeUpdate();

      // For the purposes of Sync (CompanionLink), we need to have
      // a hack. :-( Basically, we're going to store Note data in two
      // places, causing redundant data in our database. So when we
      // update a note, we need to update the corresponding record in
      // the syncnote table
      this.updateSyncNotes(noteVO, cvdal);
    } catch (Exception e) {
      logger.error("[updateNote]: Exception", e);
      throw new NoteException(NoteException.INSERT_FAILED, "Failed in note ejb while updating note");
    } finally {
      cvdal.destroy();
      cvdal = null;
    }
  } // end updateNote(int,NoteVO) method

  /**
   * Deletes a note record from the database, based on the given
   * <code>noteID</code> paramater. Note that the record is moved to the
   * "attic".
   * @param individualID The <code>individualID</code> of the user who is
   *          deleting the note record.
   * @param noteID The ID of the note to be deleted.
   * @return void
   */
  public void deleteNote(int individualID, int noteID) throws AuthorizationFailedException
  {
    if (!CVUtility.canPerformRecordOperation(individualID, "Notes", noteID, ModuleFieldRightMatrix.DELETE_RIGHT, this.dataSource)) {
      throw new AuthorizationFailedException("User cannot delete this note.");
    }

    CVDal cvdal = new CVDal(this.dataSource);

    try {
      // we'll need the details of the note for attic transaction,
      // so get the NoteVO before deleting the record ;-)
      NoteVO noteVO = this.getNote(individualID, noteID);

      // next two hashmaps are needed for attic transaction
      HashMap hmNote = new HashMap();
      hmNote.put("noteid", noteVO.getNoteId() + "");

      HashMap hmDetails = new HashMap();
      hmDetails.put("title", noteVO.getTitle());
      hmDetails.put("owner", new Integer(noteVO.getOwner()));
      hmDetails.put("module", new Integer(5));
      hmDetails.put("recordtype", new Integer(111));

      // do attic transaction
      this.sendToAttic(individualID, "note", hmNote, hmDetails, Constants.CV_GARBAGE);

      // delete note from database
      cvdal.setSql("note.deletenote");
      cvdal.setInt(1, noteID);
      cvdal.executeUpdate();

      // update the syncnote table
      this.updateSyncNotes(noteVO, cvdal);
    } catch (NoteException ne) {
      throw new EJBException(ne);
    } finally {
      cvdal.destroy();
      cvdal = null;
    }
  } // end deleteNote(int,int) method

  /**
   * Gets the Whole list of notes
   * @param individualID The <code>individualID</code> of the user who is
   *          requesting the list.
   * @param hashmap Paging/List parameters
   * @return NoteList containg the list of note records.
   */
  public NoteList getNoteList(int individualID, HashMap hashmap) throws AuthorizationFailedException
  {
    if (!CVUtility.isModuleVisible("Notes", individualID, this.dataSource)) {
      throw new AuthorizationFailedException("Notes - ListNote");
    }

    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");
    String strNoteTypeReq = (String) hashmap.get("notetype");

    char charSort = chrSortType.charValue();

    int intStartParam = intStart.intValue();
    int intEndParam = intEnd.intValue();

    int beginIndex = Math.max(intStartParam - 100, 1);
    int endindex = intEndParam + 100;

    NoteList noteList = new NoteList();

    noteList.setSortMember(strSortMem);

    CVDal cvdal = new CVDal(dataSource);

    Collection colList = null;

    CVUtility.getAllAccessibleRecords("Notes", "noteaccess", "note", "NoteID", "Owner", null, individualID, cvdal);

    try {
      if ((strSearch != null) && strSearch.startsWith("ADVANCE:")) {
        // This is an advanced search
        strSearch = strSearch.substring(8);

        // create a temp table that we'll search against, the search string
        // will need to populate that temp table with data, or nothing will
        // be returned
        String str = "CREATE TEMPORARY TABLE notelistSearch " + strSearch;
        cvdal.setSqlQueryToNull();
        cvdal.setSqlQuery(str);
        cvdal.executeUpdate();
        cvdal.setSqlQueryToNull();

        // note that we don't need to define two exact queries with only
        // the sort order changed, we can use a varible =-o
        String sortOrder = (charSort == 'A') ? " ASC" : " DESC";

        if (strNoteTypeReq.equals(NoteConstantKeys.ALLNOTELIST)) {
          // for "All Notes"
          String strQuery = "SELECT nt.noteid AS noteid, nt.title AS title, nt.Detail AS Detail, "
              + "nt.datecreated AS date, concat(indv.FirstName,' ',indv.LastName) AS 'Created By', "
              + "nt.priority AS priority, indv.individualid AS individualid FROM note nt "
              + "LEFT OUTER join individual indv ON indv.individualid=nt.owner, "
              + "notelistSearch ntlist, noteaccess nta WHERE ntlist.noteid=nt.noteid AND " + "nta.NoteID = nt.NoteID ORDER BY '" + strSortMem + "'"
              + sortOrder;

          cvdal.setSqlQueryToNull();
          cvdal.setSqlQuery(strQuery);
          colList = cvdal.executeQuery();
          cvdal.setSqlQueryToNull();
        } else {
          // for "My Notes"
          String strQuery = "SELECT nt.noteid AS noteid, nt.title as title, nt.Detail as Detail, "
              + "nt.datecreated AS date, CONCAT(indv.FirstName, ' ', indv.LastName) AS 'Created By', "
              + "nt.priority AS priority, indv.individualid AS individualid FROM note nt "
              + "LEFT OUTER JOIN individual indv ON indv.individualid=nt.owner, "
              + "notelistSearch ntlist WHERE nt.owner=? AND ntlist.noteid=nt.noteid ORDER BY '" + strSortMem + "'" + sortOrder;

          cvdal.setSqlQueryToNull();
          cvdal.setSqlQuery(strQuery);
          cvdal.setInt(1, individualID);
          colList = cvdal.executeQuery();
          cvdal.setSqlQueryToNull();
        }

        // drop the temp table used for searching
        cvdal.setSqlQuery("DROP TABLE notelistSearch");
        cvdal.executeUpdate();

        noteList.setTotalNoOfRecords(colList.size());
      } else {
        // this is for returning the list with no searching
        if (strNoteTypeReq.equals(NoteConstantKeys.ALLNOTELIST)) {
          if (charSort == 'A') {
            cvdal.setDynamicQuery("note.allnotes", "ASC", strSortMem, beginIndex, endindex);
          } else {
            cvdal.setDynamicQuery("note.allnotes", "DESC", strSortMem, beginIndex, endindex);
          }

          colList = cvdal.executeQuery();
          cvdal.setSqlQueryToNull();

          cvdal.setSql("note.allnotecount");
          cvdal.executeQuery();

          Collection count = cvdal.executeQuery();
          Iterator itCount = count.iterator();
          HashMap hmx = (HashMap) itCount.next();
          Integer endCount = (Integer) hmx.get("allnotecount");
          cvdal.setSqlQueryToNull();

          int totalCount = endCount.intValue();

          noteList.setTotalNoOfRecords(totalCount);
        } else {
          if (charSort == 'A') {
            cvdal.setDynamicQuery("note.mynotes", "ASC", strSortMem, beginIndex, endindex);
          } else {
            cvdal.setDynamicQuery("note.mynotes", "DESC", strSortMem, beginIndex, endindex);
          }

          cvdal.setInt(1, individualID);
          colList = cvdal.executeQuery();
          cvdal.setSqlQueryToNull();

          cvdal.setSql("note.mynotecount");
          cvdal.setInt(1, individualID);
          cvdal.executeQuery();

          Collection count = cvdal.executeQuery();
          Iterator itCount = count.iterator();
          HashMap hmx = (HashMap) itCount.next();
          Integer endCount = (Integer) hmx.get("mynotecount");
          cvdal.setSqlQueryToNull();

          int totalCount = endCount.intValue();

          noteList.setTotalNoOfRecords(totalCount);
        }
      }

      cvdal.setSqlQueryToNull();
      cvdal.setSqlQuery("drop table noteaccess");
      cvdal.executeUpdate();
    } finally {
      cvdal.destroy();
      cvdal = null;
    }

    if (colList != null) {
      Iterator it = colList.iterator();

      int i = 0;

      while (it.hasNext()) {
        i++;

        HashMap hm = (HashMap) it.next();
        int noteID = ((Long) hm.get("noteid")).intValue();

        try {
          IntMember intNoteID = new IntMember("NoteID", noteID, 10, "", 'T', false, 10);

          StringMember strTitle = null;

          if ((hm.get("title") != null)) {
            strTitle = new StringMember("Title", (String) hm.get("title"), 10, "/centraview/ViewNoteHandler.do?typeOfContact=entity&rowId=1", 'T',
                true);
          } else {
            strTitle = new StringMember("Title", null, 10, "/centraview/ViewNoteHandler.do?typeOfContact=entity&rowId=1", 'T', true);
          }

          StringMember strDetail = null;

          if ((hm.get("Detail") != null)) {
            strDetail = new StringMember("Detail", (String) hm.get("Detail"), 10, "", 'T', false);
          } else {
            strDetail = new StringMember("Detail", null, 10, "", 'T', false);
          }

          StringMember strCreatedBY = new StringMember("CreatedBy", (String) hm.get("Created By"), 10, "", 'T', true);
          StringMember strPriority = new StringMember("Priority", (String) hm.get("priority"), 10, "", 'T', false);

          IntMember intIndividualID = null;
          if ((hm.get("individualid") != null)) {
            intIndividualID = new IntMember("IndividualID", ((Long) hm.get("individualid")).intValue(), 10, "", 'T', false, 10);
          } else {
            intIndividualID = new IntMember("IndividualID", 0, 10, "", 'T', false, 10);
          }

          Timestamp dtCreated = null;
          DateMember dmCreated = null;

          String timezoneid = "EST";

          if ((hm.get("date") != null)) {
            dtCreated = (Timestamp) hm.get("date");
            dmCreated = new DateMember("Date", dtCreated, 10, "", 'T', false, 1, timezoneid);
          } else {
            dmCreated = new DateMember("Date", null, 10, "", 'T', false, 1, timezoneid);
          }

          NoteListElement notelistelement = new NoteListElement(noteID);
          notelistelement.put("NoteID", intNoteID);
          notelistelement.put("Title", strTitle);
          notelistelement.put("CreatedBy", strCreatedBY);
          notelistelement.put("Date", dmCreated);
          notelistelement.put("Priority", strPriority);
          notelistelement.put("Detail", strDetail);

          notelistelement.put("IndividualID", intIndividualID);

          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();
          noteList.put(s4, notelistelement);
        } catch (Exception e) {
          logger.error("[getNoteList]: Exception", e);
        }
      }
    }

    noteList.setNoteType(strNoteTypeReq);
    noteList.setListType("Note");
    noteList.setBeginIndex(beginIndex);
    noteList.setEndIndex(noteList.size());
    return noteList;
  } // end getNoteList(int,HashMap) method

  /**
   * This function is used for the Entity Detail bottom listing for notes. The
   * parameter change is on that takes an EntityID instead of an Individual
   * @param entityId Current entity id value
   * @param hashmap Hashmap of list attributes
   * @return NoteList Return a NoteList for the current entity
   * @author Chuck Durham
   */
  public NoteList getEntityNoteList(int entityId, 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");
    String strNoteTypeReq = (String) hashmap.get("notetype");

    char charSort = chrSortType.charValue();

    int intStartParam = intStart.intValue();
    int intEndParam = intEnd.intValue();

    int beginIndex = Math.max(intStartParam - 100, 1);
    int endindex = intEndParam + 100;

    NoteList noteList = new NoteList();

    noteList.setSortMember(strSortMem);

    CVDal cvdal = new CVDal(dataSource);

    Collection colList = null;

    // Check to see if there is Search Criteria
    if ((strSearch != null) && strSearch.startsWith("ADVANCE:")) {
      strSearch = strSearch.substring(8);
      String str = "create TEMPORARY TABLE notelistSearch " + strSearch;
      cvdal.setSqlQueryToNull();
      cvdal.setSqlQuery(str);
      cvdal.executeUpdate();
      cvdal.clearParameters();
      if (strNoteTypeReq.equals(NoteConstantKeys.ALLNOTELIST)) {
        String strQuery = "";

        if (charSort == 'A') {
          strQuery = "select nt.noteid as noteid,nt.title as title,nt.Detail as Detail,nt.datecreated as date,concat(indv.FirstName,' ',indv.LastName) 'Created By',nt.priority as priority,indv.individualid as individualid from note nt left outer join individual indv on indv.individualid=nt.owner,notelistSearch ntlist where ntlist.noteid=nt.noteid order by '"
              + strSortMem + "' ASC";
        } else {
          strQuery = "select nt.noteid as noteid,nt.title as title,nt.Detail as Detail,nt.datecreated as date,concat(indv.FirstName,' ',indv.LastName) 'Created By',nt.priority as priority,indv.individualid as individualid from note nt left outer join individual indv on indv.individualid=nt.owner,notelistSearch ntlist where ntlist.noteid=nt.noteid order by '"
              + strSortMem + "' DESC";
        }

        cvdal.setSqlQueryToNull();
        cvdal.setSqlQuery(strQuery);
        colList = cvdal.executeQuery();
        cvdal.clearParameters();
      } else {
        String strQuery = "";

        if (charSort == 'A') {
          strQuery = "select nt.noteid as noteid,nt.title as title,nt.Detail as Detail,nt.datecreated as date ,concat(indv.FirstName,' ',indv.LastName) 'Created By',nt.priority as priority,indv.individualid as individualid from note nt left outer join individual indv on indv.individualid=nt.owner,notelistSearch ntlist where  nt.RelateEntity=? and ntlist.noteid=nt.noteid order by '"
              + strSortMem + "' ASC";
        } else {
          strQuery = "select nt.noteid as noteid,nt.title as title,nt.Detail as Detail,nt.datecreated as date ,concat(indv.FirstName,' ',indv.LastName) 'Created By',nt.priority as priority,indv.individualid as individualid from note nt left outer join individual indv on indv.individualid=nt.owner,notelistSearch ntlist where  nt.RelateEntity=? and ntlist.noteid=nt.noteid order by '"
              + strSortMem + "' DESC";
        }

        cvdal.setSqlQueryToNull();
        cvdal.setSqlQuery(strQuery);
        cvdal.setInt(1, entityId);
        colList = cvdal.executeQuery();
        cvdal.clearParameters();
      }

      cvdal.setSqlQueryToNull();
      cvdal.setSqlQuery("DROP TABLE notelistSearch");
      cvdal.executeUpdate();

      noteList.setTotalNoOfRecords(colList.size());
    } else {
      if (strNoteTypeReq.equals(NoteConstantKeys.ALLNOTELIST)) {
        if (charSort == 'A') {
          cvdal.setDynamicQuery("note.allnotes", "ASC", strSortMem, beginIndex, endindex);
        } else {
          cvdal.setDynamicQuery("note.allnotes", "DESC", strSortMem, beginIndex, endindex);
        }

        colList = cvdal.executeQuery();
        cvdal.clearParameters();

        cvdal.setSql("note.allnotecount");
        cvdal.executeQuery();

        Collection count = cvdal.executeQuery();
        Iterator itCount = count.iterator();
        HashMap hmx = (HashMap) itCount.next();
        Integer endCount = (Integer) hmx.get("allnotecount");
        cvdal.clearParameters();

        int totalCount = endCount.intValue();

        noteList.setTotalNoOfRecords(totalCount);
      } else {
        if (charSort == 'A') {
          cvdal.setDynamicQuery("note.entitynotes", "ASC", strSortMem, beginIndex, endindex);
        } else {
          cvdal.setDynamicQuery("note.entitynotes", "DESC", strSortMem, beginIndex, endindex);
        }

        cvdal.setInt(1, entityId);
        colList = cvdal.executeQuery();
        cvdal.clearParameters();

        cvdal.setSql("note.entitynotecount");
        cvdal.setInt(1, entityId);
        cvdal.executeQuery();

        Collection count = cvdal.executeQuery();
        Iterator itCount = count.iterator();
        HashMap hmx = (HashMap) itCount.next();
        Integer endCount = (Integer) hmx.get("mynotecount");
        cvdal.clearParameters();

        int totalCount = endCount.intValue();

        noteList.setTotalNoOfRecords(totalCount);
      }
    }

    cvdal.destroy();

    if (colList != null) {
      Iterator it = colList.iterator();

      int i = 0;

      while (it.hasNext()) {
        i++;

        HashMap hm = (HashMap) it.next();
        int noteID = ((Long) hm.get("noteid")).intValue();

        try {
          IntMember intNoteID = new IntMember("NoteID", noteID, 10, "", 'T', false, 10);

          StringMember strTitle = null;

          if ((hm.get("title") != null)) {
            strTitle = new StringMember("Title", (String) hm.get("title"), 10, "/centraview/ViewNoteHandler.do?typeOfContact=entity&rowId=1", 'T',
                false);
          } else {
            strTitle = new StringMember("Title", null, 10, "/centraview/ViewNoteHandler.do?typeOfContact=entity&rowId=1", 'T', false);
          }

          StringMember strCreatedBY = new StringMember("CreatedBy", (String) hm.get("Created By"), 10, "", 'T', false);
          StringMember strPriority = new StringMember("Priority", (String) hm.get("priority"), 10, "", 'T', false);
          IntMember intIndividualID = null;

          if ((hm.get("individualid") != null)) {
            intIndividualID = new IntMember("IndividualID", ((Long) hm.get("individualid")).intValue(), 10, "", 'T', false, 10);
          } else {
            intIndividualID = new IntMember("IndividualID", 0, 10, "", 'T', false, 10);
          }

          Timestamp dtCreated = null;
          DateMember dmCreated = null;

          String timezoneid = "EST";

          if ((hm.get("date") != null)) {
            dtCreated = (Timestamp) hm.get("date");
            dmCreated = new DateMember("Date", dtCreated, 10, "", 'T', false, 1, timezoneid);
          } else {
            dmCreated = new DateMember("Date", null, 10, "", 'T', false, 1, timezoneid);
          }

          StringMember strDetail = null;

          if ((hm.get("Detail") != null)) {
            strDetail = new StringMember("Detail", (String) hm.get("Detail"), 10, "", 'T', false);
          } else {
            strDetail = new StringMember("Detail", null, 10, "", 'T', false);
          }

          NoteListElement notelistelement = new NoteListElement(noteID);

          notelistelement.put("NoteID", intNoteID);
          notelistelement.put("Title", strTitle);
          notelistelement.put("CreatedBy", strCreatedBY);
          notelistelement.put("Date", dmCreated);
          notelistelement.put("Detail", strDetail);
          notelistelement.put("Priority", strPriority);
          notelistelement.put("IndividualID", intIndividualID);

          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();

          noteList.put(s4, notelistelement);
        } catch (Exception e) {
          logger.error("[getEntityNoteList]: Exception", e);
        }
      }
    }

    noteList.setNoteType(strNoteTypeReq);
    noteList.setListType("Note");
    noteList.setBeginIndex(beginIndex);
    noteList.setEndIndex(noteList.size());

    return noteList;
  } // end getEntityNoteList(int,HashMap) method

  private void sendToAttic(int userID, String recordType, HashMap primaryMembers, HashMap hmDetails, String dumpType)
  {
    try {
      InitialContext ctx = CVUtility.getInitialContext();
      CvAtticLocalHome home = (CvAtticLocalHome) ctx.lookup("local/CvAttic");

      CvAtticLocal remote = home.create();
      remote.setDataSource(this.dataSource);

      int transID = remote.getAtticTransactionID(userID, dumpType, hmDetails);

      if (transID > 0) {
        remote.dumpData(userID, transID, recordType, primaryMembers);
      }
    } catch (Exception e) {
      logger.error("[sendToAttic]: Exception", e);
    }
  } // end sendToAttic(int,String,HashMap,HashMap,String) method

  /**
   * Updates the "syncnote" table with the most current notes data for the
   * Individual who is related to the <code>NoteVO</code> passed in. This
   * method creates one record in the "syncnote" table. It first gets the
   * <code>individualID</code> of the related individual from the
   * <code>NoteVO</code> passed in, then gets the list of <strong>all</strong>
   * notes associated with that individual, then creates one String that is an
   * aggregate of all those notes, then inserts that String as a record in the
   * "syncnote" table. The only reason for doing this is to improve the
   * performance of the Sync Agent.
   * @param noteVO A <code>NoteVO</code> object representing the note that was
   *          modified in some way prior to this method being called. We'll use
   *          it to get the related <code>individualID</code>.
   * @param cvdal An <strong>open</strong> database connection.
   * @return void
   */
  private void updateSyncNotes(NoteVO noteVO, CVDal cvdal)
  {
    try {
      int relatedIndividualID = noteVO.getRelateIndividual();
      if (relatedIndividualID > 0) {
        // always delete all records from the "syncnote" table first.
        // the logic here is that we'll remove the record associated
        // with the contact, then rebuild it based on the content of
        // the "note" table. That way, we don't have to figure out if
        // we need to update or insert, it's always insert.
        cvdal.setSqlQuery("DELETE FROM syncnote WHERE recordID=? AND recordTypeID=2");
        cvdal.setInt(1, relatedIndividualID);
        cvdal.executeUpdate();
        cvdal.setSqlQueryToNull();

        // now get all notes related to the specified individual
        String getNotes = "SELECT n.NoteID AS noteID, n.Detail AS content, n.DateUpdated AS lastModified, "
            + "u.Name as userName FROM note n LEFT JOIN user u ON (n.Owner=u.IndividualID) "
            + "WHERE n.RelateIndividual=? ORDER BY lastModified DESC";
        cvdal.setSqlQuery(getNotes);
        cvdal.setInt(1, relatedIndividualID);
        Collection results = cvdal.executeQuery();
        cvdal.setSqlQueryToNull();

        if (results != null && results.size() > 0) {
          StringBuffer newContent = new StringBuffer("");
          Iterator iter = results.iterator();
          while (iter.hasNext()) {
            HashMap note = (HashMap) iter.next();

            // loop through the list of notes, appending a delimiter
            // and the content of the note to a StringBuffer, which
            // we'll then put back into a new record in syncnote table
            Number noteID = (Number) note.get("noteID");
            String content = (String) note.get("content");
            Timestamp lastModified = (Timestamp) note.get("lastModified");
            String userName = (String) note.get("userName");

            // format date as string
            SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss a");
            String dateString = dateFormatter.format(lastModified);

            // create delimiter
            String delimiter = "----# " + noteID.toString() + " - " + userName + " - " + dateString + " #----\n";

            // append content
            newContent.append(delimiter);
            newContent.append(content);
            if (iter.hasNext()) {
              newContent.append("\n\n");
            }
          } // end while(iter.hasNext())

          // update syncnote with new content
          String update = "INSERT INTO syncnote (recordID, recordTypeID, content) VALUES (?, 2, ?)";
          cvdal.setSqlQuery(update);
          cvdal.setInt(1, relatedIndividualID);
          cvdal.setString(2, newContent.toString());
          cvdal.executeUpdate();
        }
      } else {
        return;
      }
      // If, in the future, we deem that we need to track
      // entity notes for sync the same way that we're
      // tracking individual notes, then abstract the code
      // above into a new method, and check for the existence
      // of a related entity id here, and make the same calls
      // with recordTypeID = 1.
    } catch (Exception e) {
      logger.error("[updateSyncNotes]: Exception", e);
    } finally {
      cvdal.setSqlQueryToNull();
    }
  }

  /**
   * @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;
  }

  /**
   * Returns a ValueListVO representing a list of Note records, based on the
   * <code>parameters</code> argument which limits results.
   */
  public ValueListVO getNoteValueList(int individualID, ValueListParameters parameters)
  {
    ArrayList list = new ArrayList();

    boolean permissionSwitch = individualID < 1 ? false : true;
    boolean applyFilter = false;
    String filter = parameters.getFilter();

    CVDal cvdl = new CVDal(this.dataSource);
    if (filter != null && filter.length() > 0) {
      String str = "CREATE TABLE notelistfilter " + filter;
      cvdl.setSqlQuery(str);
      cvdl.executeUpdate();
      cvdl.setSqlQueryToNull();
      applyFilter = true;
    }
    int numberOfRecords = 0;
    if (applyFilter)
      numberOfRecords = EJBUtil.buildListFilterTable(cvdl, "notelistfilter", individualID, 5, "note", "NoteID", "Owner", null, permissionSwitch);
    else if (permissionSwitch)
      numberOfRecords = EJBUtil.buildListFilterTable(cvdl, null, individualID, 5, "note", "NoteID", "Owner", null, permissionSwitch);

    parameters.setTotalRecords(numberOfRecords);
    String query = this.buildNoteListQuery(applyFilter, permissionSwitch, parameters);
    cvdl.setSqlQuery(query);
    list = cvdl.executeQueryList(1);
    cvdl.setSqlQueryToNull();

    if (applyFilter) {
      cvdl.setSqlQueryToNull();
      cvdl.setSqlQuery("DROP TABLE notelistfilter");
      cvdl.executeUpdate();
    }
    if (applyFilter || permissionSwitch) {
      cvdl.setSqlQueryToNull();
      cvdl.setSqlQuery("DROP TABLE listfilter");
      cvdl.executeUpdate();
    }
    cvdl.destroy();
    cvdl = null;
    return new ValueListVO(list, parameters);
  }

  private String buildNoteListQuery(boolean applyFilter, boolean permissionSwitch, ValueListParameters parameters)
  {
    String select = "SELECT n.NoteID, n.Title, n.Detail, n.DateCreated, CONCAT(i.FirstName, ' ', i.LastName) AS CreatedBy, "
        + "n.Priority, i.IndividualID ";

    String joinConditions = "LEFT OUTER JOIN individual i ON i.IndividualID = n.Owner ";

    StringBuffer from = new StringBuffer("FROM note n ");
    StringBuffer where = new StringBuffer("WHERE 1 = 1 ");
    String orderBy = "ORDER BY " + String.valueOf(parameters.getSortColumn() + " " + parameters.getSortDirection());
    String limit = parameters.getLimitParam();

    // If a filter is applied we need to do an additional join against the
    // temporary entity list filter table.
    if (applyFilter || permissionSwitch) {
      from.append(", listfilter AS lf ");
      where.append("AND n.NoteID = lf.NoteID ");
    }
    // Build up the actual query using all the different permissions.
    // Where owner = passed individualId
    StringBuffer query = new StringBuffer();
    query.append(select);
    query.append(from);
    query.append(joinConditions);
    query.append(where);
    query.append(orderBy);
    query.append(limit);
    return query.toString();
  }
}
TOP

Related Classes of com.centraview.note.NoteEJB

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.