/**
  * Saves the entity.
  *
  * @return the SUCCESS result
  */
 public String save() throws Exception {
   TargetList originalTargetList = saveEntity();
   final Collection<ChangeLog> changeLogs = changeLog(originalTargetList, targetList);
   if ("Campaign".equals(this.getRelationKey())) {
     Campaign campaign =
         campaignService.getEntityById(Campaign.class, Integer.valueOf(this.getRelationValue()));
     Set<Campaign> campaigns = targetList.getCampaigns();
     if (campaigns == null) {
       campaigns = new HashSet<Campaign>();
     }
     campaigns.add(campaign);
   }
   targetList = getBaseService().makePersistent(targetList);
   this.setId(targetList.getId());
   this.setSaveFlag("true");
   if (changeLogs != null) {
     taskExecutor.execute(
         new Runnable() {
           public void run() {
             batchInserChangeLogs(changeLogs);
           }
         });
   }
   return SUCCESS;
 }
  /**
   * Unselects the entities
   *
   * @return the SUCCESS result
   */
  public String unselect() throws ServiceException {
    Campaign campaign = null;
    Set<TargetList> targetLists = null;

    if ("Campaign".equals(this.getRelationKey())) {
      campaign =
          campaignService.getEntityById(Campaign.class, Integer.valueOf(this.getRelationValue()));
      targetLists = campaign.getTargetLists();
    }

    if (this.getSeleteIDs() != null) {
      String[] ids = seleteIDs.split(",");
      Collection<TargetList> selectedTargetLists = new ArrayList<TargetList>();
      for (int i = 0; i < ids.length; i++) {
        Integer selectId = Integer.valueOf(ids[i]);
        A:
        for (TargetList targetList : targetLists) {
          if (targetList.getId().intValue() == selectId.intValue()) {
            selectedTargetLists.add(targetList);
            break A;
          }
        }
      }
      targetLists.removeAll(selectedTargetLists);
    }

    if ("Campaign".equals(this.getRelationKey())) {
      campaignService.makePersistent(campaign);
    }
    return SUCCESS;
  }
 /**
  * Copies the selected entities
  *
  * @return the SUCCESS result
  */
 public String copy() throws Exception {
   UserUtil.permissionCheck("create_targetList");
   if (this.getSeleteIDs() != null) {
     String[] ids = seleteIDs.split(",");
     for (int i = 0; i < ids.length; i++) {
       String copyid = ids[i];
       TargetList oriRecord = baseService.getEntityById(TargetList.class, Integer.valueOf(copyid));
       TargetList targetListRecord = oriRecord.clone();
       targetListRecord.setId(null);
       this.getbaseService().makePersistent(targetListRecord);
     }
   }
   return SUCCESS;
 }
 public String relateTargetListUser() throws Exception {
   targetList = baseService.getEntityById(TargetList.class, id);
   Set<User> users = targetList.getUsers();
   Iterator<User> userIterator = users.iterator();
   int totalRecords = users.size();
   ListUserAction.getListJson(userIterator, totalRecords, null, false);
   return null;
 }
 public String relateTargetListTarget() throws Exception {
   targetList = baseService.getEntityById(TargetList.class, id);
   Set<Target> targets = targetList.getTargets();
   Iterator<Target> targetIterator = targets.iterator();
   long totalRecords = targets.size();
   ListTargetAction.getListJson(targetIterator, totalRecords, null, false);
   return null;
 }
 /**
  * Gets the related leads.
  *
  * @return null
  */
 public String relateTargetListLead() throws Exception {
   targetList = baseService.getEntityById(TargetList.class, id);
   Set<Lead> leads = targetList.getLeads();
   Iterator<Lead> leadIterator = leads.iterator();
   long totalRecords = leads.size();
   ListLeadAction.getListJson(leadIterator, totalRecords, null, false);
   return null;
 }
  /**
   * Imports the entities
   *
   * @return the SUCCESS result
   */
  public String importCSV() throws Exception {
    File file = this.getUpload();
    CsvListReader reader = new CsvListReader(new FileReader(file), CsvPreference.EXCEL_PREFERENCE);
    int failedNum = 0;
    int successfulNum = 0;
    try {
      final String[] header = reader.getCSVHeader(true);

      List<String> line = new ArrayList<String>();
      Map<String, String> failedMsg = new HashMap<String, String>();
      while ((line = reader.read()) != null) {

        Map<String, String> row = new HashMap<String, String>();
        for (int i = 0; i < line.size(); i++) {
          row.put(header[i], line.get(i));
        }

        TargetList targetList = new TargetList();
        try {
          String id = row.get(getText("entity.id.label"));
          if (!CommonUtil.isNullOrEmpty(id)) {
            targetList.setId(Integer.parseInt(id));
          }
          targetList.setName(CommonUtil.fromNullToEmpty(row.get(getText("entity.name.label"))));
          targetList.setDescription(
              CommonUtil.fromNullToEmpty(row.get(getText("entity.description.label"))));
          targetList.setNotes(CommonUtil.fromNullToEmpty(row.get(getText("entity.notes.label"))));
          String assignedToID = row.get(getText("entity.assigned_to_id.label"));
          if (CommonUtil.isNullOrEmpty(assignedToID)) {
            targetList.setAssigned_to(null);
          } else {
            User assignedTo = userService.getEntityById(User.class, Integer.parseInt(assignedToID));
            targetList.setAssigned_to(assignedTo);
          }
          baseService.makePersistent(targetList);
          successfulNum++;
        } catch (Exception e) {
          failedNum++;
          String Name = CommonUtil.fromNullToEmpty(targetList.getName());
          failedMsg.put(Name, e.getMessage());
        }
      }

      this.setFailedMsg(failedMsg);
      this.setFailedNum(failedNum);
      this.setSuccessfulNum(successfulNum);
      this.setTotalNum(successfulNum + failedNum);
    } finally {
      reader.close();
    }
    return SUCCESS;
  }
 /**
  * Gets the entity.
  *
  * @return the SUCCESS result
  */
 public String get() throws Exception {
   if (this.getId() != null) {
     targetList = baseService.getEntityById(TargetList.class, this.getId());
     User assignedTo = targetList.getAssigned_to();
     if (assignedTo != null) {
       this.setAssignedToID(assignedTo.getId());
       this.setAssignedToText(assignedTo.getName());
     }
     this.getBaseInfo(targetList, TargetList.class.getSimpleName(), Constant.CRM_NAMESPACE);
   } else {
     this.initBaseInfo();
   }
   return SUCCESS;
 }
 /** Mass update entity record information */
 public String massUpdate() throws Exception {
   saveEntity();
   String[] fieldNames = this.massUpdate;
   if (fieldNames != null) {
     String[] selectIDArray = this.seleteIDs.split(",");
     Collection<TargetList> targetLists = new ArrayList<TargetList>();
     User loginUser = this.getLoginUser();
     User user = userService.getEntityById(User.class, loginUser.getId());
     Collection<ChangeLog> allChangeLogs = new ArrayList<ChangeLog>();
     for (String IDString : selectIDArray) {
       int id = Integer.parseInt(IDString);
       TargetList targetListInstance = this.baseService.getEntityById(TargetList.class, id);
       TargetList originalTargetList = targetListInstance.clone();
       for (String fieldName : fieldNames) {
         Object value = BeanUtil.getFieldValue(targetList, fieldName);
         BeanUtil.setFieldValue(targetListInstance, fieldName, value);
       }
       targetListInstance.setUpdated_by(user);
       targetListInstance.setUpdated_on(new Date());
       Collection<ChangeLog> changeLogs = changeLog(originalTargetList, targetListInstance);
       allChangeLogs.addAll(changeLogs);
       targetLists.add(targetListInstance);
     }
     final Collection<ChangeLog> changeLogsForSave = allChangeLogs;
     if (targetLists.size() > 0) {
       this.baseService.batchUpdate(targetLists);
       taskExecutor.execute(
           new Runnable() {
             public void run() {
               batchInserChangeLogs(changeLogsForSave);
             }
           });
     }
   }
   return SUCCESS;
 }
  private InputStream getDownloadContent(boolean isTemplate) throws Exception {
    UserUtil.permissionCheck("view_targetList");
    String fileName = getText("entity.targetList.label") + ".csv";
    fileName = new String(fileName.getBytes(), "ISO8859-1");
    File file = new File(fileName);
    ICsvMapWriter writer = new CsvMapWriter(new FileWriter(file), CsvPreference.EXCEL_PREFERENCE);
    try {
      final String[] header =
          new String[] {
            getText("entity.id.label"),
            getText("entity.name.label"),
            getText("entity.description.label"),
            getText("entity.notes.label"),
            getText("entity.assigned_to_id.label"),
            getText("entity.assigned_to_name.label")
          };
      writer.writeHeader(header);
      if (!isTemplate) {
        String[] ids = seleteIDs.split(",");
        for (int i = 0; i < ids.length; i++) {
          String id = ids[i];
          TargetList targetList = baseService.getEntityById(TargetList.class, Integer.parseInt(id));
          final HashMap<String, ? super Object> data1 = new HashMap<String, Object>();
          data1.put(header[0], targetList.getId());
          data1.put(header[1], CommonUtil.fromNullToEmpty(targetList.getName()));
          data1.put(header[2], CommonUtil.fromNullToEmpty(targetList.getDescription()));
          data1.put(header[3], CommonUtil.fromNullToEmpty(targetList.getNotes()));
          if (targetList.getAssigned_to() != null) {
            data1.put(header[4], targetList.getAssigned_to().getId());
            data1.put(header[5], targetList.getAssigned_to().getName());
          } else {
            data1.put(header[4], "");
            data1.put(header[5], "");
          }
          writer.write(data1, header);
        }
      }
    } catch (Exception e) {
      throw e;
    } finally {
      writer.close();
    }

    InputStream in = new FileInputStream(file);
    this.setFileName(fileName);
    return in;
  }
  private Collection<ChangeLog> changeLog(TargetList originalTargetList, TargetList targetList) {
    Collection<ChangeLog> changeLogs = null;
    if (originalTargetList != null) {
      ActionContext context = ActionContext.getContext();
      Map<String, Object> session = context.getSession();
      String entityName = TargetList.class.getSimpleName();
      Integer recordID = targetList.getId();
      User loginUser = (User) session.get(AuthenticationSuccessListener.LOGIN_USER);
      changeLogs = new ArrayList<ChangeLog>();

      String oldName = CommonUtil.fromNullToEmpty(originalTargetList.getName());
      String newName = CommonUtil.fromNullToEmpty(targetList.getName());
      if (!oldName.equals(newName)) {
        ChangeLog changeLog =
            saveChangeLog(entityName, recordID, "entity.name.label", oldName, newName, loginUser);
        changeLogs.add(changeLog);
      }

      String oldDescription = CommonUtil.fromNullToEmpty(originalTargetList.getDescription());
      String newDescription = CommonUtil.fromNullToEmpty(targetList.getDescription());
      if (!oldDescription.equals(newDescription)) {
        ChangeLog changeLog =
            saveChangeLog(
                entityName,
                recordID,
                "entity.description.label",
                oldDescription,
                newDescription,
                loginUser);
        changeLogs.add(changeLog);
      }

      String oldNotes = CommonUtil.fromNullToEmpty(originalTargetList.getNotes());
      String newNotes = CommonUtil.fromNullToEmpty(targetList.getNotes());
      if (!oldNotes.equals(newNotes)) {
        ChangeLog changeLog =
            saveChangeLog(
                entityName, recordID, "entity.notes.label", oldNotes, newNotes, loginUser);
        changeLogs.add(changeLog);
      }

      String oldAssignedToName = "";
      User oldAssignedTo = originalTargetList.getAssigned_to();
      if (oldAssignedTo != null) {
        oldAssignedToName = oldAssignedTo.getName();
      }
      String newAssignedToName = "";
      User newAssignedTo = targetList.getAssigned_to();
      if (newAssignedTo != null) {
        newAssignedToName = newAssignedTo.getName();
      }
      if (oldAssignedToName != newAssignedToName) {
        ChangeLog changeLog =
            saveChangeLog(
                entityName,
                recordID,
                "entity.assigned_to.label",
                CommonUtil.fromNullToEmpty(oldAssignedToName),
                CommonUtil.fromNullToEmpty(newAssignedToName),
                loginUser);
        changeLogs.add(changeLog);
      }
    }
    return changeLogs;
  }
  /**
   * Saves entity field
   *
   * @return original TargetList record
   * @throws Exception
   */
  private TargetList saveEntity() throws Exception {
    TargetList originalTargetList = null;
    if (targetList.getId() == null) {
      UserUtil.permissionCheck("create_targetList");
    } else {
      UserUtil.permissionCheck("update_targetList");
      originalTargetList = baseService.getEntityById(TargetList.class, targetList.getId());
      targetList.setTargets(originalTargetList.getTargets());
      targetList.setContacts(originalTargetList.getContacts());
      targetList.setLeads(originalTargetList.getLeads());
      targetList.setUsers(originalTargetList.getUsers());
      targetList.setAccounts(originalTargetList.getAccounts());
    }

    User assignedTo = null;
    if (this.getAssignedToID() != null) {
      assignedTo = userService.getEntityById(User.class, this.getAssignedToID());
    }
    targetList.setAssigned_to(assignedTo);

    User owner = null;
    if (this.getOwnerID() != null) {
      owner = userService.getEntityById(User.class, this.getOwnerID());
    }
    targetList.setOwner(owner);

    super.updateBaseInfo(targetList);
    return originalTargetList;
  }
  /**
   * Gets the list JSON data.
   *
   * @return list JSON data
   */
  public static void getListJson(
      Iterator<TargetList> targetLists,
      long totalRecords,
      SearchCondition searchCondition,
      boolean isList)
      throws Exception {

    StringBuilder jsonBuilder = new StringBuilder("");
    jsonBuilder.append(getJsonHeader(totalRecords, searchCondition, isList));

    String assignedTo = null;
    while (targetLists.hasNext()) {
      TargetList instance = targetLists.next();
      int id = instance.getId();
      String name = CommonUtil.fromNullToEmpty(instance.getName());
      String description = CommonUtil.fromNullToEmpty(instance.getDescription());
      User user = instance.getAssigned_to();
      if (user != null) {
        assignedTo = user.getName();
      } else {
        assignedTo = "";
      }

      if (isList) {
        User createdBy = instance.getCreated_by();
        String createdByName = "";
        if (createdBy != null) {
          createdByName = CommonUtil.fromNullToEmpty(createdBy.getName());
        }
        User updatedBy = instance.getUpdated_by();
        String updatedByName = "";
        if (updatedBy != null) {
          updatedByName = CommonUtil.fromNullToEmpty(updatedBy.getName());
        }
        SimpleDateFormat dateFormat = new SimpleDateFormat(Constant.DATE_TIME_FORMAT);
        Date createdOn = instance.getCreated_on();
        String createdOnName = "";
        if (createdOn != null) {
          createdOnName = dateFormat.format(createdOn);
        }
        Date updatedOn = instance.getUpdated_on();
        String updatedOnName = "";
        if (updatedOn != null) {
          updatedOnName = dateFormat.format(updatedOn);
        }

        jsonBuilder
            .append("{\"cell\":[\"")
            .append(id)
            .append("\",\"")
            .append(name)
            .append("\",\"")
            .append(description)
            .append("\",\"")
            .append(assignedTo)
            .append("\",\"")
            .append(createdByName)
            .append("\",\"")
            .append(updatedByName)
            .append("\",\"")
            .append(createdOnName)
            .append("\",\"")
            .append(updatedOnName)
            .append("\"]}");
      } else {
        jsonBuilder
            .append("{\"id\":\"")
            .append(id)
            .append("\",\"name\":\"")
            .append(name)
            .append("\",\"assigned_to.name\":\"")
            .append(assignedTo)
            .append("\"}");
      }
      if (targetLists.hasNext()) {
        jsonBuilder.append(",");
      }
    }
    jsonBuilder.append("]}");

    // Returns JSON data back to page
    HttpServletResponse response = ServletActionContext.getResponse();
    response.setContentType("text/html;charset=UTF-8");
    response.getWriter().write(jsonBuilder.toString());
  }