Package com.centraview.marketing.List

Source Code of com.centraview.marketing.List.ListEJB

/*
* $RCSfile: ListEJB.java,v $    $Revision: 1.2 $  $Date: 2005/09/01 15:31:05 $ - $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.marketing.List;

import java.io.StringBufferInputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Random;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.Vector;

import javax.ejb.CreateException;
import javax.ejb.SessionBean;
import javax.ejb.SessionContext;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

import org.apache.log4j.Logger;

import com.centraview.administration.authorization.AuthorizationException;
import com.centraview.administration.authorization.AuthorizationLocal;
import com.centraview.administration.authorization.AuthorizationLocalHome;
import com.centraview.common.CVDal;
import com.centraview.common.CVUtility;
import com.centraview.common.Constants;
import com.centraview.common.DDNameValue;
import com.centraview.common.helper.CommonHelperLocal;
import com.centraview.common.helper.CommonHelperLocalHome;
import com.centraview.contact.contactfacade.ContactFacadeLocal;
import com.centraview.contact.contactfacade.ContactFacadeLocalHome;
import com.centraview.contact.helper.ContactHelperLocal;
import com.centraview.contact.helper.ContactHelperLocalHome;
import com.centraview.customfield.CustomFieldLocal;
import com.centraview.customfield.CustomFieldLocalHome;
import com.centraview.file.CvFileFacade;
import com.centraview.file.CvFileLocal;
import com.centraview.file.CvFileLocalHome;
import com.centraview.file.CvFileVO;
import com.centraview.file.CvFolderVO;

public class ListEJB implements SessionBean
{
  private static Logger logger = Logger.getLogger(ListEJB.class);
  protected javax.ejb.SessionContext ctx;
  protected Context environment;
  private String dataSource = "MySqlDS";

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

  public void ejbActivate() { }
  public void ejbPassivate() { }
  public void ejbRemove() { }
  public void ejbCreate() { }

  public int addList(int userId, ListVO listVO) throws AuthorizationException, CreateException, NamingException
  {
    int newListID = 0;
    CVDal dl = new CVDal(dataSource);
    try {
      dl.setSqlQuery("INSERT INTO marketinglist (title, description, owner, created, modified ,status) VALUES (?, ?, ?, NOW(), NOW(), 'YES')");
      dl.setString(1, listVO.getTitle());
      dl.setString(2, listVO.getDescription());
      dl.setInt(3, listVO.getOwnerID());
      dl.executeUpdate();
      newListID = dl.getAutoGeneratedKey();
    } catch (Exception e) {
      logger.error("[Exception] ListEJB.addList: ", e);
    } finally {
      dl.clearParameters();
      dl.destroy();
      dl = null;
    }

    if (newListID != 0) {
      // Everything is created now apply the default permissions for this user.
      InitialContext ic = CVUtility.getInitialContext();
      AuthorizationLocalHome authorizationHome = (AuthorizationLocalHome)ic.lookup("local/Authorization");
      AuthorizationLocal authorizationLocal = authorizationHome.create();
      authorizationLocal.setDataSource(this.dataSource);
      authorizationLocal.saveCurrentDefaultPermission("ListManager", newListID, userId);
      authorizationLocal.saveCurrentDefaultPermission("MarketingList", newListID, userId);
    }
    return newListID;
  }

  public boolean deleteList(int listID)
  {
    // Don't delete the default list.
    if (listID == 1) {
      return false;
    }
   
    CVDal cvdal = new CVDal(dataSource);
    boolean deleted = false;
    try {
      cvdal.setSqlQuery("delete from marketinglist  where ListID = ? ");
      cvdal.setInt(1, listID);
      cvdal.executeUpdate();
      cvdal.clearParameters();
     
      InitialContext ic = CVUtility.getInitialContext();
      ContactFacadeLocalHome contactHome = (ContactFacadeLocalHome)ic.lookup("local/ContactFacade");
      ContactFacadeLocal contactLocal = contactHome.create();
      contactLocal.setDataSource(this.dataSource);
      contactLocal.deleteEntity(listID);
      contactLocal.deleteIndividual(listID);
     
      AuthorizationLocalHome authorizationHome = (AuthorizationLocalHome)ic.lookup("local/Authorization");
      AuthorizationLocal authorizationLocal = authorizationHome.create();
      authorizationLocal.setDataSource(this.dataSource);
      authorizationLocal.deleteMarketingMemberPublicRecords(listID);
      authorizationLocal.deleteRecordFromPublic("ListManager",listID);
      authorizationLocal.deleteRecordFromPublic("MarketingList",listID);
      authorizationLocal.deleteRecordsFromRecordAuthorization("ListManager",listID);
      authorizationLocal.deleteRecordsFromRecordAuthorization("MarketingList",listID);
     
      deleted = true;
    } catch (Exception e) {
      logger.error("[Exception] ListEJB.deleteList: ", e);
    } finally {
      cvdal.clearParameters();
      cvdal.destroy();
      cvdal = null;
    }
    return deleted;
  }

  public boolean updateList(int userId, ListVO listVO)
  {
    CVDal dl = new CVDal(dataSource);
    boolean updated = false;
    try {
      dl.setSqlQuery("UPDATE marketinglist set title=?, description=?, modified=NOW() WHERE ListID=? ");
      dl.setString(1, listVO.getTitle());
      dl.setString(2, listVO.getDescription());
      dl.setInt(3, listVO.getListID());
      dl.executeUpdate();
      updated = true;
    } catch (Exception e) {
      logger.error("[Exception] ListEJB.updateList: ", e);
    }finally{
      dl.clearParameters();
      dl.destroy();
      dl = null;
    }
    return updated;
  }

  public ListVO viewList(int listId)
  {
    ListVO listVO = new ListVO();
   
    CVDal dl = new CVDal(dataSource);

    try {
      dl.setSqlQuery("SELECT mls.ListID, mls.title, mls.Description, mls.owner, " +
                     "CONCAT(trim(ind.Firstname), ' ', trim(ind.LastName)) AS ownername, " +
                     "mls.created ,mls.modified  from marketinglist mls, individual ind " +
                     "WHERE mls.ListID = ? AND ind.individualid=mls.owner GROUP BY mls.ListID");
      dl.setInt(1, listId);

      Collection col = dl.executeQuery();

      if (col != null) {
        HashMap hm = (HashMap) col.iterator().next();
        listVO.setTitle((String) hm.get("title").toString());
        listVO.setDescription((String) hm.get("Description").toString());
       
        if (hm.get("ListID") != null) {
          listVO.setListID(((Number) hm.get("ListID")).intValue());
        }
       
        listVO.setCreated((String) hm.get("created").toString());
        listVO.setModified((String) hm.get("modified").toString());
       
        if (hm.get("owner") != null) {
          listVO.setOwnerID(((Number) hm.get("owner")).intValue());
        }
       
        listVO.setOwnerName((String) hm.get("ownername").toString());
      }
    } catch (Exception e) {
      logger.error("[Exception] ListEJB.viewList: ", e);
    } finally {
      dl.clearParameters();
      dl.destroy();
      dl = null;
    }
    return listVO;
  }

  public Collection getAllList()
  {
    Collection col = null;
    CVDal dl = new CVDal(dataSource);

    try {
      dl.setSqlQuery("select ListID , title from marketinglist ");
      col = dl.executeQuery();
    } catch (Exception e) {
      logger.error("[Exception] ListEJB.getAllList: ", e);
    } finally {
      dl.clearParameters();
      dl.destroy();
      dl = null;
    }
    return col;
  }

  /**
   * This method Parse the information column by column and stores the information
   * in the database and returns a String of Message objects.
   * @param Vector The importList to get the Import row and Column.
   * @param int The headerRow to get the head row.
   * @param int The listID Identify we are are importing records into which list.
   * @param int The individualID Identify who is logged in an performing the task.
   * @param Collection The CustomEntList to get the list of Custom Entity.
   * @param Collection The CustomIndList to get the list of Custom Individual.
   * @param String The tabDelimiter to identify the column seperation delimiter.
   * @param String The lineDelimiter to identify the row seperation delimiter.
   * @param String The headLine its a header line.
   * @return HashMap of Message objects.
   */
  public HashMap getImportList(Vector importList, int headerRow, int listid, int indvID, Collection CustomEntList, Collection CustomIndList, String tabDelimiter, String lineDelimiter, String headLine)
  {
    HashMap messageList = new HashMap();

    try {
      StringBuffer importInputStream = new StringBuffer();

      if ((headLine != null) && !headLine.equals("")) {
        importInputStream.append(headLine + tabDelimiter + "Line" + tabDelimiter + "Error Message" + lineDelimiter);
      }

      //Collect the Error Line
      HashMap errLineNumber = new HashMap();
      HashMap msgLineNumber = new HashMap();

      //intialize the Variable
      String street1 = null;
      String street2 = null;
      String city = null;
      String state = null;
      String zip = null;
      String country = null;
      String email = null;
      String phone = null;
      String entity = null;
      String manager = null;
      String group = null;
      String fName = null;
      String mName = null;
      String lName = null;
      String title = null;
      String homePhone = null;
      String faxPhone = null;
      String mainPhone = null;
      String mobilePhone = null;
      String otherPhone = null;
      String pagerPhone = null;
      String workPhone = null;
      String entityExternalID = null;
      String individualExternalID = null;
      String sourceIndividual = null;
      String sourceEntity = null;
      String website = null;
      Vector customEntity = new Vector();
      Vector customIndividual = new Vector();
      String errMsg = "";
      String line = "";
      boolean entityPrimaryFlag = false;

      // Collect the State, country, source, group, user, Method of Contact List
      InitialContext ic = CVUtility.getInitialContext();
      ContactHelperLocalHome homeContact = (ContactHelperLocalHome)ic.lookup("local/ContactHelper");
      ContactHelperLocal remoteContact =  homeContact.create();
      remoteContact.setDataSource(this.dataSource);

      CommonHelperLocalHome homeCommon = (CommonHelperLocalHome)ic.lookup("local/CommonHelper");
      CommonHelperLocal remoteCommon =  homeCommon.create();
      remoteCommon.setDataSource(this.dataSource);

      HashMap sourceList = remoteCommon.getSourceList();
      Vector groupList = remoteContact.getGroups();
      HashMap entityList = remoteContact.getEntityList(listid);
      HashMap employeeList = remoteContact.getEmployeeList();

      //remoteCommon = null;
      homeCommon = null;
      remoteContact = null;
      homeContact = null;

      // Collect all the CustomfieldValue
      CustomFieldLocalHome homeCustomField = (CustomFieldLocalHome)ic.lookup("local/CustomField");
      CustomFieldLocal remoteCustomField =  homeCustomField.create();
      remoteCustomField.setDataSource(this.dataSource);

      HashMap CustomFieldValues = remoteCustomField.getCustomFieldValue();
      homeCustomField = null;
      remoteCustomField = null;

      ArrayList newEntityList = new ArrayList();
      ArrayList newIndividualList = new ArrayList();

      int errCounter = 0;

      //initalize the cvDal
      CVDal dl = new CVDal(dataSource);

      dl.setSqlQuery("SELECT a.PrimaryContact ,b.EntityId FROM individual a, "
        + "entity b WHERE a.Entity=b.EntityId AND PrimaryContact='YES' "
        + "AND a.list=" + listid);

      Collection col = dl.executeQuery();
      dl.clearParameters();

      HashMap primaryContactList = new HashMap();

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

        while (it.hasNext()) {
          HashMap hm = (HashMap) it.next();
          String name = (String) hm.get("PrimaryContact");
          int id = ((Long) hm.get("EntityId")).intValue();
          primaryContactList.put(id + "", name.trim());
        }
      }

      int count = importList.size();

      ArrayList batchQuery = new ArrayList();
      int i = 0;
      while (i < importList.size()) {
        HashMap hCols = (HashMap) importList.get(0);
        line = (String) hCols.get("Line");
        String showLine = line;

        if (line != null && line.length() >25) {
          showLine = line.substring(0, 25);
        }
        entityPrimaryFlag = false;
        errMsg = "";

        if (hCols.size() == 0) {
          errMsg = "Delimitor doesn't Match Up!,";
          errCounter++;
        } else {
          fName = (String) hCols.get("First Name");
          lName = (String) hCols.get("Last Name");
          mName = (String) hCols.get("Middle Name");
          entity = (String) hCols.get("Entity Name");
          manager = (String) hCols.get("Account Manager");
          group = (String) hCols.get("Account Team");
          street1 = (String) hCols.get("Street1");
          street2 = (String) hCols.get("Street2");
          city = (String) hCols.get("City");
          state = (String) hCols.get("State");
          country = (String) hCols.get("Country");
          zip = (String) hCols.get("Zipcode");
          title = (String) hCols.get("Title");
          homePhone = (String) hCols.get("Home Phone");
          faxPhone = (String) hCols.get("Fax Phone");
          mainPhone = (String) hCols.get("Main Phone");
          mobilePhone = (String) hCols.get("Mobile Phone");
          otherPhone = (String) hCols.get("Other Phone");
          pagerPhone = (String) hCols.get("Pager Phone");
          workPhone = (String) hCols.get("Work Phone");
          email = (String) hCols.get("Email");
          entityExternalID = (String) hCols.get("ExternalID (Entity)");
          individualExternalID = (String) hCols.get("ExternalID (Individual)");
          sourceIndividual = (String) hCols.get("Source (Individual)");
          sourceEntity = (String) hCols.get("Source (Entity)");
          website = (String) hCols.get("Website");

          if (fName == null) {
            fName = "";
          }

          if (lName == null) {
            lName = "";
          }

          if (manager == null) {
            manager = "";
          }

          if (group == null) {
            group = "";
          }

          if (mName == null) {
            mName = "";
          }

          if (entity == null) {
            entity = "";
          }

          if (street1 == null) {
            street1 = "";
          }

          if (street2 == null) {
            street2 = "";
          }

          if (city == null) {
            city = "";
          }

          if (state == null) {
            state = "";
          }

          if (country == null) {
            country = "";
          }

          if (zip == null) {
            zip = "";
          }

          if (title == null) {
            title = "";
          }

          if (homePhone == null) {
            homePhone = "";
          }

          if (faxPhone == null) {
            faxPhone = "";
          }

          if (mainPhone == null) {
            mainPhone = "";
          }

          if (mobilePhone == null) {
            mobilePhone = "";
          }

          if (otherPhone == null) {
            otherPhone = "";
          }

          if (pagerPhone == null) {
            pagerPhone = "";
          }

          if (workPhone == null) {
            workPhone = "";
          }

          if (email == null) {
            email = "";
          }

          if (entityExternalID == null) {
            entityExternalID = "";
          }

          if (individualExternalID == null) {
            individualExternalID = "";
          }

          if (sourceIndividual == null) {
            sourceIndividual = "";
          }

          if (sourceEntity == null) {
            sourceEntity = "";
          }

          if (website == null) {
            website = "";
          }

          if ((fName.equals("")) && (lName.equals("")) && (website.equals("")) &&
              (manager.equals("")) && (group.equals("")) && (mName.equals("")) &&
              (entity.equals("")) && (street1.equals("")) &&
              (street2.equals("")) && (city.equals("")) && (state.equals("")) &&
              (country.equals("")) && (zip.equals("")) && (title.equals("")) &&
              (homePhone.equals("")) && (faxPhone.equals("")) &&
              (mainPhone.equals("")) && (mobilePhone.equals("")) &&
              (otherPhone.equals("")) && (pagerPhone.equals("")) &&
              (workPhone.equals("")) && (email.equals("")) &&
              (entityExternalID.equals("")) &&
              (individualExternalID.equals("")) &&
              (sourceIndividual.equals("")) && (sourceEntity.equals("")))
          {
            errMsg = errMsg + "Delimitor doesn't Match Up!,";
            errCounter++;
          } else {
            if (entity.equals("") || ((fName.equals("")) && (lName.equals("")))) {
              if (entity.equals("")) {
                errMsg = errMsg + "Entity is a Required Field,";
              }

              if (fName.equals("")) {
                errMsg = errMsg + "First Name is a Required Field,";
              }

              if (lName.equals("")) {
                errMsg = errMsg + "Last Name is a Required Field,";
              }

              errCounter++;
            } else {
              boolean flagInsert = true;

              if (! manager.equals("")) {
                int user = 0;
                boolean employeeFlag = employeeList.containsKey(manager);

                if (employeeFlag) {
                  user = Integer.parseInt((String) employeeList.get(manager));
                }

                if (user == 0) {
                  errMsg = errMsg + "Account Manager \"" + manager + "\" not found in Employee List,";
                  flagInsert = false;
                }
              }

              if (! group.equals("")) {
                // Get the group ID from the database
                int groupID = 0;

                // loop throught list and look for match
                Iterator itGroup = groupList.iterator();

                while (itGroup.hasNext()) {
                  DDNameValue nameValue = (DDNameValue) itGroup.next();

                  // if name matches, then...
                  if (group.equals(nameValue.getName())) {
                    // ... get the ID
                    groupID = nameValue.getId();
                  }
                }

                if (groupID == 0) {
                  errMsg = errMsg + "Account Team \"" + group + "\" not found in Group List,";
                  flagInsert = false;
                }
              }

              if ((CustomEntList != null) && (CustomEntList.size() > 0)) {
                Iterator it = CustomEntList.iterator();

                while (it.hasNext()) {
                  DDNameValue ddname = (DDNameValue) it.next();
                  String id = ddname.getName();

                  String type = null;

                  StringTokenizer st = new StringTokenizer(id, "*");

                  while (st.hasMoreTokens()) {
                    id = (String) st.nextToken();
                    type = (String) st.nextToken();
                  }

                  String name = ddname.getStrid();

                  String customEntityValue = (String) hCols.get(name);

                  if (customEntityValue != null) {
                    if ((type != null) && type.equals("MULTIPLE")) {
                      String tempEnt = customEntityValue;

                      int indexName = name.indexOf("(");


                      if (indexName > 0) {
                        customEntityValue = customEntityValue + "*" + name.substring(0, indexName);
                      }

                      boolean customFlag = CustomFieldValues.containsKey(customEntityValue);

                      if (! customFlag) {
                        errMsg = errMsg + "Custom Field \"" + tempEnt + "\" Mapped for Entity's Does Not Exist in the database ,";
                        flagInsert = false;
                      }
                    }
                  }
                }
              }

              if ((CustomIndList != null) && (CustomIndList.size() > 0)) {
                Iterator it = CustomIndList.iterator();

                while (it.hasNext()) {
                  DDNameValue ddname = (DDNameValue) it.next();
                  String id = ddname.getName();
                  String type = null;
                  StringTokenizer st = new StringTokenizer(id, "*");

                  while (st.hasMoreTokens()) {
                    id = (String) st.nextToken();
                    type = (String) st.nextToken();
                  }

                  String name = ddname.getStrid();
                  String customIndividualName = (String) hCols.get(name);

                  if (customIndividualName != null) {
                    if ((type != null) && type.equals("MULTIPLE")) {
                      String tempIndv = customIndividualName;

                      int indexName = name.indexOf("(");

                      if (indexName > 0) {
                        customIndividualName = customIndividualName + "*" + name.substring(0, indexName);
                      }

                      boolean customFlag = CustomFieldValues.containsKey(customIndividualName.trim());

                      if (!customFlag) {
                        errMsg = errMsg + "Custom Filed \"" + tempIndv + "\" mapped for Entity's Is Not Existing in the database ,";
                        flagInsert = false;
                      }
                    }
                  }
                }
              }

              if (!errMsg.equals("")) {
                errCounter++;
              }

              if (flagInsert) {
                int sourceId = 0;
                int sourceEn = 0;
                int entId = 0;

                boolean sourceFlag = sourceList.containsKey(sourceIndividual);

                if (sourceFlag) {
                  sourceId = Integer.parseInt((String) sourceList.get(sourceIndividual));
                } else {
                  if (sourceIndividual != null && !sourceIndividual.equals("")) {
                    try {
                      sourceId = remoteCommon.getSourceID(sourceIndividual);
                    } catch(Exception e) {
                      logger.error("[Exception] ListEJB.getImportList: ", e);
                    }
                  }
                }

                sourceFlag = sourceList.containsKey(sourceEntity);

                if (sourceFlag) {
                  sourceEn = Integer.parseInt((String) sourceList.get(sourceEntity));
                } else {
                  if (sourceEntity != null && !sourceEntity.equals("")) {
                    try {
                      sourceId = remoteCommon.getSourceID(sourceEntity);
                    } catch (Exception e) {
                      logger.error("[Exception] ListEJB.getImportList: ", e);
                      e.printStackTrace();
                    }
                  }
                }

                // Get the group ID from the database
                int groupID = 0;

                // loop throught list and look for match
                Iterator itGroup = groupList.iterator();

                while (itGroup.hasNext()) {
                  DDNameValue nameValue = (DDNameValue) itGroup.next();

                  // if name matches, then...
                  if (group.equals(nameValue.getName())) {
                    // ... get the ID
                    groupID = nameValue.getId();
                  }
                }

                int user = 0;

                // loop throught list and look for match
                boolean employeeFlag = employeeList.containsKey(manager);

                if (employeeFlag) {
                  user = Integer.parseInt((String) employeeList.get(manager));
                }

                if (!(website.startsWith("http://")) || (website.startsWith("https://"))) {
                  // added only http by default and not https
                  if ((website.trim()).equals("")) {
                    website = "";
                  } else {
                    website = "http://" + website;
                  }
                }

                // set Entity
                if (entity != "") {
                  boolean entityFlag = entityList.containsKey(entity);

                  if (entityFlag) {
                    entId = Integer.parseInt((String) entityList.get(entity));
                  } else {
                    dl.setSql("contact.addentity");
                    dl.setString(1, entityExternalID);
                    dl.setString(2, entity);
                    dl.setInt(3, sourceEn);
                    dl.setInt(4, 0);
                    dl.setInt(5, listid);
                    dl.setInt(6, indvID);
                    dl.setInt(7, indvID);
                    dl.setInt(8, user);
                    dl.setInt(9, groupID);
                    dl.executeUpdate();
                    entId = dl.getAutoGeneratedKey();
                    dl.clearParameters();


                    // apply the logged-in user's default privileges to this record
                    //remoteAuth.saveCurrentDefaultPermission("Entity", entId, indvID);
                    if (!newEntityList.contains(entId+"")) {
                      newEntityList.add(entId+"");
                    }

                    //Add the new Entity to the EntityList
                    entityList.put(entity, entId + "");
                  }

                  boolean addressFlag = primaryContactList.containsKey(entId +"");

                  if (!addressFlag) {
                    String Contact = (String) primaryContactList.get(entId + "");

                    if (Contact == null) {
                      entityPrimaryFlag = true;
                    }

                    if ((Contact != null) && Contact.equals("NO")) {
                      entityPrimaryFlag = true;
                    }
                  }

                  if ((CustomEntList != null) && (CustomEntList.size() > 0)) {
                    Iterator it = CustomEntList.iterator();

                    while (it.hasNext()) {
                      DDNameValue ddname = (DDNameValue) it.next();
                      String id = ddname.getName();

                      String type = null;

                      StringTokenizer st = new StringTokenizer(id, "*");

                      while (st.hasMoreTokens()) {
                        id = (String) st.nextToken();
                        type = (String) st.nextToken();
                      }

                      String name = ddname.getStrid();
                      String customEntityValue = (String) hCols.get(name);
                      String customName = name.substring(0, name.indexOf("("));

                      if (type != null) {
                        //Scalar Value
                        if (type.equals("SCALAR")) {
                          if (customEntityValue != null) {
                            batchQuery.add("insert into customfieldscalar (customfieldid,recordid,value) values (" + id + "," + entId + ",'" + customEntityValue + "')");
                          }
                        }

                        //Multiple Value
                        if (type.equals("MULTIPLE")) {
                          int indexName = name.indexOf("(");

                          if (indexName > 0) {
                            customEntityValue = customEntityValue + "*" + name.substring(0, indexName);
                          }

                          boolean customFlag = CustomFieldValues.containsKey(customEntityValue);

                          if (customFlag) {
                            String fieldId = (String) CustomFieldValues.get(customEntityValue);
                            String valueId = null;
                            st = null;
                            st = new StringTokenizer(fieldId, "*");

                            while (st.hasMoreTokens()) {
                              valueId = (String) st.nextToken();
                              fieldId = (String) st.nextToken();
                            }

                            if (valueId != null) {
                              if (fieldId.equals(id)) {
                                batchQuery.add( "insert into customfieldmultiple (customfieldid,recordid,valueid) values (" + id + "," + entId + "," + valueId + ")");
                              }
                            }
                          }
                        }
                      }
                    }
                  }
                }

                int individualID = 0;

                // create Individual
                dl.setSql("contact.createindividual");
                dl.setInt(1, entId);
                dl.setString(2, fName);
                dl.setString(3, lName);
                dl.setString(4, title);
                dl.setInt(5, indvID);

                if (entityPrimaryFlag) {
                  dl.setString(6, "YES");
                } else {
                  dl.setString(6, "NO");
                }

                dl.setString(7, mName);
                dl.setInt(8, sourceId);
                dl.setString(9, individualExternalID);
                dl.setInt(10, listid);
                dl.setInt(11, indvID);

                try {
                  dl.executeUpdate();
                  individualID = dl.getAutoGeneratedKey();
                  dl.clearParameters();

                  // apply the logged-in user's default privileges to this record
                  //remoteAuth.saveCurrentDefaultPermission("Individual", individualID, indvID);
                 
                  if (!newIndividualList.contains(individualID+"")) {
                    newIndividualList.add(individualID+"");
                  }
                 
                  if (entId != 0) {
                    primaryContactList.put(entId + "", "YES");
                  }

                  if (individualID == 0) {
                    errMsg = errMsg + "Failed to create Individual,";
                    errCounter++;
                  }
                } catch (Exception ex) {
                  errMsg = errMsg + "Failed to create Individual,";
                  errCounter++;
                  ex.printStackTrace();
                  throw new CreateException();
                } finally {
                  dl.clearParameters();
                }

                try {
                  if (! street1.equals("") || ! street2.equals("") || ! city.equals("") ||
                      ! state.equals("") || ! zip.equals("") || ! country.equals("") ||
                      ! website.equals("")) {
                    dl.setSql("contact.addaddress");
                    dl.setInt(1, 1);
                    dl.setString(2, street1);
                    dl.setString(3, street2);
                    dl.setString(4, city);
                    dl.setString(5, state);
                    dl.setString(6, zip);
                    dl.setString(7, country);
                    dl.setString(8, website);
                    dl.setInt(9, 0);
                    dl.executeUpdate();

                    int adrId = dl.getAutoGeneratedKey();
                    dl.clearParameters();

                    batchQuery.add("insert into addressrelate (Address, ContactType, Contact, AddressType, IsPrimary) values (" + adrId + ", 2, " + individualID + ", 1, 'YES')");

                    if (entityPrimaryFlag) {
                      batchQuery.add("insert into addressrelate (Address, ContactType, Contact, AddressType, IsPrimary) values (" + adrId + ", 1, " + entId + ", 1, 'YES')");
                    }
                  }
                } catch (Exception e) {
                  logger.error("[Exception] ListEJB.getImportList: ", e);
                }

                // set workPhone
                if ((workPhone != null) && (!workPhone.equals(""))) {
                  try {
                    dl.setSql("contact.addmoc");
                    dl.setInt(1, Constants.MOC_WORK);
                    dl.setString(2, workPhone);
                    dl.setString(3, ""); //moc.getNote()
                    dl.setString(4, "Work");
                    dl.setString(5, null); //moc.getMocOrder()
                    dl.executeUpdate();

                    int mocId = dl.getAutoGeneratedKey();
                    dl.clearParameters();

                    if (mocId != 0) {
                      batchQuery.add("insert into mocrelate (MOCID, ContactType, ContactID, isPrimary) values (" + mocId + ", 2, " + individualID + ", 'YES')");

                      if (entityPrimaryFlag) {
                        batchQuery.add("INSERT INTO mocrelate (MOCID, ContactType, ContactID, isPrimary) values (" + mocId + ", 1, " + entId + ", 'YES')");
                      }
                    }
                  } catch (Exception e) {
                    logger.error("[Exception] ListEJB.getImportList: ", e);
                  }
                }

                // set homePhone
                if ((homePhone != null) && (!homePhone.equals(""))) {
                  try {
                    dl.setSql("contact.addmoc");
                    dl.setInt(1, Constants.MOC_HOME);
                    dl.setString(2, homePhone);
                    dl.setString(3, ""); //moc.getNote()
                    dl.setString(4, "Home");
                    dl.setString(5, null); //moc.getMocOrder()
                    dl.executeUpdate();

                    int mocId = dl.getAutoGeneratedKey();
                    dl.clearParameters();

                    if (mocId != 0) {
                      batchQuery.add("insert into mocrelate (MOCID, ContactType, ContactID, isPrimary) values (" + mocId + ", 2, " + individualID + ", 'YES')");

                      if (entityPrimaryFlag) {
                        batchQuery.add( "insert into mocrelate (MOCID, ContactType, ContactID, isPrimary) values (" + mocId + ", 1, " + entId + ", 'YES')");
                      }
                    }
                  } catch (Exception e) {
                    logger.error("[Exception] ListEJB.getImportList: ", e);
                  }
                }

                // set faxPhone
                if ((faxPhone != null) && (!faxPhone.equals(""))) {
                  try {
                    dl.setSql("contact.addmoc");
                    dl.setInt(1, Constants.MOC_FAX);
                    dl.setString(2, faxPhone);
                    dl.setString(3, ""); //moc.getNote()
                    dl.setString(4, "Fax");
                    dl.setString(5, null); //moc.getMocOrder()
                    dl.executeUpdate();

                    int mocId = dl.getAutoGeneratedKey();
                    dl.clearParameters();

                    if (mocId != 0)
                    {
                      batchQuery.add("insert into mocrelate(MOCID,ContactType," + "ContactID,isPrimary) values(" + mocId + ",2," + individualID + ",'YES')");

                      if (entityPrimaryFlag) {
                        batchQuery.add( "insert into mocrelate(MOCID,ContactType," + "ContactID,isPrimary) values(" + mocId + ",1," + entId + ",'YES')");
                      }
                    }
                  } catch (Exception e) {
                    logger.error("[Exception] ListEJB.getImportList: ", e);
                  }
                }

                // set otherPhone
                if ((otherPhone != null) && (!otherPhone.equals(""))) {
                  try {
                    dl.setSql("contact.addmoc");
                    dl.setInt(1, Constants.MOC_OTHER);
                    dl.setString(2, otherPhone);
                    dl.setString(3, ""); //moc.getNote()
                    dl.setString(4, "Other");
                    dl.setString(5, null); //moc.getMocOrder()
                    dl.executeUpdate();

                    int mocId = dl.getAutoGeneratedKey();
                    dl.clearParameters();

                    if (mocId != 0) {
                      batchQuery.add("insert into mocrelate(MOCID,ContactType," + "ContactID,isPrimary) values(" + mocId + ",2," + individualID + ",'YES')");

                      if (entityPrimaryFlag) {
                        batchQuery.add( "insert into mocrelate(MOCID,ContactType," + "ContactID,isPrimary) values(" + mocId + ",1," + entId + ",'YES')");
                      }
                    }
                  } catch (Exception e) {
                    logger.error("[Exception] ListEJB.getImportList: ", e);
                  }
                }

                // set mainPhone
                if ((mainPhone != null) && (!mainPhone.equals(""))) {
                  try {
                    dl.setSql("contact.addmoc");
                    dl.setInt(1, Constants.MOC_MAIN);
                    dl.setString(2, mainPhone);
                    dl.setString(3, ""); //moc.getNote()
                    dl.setString(4, "Main");
                    dl.setString(5, null); //moc.getMocOrder()
                    dl.executeUpdate();

                    int mocId = dl.getAutoGeneratedKey();
                    dl.clearParameters();

                    if (mocId != 0) {
                      batchQuery.add("insert into mocrelate(MOCID,ContactType," + "ContactID,isPrimary) values(" + mocId + ",2," + individualID + ",'YES')");

                      if (entityPrimaryFlag) {
                        batchQuery.add( "insert into mocrelate(MOCID,ContactType," + "ContactID,isPrimary) values(" + mocId + ",1," + entId + ",'YES')");
                      }
                    }
                  } catch (Exception e) {
                    logger.error("[Exception] ListEJB.getImportList: ", e);
                  }
                }

                // set pagerPhone
                if ((pagerPhone != null) && (!pagerPhone.equals(""))) {
                  try {
                    dl.setSql("contact.addmoc");
                    dl.setInt(1, Constants.MOC_PAGER);
                    dl.setString(2, pagerPhone);
                    dl.setString(3, ""); //moc.getNote()
                    dl.setString(4, "Pager");
                    dl.setString(5, null); //moc.getMocOrder()
                    dl.executeUpdate();

                    int mocId = dl.getAutoGeneratedKey();
                    dl.clearParameters();

                    if (mocId != 0) {
                      batchQuery.add("insert into mocrelate(MOCID,ContactType," + "ContactID,isPrimary) values(" + mocId + ",2," + individualID + ",'YES')");

                      if (entityPrimaryFlag) {
                        batchQuery.add( "insert into mocrelate(MOCID,ContactType," + "ContactID,isPrimary) values(" + mocId + ",1," + entId + ",'YES')");
                      }
                    }
                  } catch (Exception e) {
                    logger.error("[Exception] ListEJB.getImportList: ", e);
                  }
                }

                // set mobilePhone
                if ((mobilePhone != null) && (!mobilePhone.equals(""))) {
                  try {
                    dl.setSql("contact.addmoc");
                    dl.setInt(1, Constants.MOC_MOBILE);
                    dl.setString(2, mobilePhone);
                    dl.setString(3, ""); //moc.getNote()
                    dl.setString(4, "Mobile");
                    dl.setString(5, null); //moc.getMocOrder()
                    dl.executeUpdate();

                    int mocId = dl.getAutoGeneratedKey();
                    dl.clearParameters();

                    if (mocId != 0) {
                      batchQuery.add("insert into mocrelate(MOCID,ContactType," + "ContactID,isPrimary) values(" + mocId + ",2," + individualID + ",'YES')");

                      if (entityPrimaryFlag) {
                        batchQuery.add( "insert into mocrelate(MOCID,ContactType," + "ContactID,isPrimary) values(" + mocId + ",1," + entId + ",'YES')");
                      }
                    }
                  } catch (Exception e) {
                    logger.error("[Exception] ListEJB.getImportList: ", e);
                  }
                }

                // set Email
                if ((email != null) && (!email.equals(""))) {
                  try {
                    dl.setSql("contact.addmoc");
                    dl.setInt(1, Constants.MOC_EMAIL);
                    dl.setString(2, email);
                    dl.setString(3, ""); //moc.getNote()
                    dl.setString(4, "Email");
                    dl.setString(5, ""); //moc.getMocOrder()
                    dl.executeUpdate();

                    int mocId = dl.getAutoGeneratedKey();
                    dl.clearParameters();

                    if (mocId != 0) {
                      batchQuery.add("insert into mocrelate(MOCID,ContactType," + "ContactID,isPrimary) values(" + mocId + ",2," + individualID + ",'YES')");

                      if (entityPrimaryFlag) {
                        batchQuery.add( "insert into mocrelate(MOCID,ContactType," + "ContactID,isPrimary) values(" + mocId + ",1," + entId + ",'YES')");
                      }
                    }
                  } catch (Exception e) {
                    logger.error("[Exception] ListEJB.getImportList: ", e);
                  }
                }

                if ((CustomIndList != null) && (CustomIndList.size() > 0)) {
                  Iterator it = CustomIndList.iterator();

                  while (it.hasNext()) {
                    DDNameValue ddname = (DDNameValue) it.next();

                    String id = ddname.getName();
                    String type = null;
                    StringTokenizer st = new StringTokenizer(id, "*");

                    while (st.hasMoreTokens()) {
                      id = (String) st.nextToken();
                      type = (String) st.nextToken();
                    }

                    String name = ddname.getStrid();
                    String customIndividualName = (String) hCols.get(name);

                    if (type != null) {
                      //Scalar Value
                      if (type.equals("SCALAR")) {
                        if ((customIndividualName != null) && !customIndividualName.equals("")) {
                          batchQuery.add("insert into customfieldscalar " + "(customfieldid,recordid,value) values " + "(" + id + "," + individualID + ",'" + customIndividualName + "')");
                        }
                      }

                      //Multiple Value
                      if (type.equals("MULTIPLE")) {
                        int indexName = name.indexOf("(");

                        if (indexName > 0) {
                          customIndividualName = customIndividualName + "*" + name.substring(0, indexName);
                        }

                        boolean customFlag = CustomFieldValues.containsKey(customIndividualName);

                        if (customFlag) {
                          String fieldId = (String) CustomFieldValues.get(customIndividualName);
                          String valueId = null;
                          st = null;
                          st = new StringTokenizer(fieldId, "*");

                          while (st.hasMoreTokens()) {
                            valueId = (String) st.nextToken();
                            fieldId = (String) st.nextToken();
                          }

                          if (valueId != null) {
                            if (fieldId.equals(id)) {
                              batchQuery.add("insert into customfieldmultiple " + "(customfieldid,recordid,valueid) values " + "(" + id + "," + individualID + "," + valueId + ")");
                            }
                          }
                        }
                      }
                    }
                  }
                }
              }
            }
          }
        }

        if (! errMsg.equals("")) {
          // TODO: Hardcoded text needs i18n support!
          errMsg = errMsg.substring(0, (errMsg.length() - 1));
          errLineNumber.put((i + headerRow + 1) + "", (i + headerRow + 1) + " " + showLine + "... " + errMsg);
          msgLineNumber.put((i + headerRow + 1) + "", line + tabDelimiter + (i + headerRow + 1) + tabDelimiter + errMsg + lineDelimiter);
        }

        // Its good thing to remove the processed line from the memory.
        // So that we will release the memory.
        importList.remove(0);
      }

      try {
        int[] batchResult = dl.batchProcess(batchQuery);
        dl.clearParameters();
      } catch (Exception e) {
        e.printStackTrace();
      }

      dl.destroy();

      // TODO: Hardcoded text needs i18n support!

      if ((errLineNumber != null) && (errLineNumber.size() == 0)) {
        count = count - errCounter;
        messageList.put("importMessage","Imported " + count + " records succesfully.");
      }

      if (count == 0) {
        messageList.put("importMessage", "No records found in the imported file!");
      }

      if ((errLineNumber != null) && (errLineNumber.size() > 0)) {
        Set key = errLineNumber.keySet();
        String LineNumber = "";
        Iterator iterator;
        iterator = key.iterator();

        while (iterator.hasNext()) {
          String keyValue = (String) iterator.next();

          importInputStream.append(msgLineNumber.get(keyValue));
          LineNumber = LineNumber + (String) errLineNumber.get(keyValue);

        }

        if ((LineNumber != null) && (!LineNumber.equals(""))) {
          count = count - errCounter;
          String importMessage = "Imported " + count + " records succesfully.";
          importMessage = importMessage + "Failed to import " + errCounter + " records.";
          messageList.put("importMessage", importMessage);
          messageList.put("lineErrorMessage", LineNumber);
        }

        try {
          CvFileFacade cvf = new CvFileFacade();
          CvFileLocalHome homeFile = (CvFileLocalHome) ic.lookup("local/CvFile");
          CvFileLocal remoteFile = (CvFileLocal) homeFile.create();
          remoteFile.setDataSource(this.dataSource);

          CvFolderVO homeFld = remoteFile.getHomeFolder(indvID);

          int rn = (new Random()).nextInt();
          Calendar c = Calendar.getInstance();
          java.util.Date dt = c.getTime();
          DateFormat df = new SimpleDateFormat("MM_dd_yyyy");
          String dateStamp = df.format(dt);

          CvFileVO flvo = new CvFileVO();
          flvo.setTitle("Error Log");
          flvo.setName("errorLog_" + indvID + "_" + rn + "_" + dateStamp + ".txt");
          messageList.put("fileName","errorLog_" + indvID + "_" + rn + "_" + dateStamp + ".txt");

          flvo.setPhysicalFolder(homeFld.getFolderId());
          flvo.setIsTemporary("NO");
          flvo.setOwner(indvID);

          //flvo.setAuthor(indvID);
          flvo.setPhysical(CvFileVO.FP_PHYSICAL);

          StringBufferInputStream stringInputStream = new StringBufferInputStream(importInputStream.toString());
          int fileId = cvf.addFile(indvID, homeFld.getFolderId(), flvo, stringInputStream, this.dataSource);
          messageList.put("fileID",fileId + "");
        } catch (Exception e) {
          logger.error("[Exception] ListEJB.getImportList: ", e);
        }
      }
     
      // We collect a set of newly created individual and entity and then we will set permission on the Individual and Entity
      // on basis of the Marketing List's Member Permission
      if (newIndividualList.size() != 0 || newEntityList.size() != 0) {
        AuthorizationLocalHome authorizationHome = (AuthorizationLocalHome)ic.lookup("local/Authorization");
        AuthorizationLocal remoteAuth = authorizationHome.create();
        remoteAuth.setDataSource(this.dataSource);
        remoteAuth.saveMarketingRecordPermission(newIndividualList, newEntityList, listid);
      }
    } catch (Exception e) {
      logger.error("[Exception] ListEJB.getImportList: ", e);
    }
    return messageList;
  }

  public boolean addListMember(int userId, int listid, HashMap info)
  {
    System.out.println("---###---  ListEJB.addListMember() called! Defunct method should be removed!");
    return true;
  }

  public boolean deleteListMember(int userId, int listid, HashMap info)
  {
    System.out.println("---###---  ListEJB.deleteListMember() called! Defunct method should be removed!");
    return true;
  }

  public boolean updateListMember(int userId, int listid, HashMap info)
  {
    System.out.println("---###---  ListEJB.updateListMember() called! Defunct method should be removed!");
    return true;
  }

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

}
TOP

Related Classes of com.centraview.marketing.List.ListEJB

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.