public static Column getObject(HttpServletRequest request) {
   Column column = CCManager.getColumnInstance();
   try {
     column.setCreator(AuthHandler.getUserid(request));
     column.setType(Integer.parseInt(request.getParameter("typeid")));
     column.setHeader(request.getParameter("header"));
     column.setModule(request.getParameter("module"));
     if (!StringUtil.isNullOrEmpty("masterdata")) {
       column.setMasterString(request.getParameter("masterdata"));
     }
     if (!StringUtil.isNullOrEmpty(request.getParameter("enabled"))) {
       column.setEnabled(request.getParameter("enabled").equals("on") ? true : false);
     }
     if (!StringUtil.isNullOrEmpty(request.getParameter("visible"))) {
       column.setVisible(request.getParameter("visible").equals("on") ? true : false);
     }
     if (!StringUtil.isNullOrEmpty(request.getParameter("isMandatory"))) {
       column.setMandatory(request.getParameter("isMandatory").equals("on") ? true : false);
     }
     if (!StringUtil.isNullOrEmpty("defaultValue")) {
       column.setDefaultValue(request.getParameter("defaultValue"));
     }
   } catch (SessionExpiredException ex) {
     Logger.getLogger(CcUtil.class.getName()).log(Level.SEVERE, null, ex);
   }
   return column;
 }
  public void saveDocumentMapping(JSONObject jobj) throws ServiceException {
    try {
      Docmap docMap = new Docmap();

      if (jobj.has("docid") && !StringUtil.isNullOrEmpty(jobj.getString("docid"))) {
        Docs doc = (Docs) hibernateTemplate.get(Docs.class, jobj.getString("docid"));
        docMap.setDocid(doc);
        if (jobj.has("companyid") && !StringUtil.isNullOrEmpty(jobj.getString("companyid"))) {
          Company company =
              (Company) hibernateTemplate.get(Company.class, jobj.getString("companyid"));
          doc.setCompany(company);
        }
        if (jobj.has("userid") && !StringUtil.isNullOrEmpty(jobj.getString("userid"))) {
          User user = (User) hibernateTemplate.get(User.class, jobj.getString("userid"));
          doc.setUserid(user);
        }
      }
      if (jobj.has("refid")) {
        docMap.setRecid(jobj.getString("refid"));
      }
      if (jobj.has("map")) {
        docMap.setRelatedto(jobj.getString("map"));
      }
      hibernateTemplate.save(docMap);
    } catch (Exception ex) {
      throw ServiceException.FAILURE("documentDAOImpl.saveDocumentMapping", ex);
    }
  }
  @Override
  public KwlReturnObject saveAccountProject(JSONObject jobj1) throws ServiceException {
    JSONObject jobj = new JSONObject();
    List ll = new ArrayList();
    try {
      String companyid = jobj1.getString("companyid");
      String userid = jobj1.getString("userid");
      String projectName = jobj1.getString("projectName");
      String accId = jobj1.getString("accId");
      jobj.put("projectname", projectName);
      jobj.put("companyid", companyid);
      jobj.put("userid", userid);
      jobj.put("remoteapikey", ConfigReader.getinstance().get("remoteapikey"));

      jobj = apiCallHandlerService.callApp(jobj1.getString("appURL"), jobj, companyid, "12", true);
      if (jobj.has("success") && jobj.getBoolean("success")) {
        jobj = jobj.getJSONObject("data");
        String projectId = jobj.getString("projectid");
        String nickName = jobj.getString("nickname");

        AccountProject ap = new AccountProject();

        if (!StringUtil.isNullOrEmpty(accId)) {
          ap.setAccountId((CrmAccount) get(CrmAccount.class, accId));
        }
        if (!StringUtil.isNullOrEmpty(nickName)) {
          ap.setNickName(nickName);
        }
        if (!StringUtil.isNullOrEmpty(projectId)) {
          ap.setProjectId(projectId);
        }
        if (!StringUtil.isNullOrEmpty(projectName)) {
          ap.setProjectName(projectName);
        }

        save(ap);
        jobj = new JSONObject();
        jobj.put("projectid", ap.getProjectId());
      } else {
        String errorCode = jobj.getString("errorcode");
        jobj = new JSONObject();
        jobj.put("errorcode", errorCode);
      }
      ll.add(jobj);
    } catch (JSONException e) {
      logger.warn(e.getMessage(), e);
      throw ServiceException.FAILURE("crmAccountDAOImpl.saveAccountProject : " + e.getMessage(), e);
    } catch (HibernateException e) {
      logger.warn(e.getMessage(), e);
      throw ServiceException.FAILURE("crmAccountDAOImpl.saveAccountProject : " + e.getMessage(), e);
    } catch (Exception e) {
      logger.warn(e.getMessage(), e);
      throw ServiceException.FAILURE("crmAccountDAOImpl.saveAccountProject : " + e.getMessage(), e);
    }
    return new KwlReturnObject(true, KWLErrorMsgs.S01, "", ll, 0);
  }
 public static String getAllLog(
     Connection conn,
     HttpServletRequest request,
     String companyid,
     String limit,
     String offset,
     String searchString,
     String dateString)
     throws ServiceException {
   ResultSet rs1 = null;
   String returnStr = "";
   String[] searchStrObj = new String[] {"params", "actiontext"};
   String myLikeString = StringUtil.getMySearchString(searchString, "and", searchStrObj);
   PreparedStatement pstmt = null;
   JSONObject resobj = new JSONObject();
   JSONObject tempobj = new JSONObject();
   JSONArray jarr = new JSONArray();
   try {
     int count1 = 0;
     pstmt =
         conn.prepareStatement(
             "select count(*) AS count from actionlog al inner join actions a on al.actionid = a.actionid where companyid = ?"
                 + myLikeString
                 + dateString);
     pstmt.setString(1, companyid);
     StringUtil.insertParamSearchString(2, pstmt, searchString, searchStrObj.length);
     rs1 = pstmt.executeQuery();
     if (rs1.next()) {
       count1 = rs1.getInt("count");
     }
     String query1 =
         "select logid, al.actionid, actionby, projectid, params, timestamp from actionlog al inner join actions a on al.actionid = a.actionid where companyid = ?"
             + myLikeString
             + dateString
             + " order by timestamp DESC limit ? offset ?";
     pstmt = conn.prepareStatement(query1);
     pstmt.setString(1, companyid);
     int cnt = StringUtil.insertParamSearchString(2, pstmt, searchString, searchStrObj.length);
     pstmt.setInt(cnt++, Integer.parseInt(limit));
     pstmt.setInt(cnt++, Integer.parseInt(offset));
     rs1 = pstmt.executeQuery();
     while (rs1.next()) {
       tempobj = getJsonForAction(conn, pstmt, rs1, request, "all");
       jarr.put(tempobj);
     }
     resobj.put("data", jarr);
     resobj.put("count", count1);
     returnStr = resobj.toString();
   } catch (ServiceException ex) {
     throw ServiceException.FAILURE("AuditTrail.getAllLog", ex);
   } catch (SQLException ex) {
     throw ServiceException.FAILURE("AuditTrail.getAllLog", ex);
   } finally {
     return returnStr;
   }
 }
 public void setCustomData(CrmAccount crmAcc, JSONArray cstmData) {
   StringBuffer fields = new StringBuffer("accountid,company");
   StringBuffer qmarks = new StringBuffer("?,?");
   ArrayList params = new ArrayList();
   params.add(crmAcc.getAccountid());
   params.add(crmAcc.getCompany().getCompanyID());
   boolean hasValue = false;
   try {
     for (int i = 0; i < cstmData.length(); i++) {
       JSONObject jobj = cstmData.getJSONObject(i);
       if (jobj.has(Constants.Crm_custom_field)) {
         String fieldname = jobj.getString(Constants.Crm_custom_field);
         String fielddbname = jobj.getString(fieldname);
         String fieldValue = jobj.getString(fielddbname);
         hasValue = true;
         fielddbname = fielddbname.replace("c", "C");
         Integer xtype = Integer.parseInt(jobj.getString("xtype"));
         if (!StringUtil.isNullOrEmpty(fieldValue)
             && !StringUtil.isNullOrEmpty(fieldValue.trim())
             && !fieldValue.equalsIgnoreCase(Constants.field_data_undefined)) {
           fields.append(',').append(fielddbname);
           qmarks.append(",?");
           params.add(fieldValue);
         } else {
           if (xtype == 7 || xtype == 8 || xtype == 4) {
             fields.append(',').append(fielddbname);
             qmarks.append(",?");
             params.add(null);
           } else {
             fields.append(',').append(fielddbname);
             qmarks.append(",?");
             params.add("");
           }
         }
       }
     }
   } catch (NumberFormatException e) {
     e.printStackTrace();
   } catch (JSONException e) {
     e.printStackTrace();
   }
   if (hasValue) {
     StringBuffer sql =
         new StringBuffer("insert into crmaccountcustomdata (")
             .append(fields)
             .append(")VALUES(")
             .append(qmarks)
             .append(')');
     updateJDBC(sql.toString(), params.toArray());
   }
 }
  public ModelAndView downloadDocuments(HttpServletRequest request, HttpServletResponse response)
      throws ServletException {
    JSONObject jobj = new JSONObject();
    JSONObject myjobj = new JSONObject();
    KwlReturnObject kmsg = null;
    String details = "";
    String auditAction = "";
    try {
      String url = request.getParameter("url");
      url = StringUtil.checkForNull(url);
      String applicant = request.getParameter("applicant");
      applicant = StringUtil.checkForNull(applicant);
      Hashtable ht;
      if (applicant.equalsIgnoreCase("applicant")) {
        kmsg = hrmsExtApplDocsDAOObj.downloadDocument(url);
        ht = getExtDocumentDownloadHash(kmsg.getEntityList());
      } else {
        kmsg = documentDAOObj.downloadDocument(url);
        ht = getDocumentDownloadHash(kmsg.getEntityList());
      }

      String src = storageHandlerImplObj.GetDocStorePath();
      //            String src = "/home/trainee/";
      if (request.getParameter("mailattch") != null) {
        src = src + ht.get("svnname");
      } else {
        src = src + ht.get("userid").toString() + "/" + ht.get("svnname");
      }

      File fp = new File(src);
      byte[] buff = new byte[(int) fp.length()];
      FileInputStream fis = new FileInputStream(fp);
      int read = fis.read(buff);
      javax.activation.FileTypeMap mmap = new javax.activation.MimetypesFileTypeMap();
      response.setContentType(mmap.getContentType(src));
      response.setContentLength((int) fp.length());
      response.setHeader(
          "Content-Disposition",
          request.getParameter("dtype") + "; filename=\"" + ht.get("Name") + "\";");
      response.getOutputStream().write(buff);
      response.getOutputStream().flush();
      response.getOutputStream().close();
      String map = ht.get("relatedto").toString();
      String refid = ht.get("recid").toString();

      myjobj.put("success", true);
    } catch (Exception e) {
      System.out.println(e.getMessage());
    }
    return new ModelAndView("jsonView", "model", myjobj.toString());
  }
  /* (non-Javadoc)
   * @see com.krawler.spring.crm.accountModule.crmAccountDAO#getAccountOwners(java.util.HashMap, java.util.ArrayList, java.util.ArrayList)
   */
  public KwlReturnObject getAccountOwners(
      HashMap<String, Object> requestParams, ArrayList filter_names, ArrayList filter_params)
      throws ServiceException {
    List ll = null;
    int dl = 0;
    try {
      String Hql = "";
      if (requestParams.containsKey("usersList") && requestParams.get("usersList") != null) {
        Hql =
            " select distinct c from accountOwners ao inner join ao.account c where c.crmLead.usersByCreatedbyid = c.usersByCreatedbyid.userID ";
        Hql += StringUtil.filterQuery(filter_names, "and");
        StringBuffer usersList = (StringBuffer) requestParams.get("usersList");
        Hql += " and ao.usersByUserid.userID in (" + usersList + ") ";
      } else {
        boolean distinctFlag = false;
        if (requestParams.containsKey("distinctFlag")
            && requestParams.get("distinctFlag") != null) {
          distinctFlag = (Boolean) requestParams.get("distinctFlag");
        }

        if (distinctFlag) {
          Hql = "select distinct c from accountOwners ao inner join ao.account c ";
        } else {
          Hql = "select ao, c from accountOwners ao inner join ao.account c ";
        }
        Hql += StringUtil.filterQuery(filter_names, "where");
      }

      ll = executeQuery(Hql, filter_params.toArray());
      dl = ll.size();
      boolean pagingFlag = false;
      if (requestParams.containsKey("pagingFlag") && requestParams.get("pagingFlag") != null) {
        pagingFlag = Boolean.parseBoolean(requestParams.get("pagingFlag").toString());
      }
      if (pagingFlag) {
        int start = 0;
        int limit = 25;
        if (requestParams.containsKey("start") && requestParams.containsKey("limit")) {
          start = Integer.parseInt(requestParams.get("start").toString());
          limit = Integer.parseInt(requestParams.get("limit").toString());
        }
        ll = executeQueryPaging(Hql, filter_params.toArray(), new Integer[] {start, limit});
      }
    } catch (Exception ex) {
      throw ServiceException.FAILURE("crmAccountDAOImpl.getAccountOwners : " + ex.getMessage(), ex);
    }
    return new KwlReturnObject(true, KWLErrorMsgs.S01, "", ll, dl);
  }
 private static int getCountQuery(
     Connection conn,
     PreparedStatement pstmt,
     String companyid,
     String likeClause,
     String myLikeString,
     String[] searchStrObj,
     String ss,
     String dateString)
     throws ServiceException, SQLException {
   int cnt = 0;
   ResultSet rs = null;
   pstmt =
       conn.prepareStatement(
           "select COUNT(*) AS count from actionlog al inner join actions a on al.actionid = a.actionid "
               + "where companyid = ? "
               + likeClause
               + myLikeString
               + dateString);
   pstmt.setString(1, companyid);
   StringUtil.insertParamSearchString(2, pstmt, ss, searchStrObj.length);
   rs = pstmt.executeQuery();
   if (rs.next()) {
     cnt = rs.getInt("count");
   }
   return cnt;
 }
 public KwlReturnObject getAuditDetails(HashMap<String, Object> requestParams)
     throws ServiceException {
   List ll = null;
   int dl = 0;
   try {
     StringBuffer usersList = null;
     if (requestParams.containsKey("userslist"))
       usersList = (StringBuffer) requestParams.get("userslist");
     String groups = requestParams.get("groups").toString();
     int start = Integer.parseInt(requestParams.get("start").toString());
     int limit = Integer.parseInt(requestParams.get("limit").toString());
     int interval = Integer.parseInt(requestParams.get("interval").toString());
     String query = "from AuditTrail at where";
     if (StringUtil.isNullOrEmpty(usersList.toString())) {
       query += " at.user.userID in (" + usersList + ")  and";
     }
     query +=
         " DATEDIFF(date(now()),date(at.auditTime)) <= ? and "
             + "at.action.auditGroup.groupName in ("
             + groups
             + ") order by at.auditTime desc";
     ll = HibernateUtil.executeQuery(hibernateTemplate, query, interval);
     dl = ll.size();
     ll =
         HibernateUtil.executeQueryPaging(
             hibernateTemplate, query, new Object[] {interval}, new Integer[] {start, limit});
   } catch (Exception e) {
     throw ServiceException.FAILURE(
         "auditTrailDAOImpl.getRecentActivityDetails : " + e.getMessage(), e);
   }
   return new KwlReturnObject(true, "002", "", ll, dl);
 }
  public KwlReturnObject getDocumentList(
      HashMap<String, Object> requestParams, StringBuffer usersList) throws ServiceException {
    String tagSearch = requestParams.containsKey("tag") ? requestParams.get("tag").toString() : "";
    String quickSearch = requestParams.containsKey("ss") ? requestParams.get("ss").toString() : "";
    int start = 0;
    int limit = 20;
    int dl = 0;
    Object[] params = null;
    if (requestParams.containsKey("start")
        && requestParams.containsKey("limit")
        && !StringUtil.isNullOrEmpty(requestParams.get("start").toString())) {
      start = Integer.parseInt(requestParams.get("start").toString());
      limit = Integer.parseInt(requestParams.get("limit").toString());
    }
    List ll = null;
    try {
      String companyid = requestParams.get("companyid").toString();
      String Hql =
          "select c from com.krawler.common.admin.Docmap c where c.docid.company.companyID=? ";
      params = new Object[] {companyid};

      if (!StringUtil.isNullOrEmpty(tagSearch)) {
        tagSearch = tagSearch.replaceAll("'", "");
        Hql += " and c.docid.tags like '%" + tagSearch + "%' ";
      }
      if (!StringUtil.isNullOrEmpty(quickSearch)) {
        Hql += " and c.docid.docname like '" + quickSearch + "%' ";
      }

      String selectInQuery =
          Hql
              + " and c.docid.userid.userID in ("
              + usersList
              + ") order by c.docid.uploadedon desc ";
      ll = HibernateUtil.executeQuery(hibernateTemplate, selectInQuery, params);
      dl = ll.size();

      ll =
          HibernateUtil.executeQueryPaging(
              hibernateTemplate, selectInQuery, params, new Integer[] {start, limit});
    } catch (ServiceException ex) {
      throw ServiceException.FAILURE("documentDAOImpl.getDocumentList", ex);
    }
    return new KwlReturnObject(true, KwlReturnMsg.S01, "", ll, dl);
  }
 public static JSONObject getJsonForAction(
     Connection conn,
     PreparedStatement pstmt,
     ResultSet rs,
     HttpServletRequest request,
     String callerFlag)
     throws ServiceException {
   java.text.SimpleDateFormat sdf1 = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
   JSONObject jobj = new JSONObject();
   ResultSet rs2 = null;
   try {
     int aid = rs.getInt("actionid");
     String author = AuthHandler.getAuthor(conn, rs.getString("actionby"));
     String params = rs.getString("params");
     String userparam[] = params.split(",");
     String query2 = "select textkey from actions where actionid = ?";
     pstmt = conn.prepareStatement(query2);
     pstmt.setInt(1, aid);
     rs2 = pstmt.executeQuery();
     Object[] strParam = new Object[userparam.length];
     for (int i = 0; i < userparam.length; i++) {
       strParam[i] = userparam[i];
     }
     rs2.next();
     String action = rs2.getString("textkey");
     String useraction = MessageSourceProxy.getMessage(action, strParam, request);
     String sdtStr =
         Timezone.toCompanyTimezone(
             conn, rs.getTimestamp("timestamp").toString(), AuthHandler.getCompanyid(request));
     jobj.put("logid", rs.getInt("logid"));
     jobj.put("actionby", author);
     jobj.put("description", useraction);
     if (callerFlag.equals("all") || callerFlag.equals("projname")) {
       String projectname = "";
       String projid = rs.getString("projectid");
       if (!StringUtil.isNullOrEmpty(projid)) {
         projectname = projdb.getProjectName(conn, projid);
       }
       jobj.put("projname", projectname);
     }
     jobj.put("timestamp", sdtStr);
   } catch (ServiceException ex) {
     Logger.getLogger(AuditTrail.class.getName()).log(Level.SEVERE, null, ex);
   } catch (JSONException ex) {
     throw ServiceException.FAILURE("AuditTrail.getJsonForAction", ex);
   } catch (Exception ex) {
     throw ServiceException.FAILURE("AuditTrail.getJsonForAction", ex);
   } finally {
     return jobj;
   }
 }
  /* (non-Javadoc)
   * @see com.krawler.spring.crm.accountModule.crmAccountDAO#getAccountProducts(java.util.ArrayList, java.util.ArrayList)
   */
  public KwlReturnObject getAccountProducts(ArrayList filter_names, ArrayList filter_params)
      throws ServiceException {
    List ll = null;
    int dl = 0;
    try {
      String Hql = "from AccountProducts ap ";
      String filterQuery = StringUtil.filterQuery(filter_names, "where");
      Hql += filterQuery;
      String selectInQuery = Hql;

      ll = executeQuery(selectInQuery, filter_params.toArray());
      dl = ll.size();
    } catch (Exception ex) {
      throw ServiceException.FAILURE(
          "crmAccountDAOImpl.getAccountProducts : " + ex.getMessage(), ex);
    }
    return new KwlReturnObject(true, KWLErrorMsgs.S01, "", ll, dl);
  }
 /* (non-Javadoc)
  * @see com.krawler.spring.crm.accountModule.crmAccountDAO#getAccountRevenue(java.util.HashMap, java.util.ArrayList, java.util.ArrayList)
  */
 public double getAccountRevenue(
     HashMap<String, Object> requestParams, ArrayList filter_names, ArrayList filter_params)
     throws ServiceException {
   List ll = null;
   double revenue = 0.0;
   try {
     String hql = "select distinct c.accountid from accountOwners ao inner join ao.account c ";
     hql += StringUtil.filterQuery(filter_names, "where");
     hql = " select sum(ca.revenue) from CrmAccount ca where ca.accountid in(" + hql + ")";
     ll = executeQuery(hql, filter_params.toArray());
     if (ll != null && ll.size() > 0) {
       revenue = ll.get(0) == null ? 0 : Double.parseDouble((String) ll.get(0));
     }
   } catch (Exception ex) {
     throw ServiceException.FAILURE("crmAccountDAOImpl.getAccountOwners : " + ex.getMessage(), ex);
   }
   return revenue;
 }
  public void insertAuditLog(
      AuditAction action, String details, HttpServletRequest request, String recid, String extraid)
      throws ServiceException {
    try {
      User user =
          (User) hibernateTemplate.load(User.class, sessionHandlerImplObj.getUserid(request));
      String ipaddr = null;
      if (StringUtil.isNullOrEmpty(request.getHeader("x-real-ip"))) {
        ipaddr = request.getRemoteAddr();
      } else {
        ipaddr = request.getHeader("x-real-ip");
      }

      insertAuditLog(action, details, ipaddr, user, recid, extraid);
    } catch (Exception e) {
      throw ServiceException.FAILURE(e.getMessage(), e);
    }
  }
  /* (non-Javadoc)
   * @see com.krawler.spring.crm.accountModule.crmAccountDAO#saveAccOwners(java.util.HashMap)
   */
  public KwlReturnObject saveAccOwners(HashMap<String, Object> requestParams) throws Exception {
    JSONObject myjobj = new JSONObject();
    List ll = new ArrayList();
    try {
      String accid = "";
      if (requestParams.containsKey("accid") && requestParams.get("accid") != null) {
        accid = requestParams.get("accid").toString();
      }
      String owners = "";
      if (requestParams.containsKey("owners") && requestParams.get("owners") != null) {
        owners = requestParams.get("owners").toString();
      }
      String mainowner = "";
      if (requestParams.containsKey("mainOwner") && requestParams.get("mainOwner") != null) {
        mainowner = requestParams.get("mainOwner").toString();
      }
      //            saveAccOwners(accid,mainowner,owners) ;
      //            myjobj.put("success", true);
      String hql = "delete from accountOwners c where c.account.accountid = ? ";
      executeUpdate(hql, accid);

      accountOwners accountOwnersObj = new accountOwners();
      accountOwnersObj.setAccount((CrmAccount) get(CrmAccount.class, accid));
      accountOwnersObj.setUsersByUserid((User) get(User.class, mainowner));
      accountOwnersObj.setMainOwner(true);
      save(accountOwnersObj);

      if (!StringUtil.isNullOrEmpty(owners) && !owners.equalsIgnoreCase("undefined")) {
        String[] ownerIds = owners.split(",");
        for (int i = 0; i < ownerIds.length; i++) {
          accountOwnersObj = new accountOwners();
          accountOwnersObj.setAccount((CrmAccount) get(CrmAccount.class, accid));
          accountOwnersObj.setUsersByUserid((User) get(User.class, ownerIds[i]));
          accountOwnersObj.setMainOwner(false);
          save(accountOwnersObj);
        }
      }
      ll.add(accountOwnersObj);
    } catch (Exception e) {
      throw ServiceException.FAILURE("crmAccountDAOImpl.saveAccOwners", e);
    }
    return new KwlReturnObject(true, KWLErrorMsgs.S01, "", ll, 1);
  }
  /**
   * @param Accountid
   * @param products
   * @throws ServiceException
   */
  @Override
  public void saveAccountProducts(String[] accids, String[] products) throws ServiceException {
    String query = "delete from AccountProducts where accountid.accountid in (:accids)";
    Map map = new HashMap();
    map.put("accids", accids);
    executeUpdate(query, null, map);
    if (products != null) {
      for (String accid : accids) {
        for (int i = 0; i < products.length; i++) {
          if (!StringUtil.isNullOrEmpty(products[i])) {
            AccountProducts accountProductObj = new AccountProducts();
            accountProductObj.setAccountid((CrmAccount) get(CrmAccount.class, accid));
            accountProductObj.setProductId((CrmProduct) get(CrmProduct.class, products[i]));

            save(accountProductObj);
          }
        }
      }
    }
  }
  // ******************* Account Project *************************
  @Override
  public KwlReturnObject getAccountProjectDetails(ArrayList filter_names, ArrayList filter_params)
      throws ServiceException {
    List ll = null;
    int dl = 0;
    try {
      String Hql = " Select c FROM AccountProject c ";
      int start = 0;
      int limit = 10;
      String filterQuery = StringUtil.filterQuery(filter_names, "where");
      Hql += filterQuery;

      //            ll = executeQuery( Hql, filter_params.toArray());
      //            dl = ll.size();
      ll = executeQueryPaging(Hql, filter_params.toArray(), new Integer[] {start, limit});
    } catch (Exception e) {
      logger.warn(e.getMessage(), e);
      throw ServiceException.FAILURE("crmAccountDAOImpl.getAccounts : " + e.getMessage(), e);
    }
    return new KwlReturnObject(true, KWLErrorMsgs.S01, "", ll, dl);
  }
  public List<Object> getData() {
    List<Object> data = new ArrayList<Object>();

    // Collect stats from all callbacks
    Map<String, Object> callbackResults = new HashMap<String, Object>();
    for (RealtimeStatsCallback callback : mCallbacks) {
      Map<String, Object> callbackData = callback.getStatData();
      if (callbackData != null) {
        callbackResults.putAll(callbackData);
      }
    }

    // Populate data based on callback results
    for (String name : mNames) {
      data.add(callbackResults.remove(name));
    }
    if (callbackResults.size() > 0) {
      KrawlerLog.perf.warn(
          "Detected unexpected realtime stats: " + StringUtil.join(", ", callbackResults.keySet()));
    }
    return data;
  }
  public ModelAndView deleteDocuments(HttpServletRequest request, HttpServletResponse response) {
    KwlReturnObject result;
    JSONObject jobj = new JSONObject();
    JSONObject jobj1 = new JSONObject();

    // Create transaction
    DefaultTransactionDefinition def = new DefaultTransactionDefinition();
    def.setName("JE_Tx");
    def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
    def.setIsolationLevel(TransactionDefinition.ISOLATION_READ_UNCOMMITTED);
    TransactionStatus status = txnManager.getTransaction(def);

    try {
      HashMap<String, Object> requestParams = new HashMap<String, Object>();
      requestParams.put("ids", request.getParameterValues("ids"));
      String applicant = request.getParameter("applicant");
      applicant = StringUtil.checkForNull(applicant);
      if (applicant.equalsIgnoreCase("applicant")) {
        result = hrmsExtApplDocsDAOObj.deleteDocuments(requestParams);
      } else {
        result = documentDAOObj.deleteDocuments(requestParams);
      }
      if (result.isSuccessFlag()) {
        jobj.put("success", true);
      } else {
        jobj.put("success", false);
      }
      jobj1.put("data", jobj.toString());
      jobj1.put("valid", true);
      txnManager.commit(status);
    } catch (Exception e) {
      System.out.println(e.getMessage());
      txnManager.rollback(status);
    } finally {
      return new ModelAndView("jsonView", "model", jobj1.toString());
    }
  }
  /* (non-Javadoc)
   * @see com.krawler.spring.crm.accountModule.crmAccountDAO#getAccounts(java.util.HashMap)
   */
  public KwlReturnObject getAccounts(HashMap<String, Object> requestParams)
      throws ServiceException {
    List ll = null;
    int dl = 0;
    try {
      ArrayList filter_names = new ArrayList();
      ArrayList filter_params = new ArrayList();

      if (requestParams.containsKey("filter_names")) {
        filter_names = (ArrayList) requestParams.get("filter_names");
      }
      if (requestParams.containsKey("filter_params")) {
        filter_params = (ArrayList) requestParams.get("filter_params");
      }

      String Hql = "select distinct c from CrmAccount c ";
      if (filter_names.contains("INp.productId.productid")) {
        Hql += " inner join c.crmProducts as p ";
      }
      String filterQuery = StringUtil.filterQuery(filter_names, "where");
      int ind = filterQuery.indexOf("(");
      if (ind > -1) {
        int index = Integer.valueOf(filterQuery.substring(ind + 1, ind + 2));
        filterQuery =
            filterQuery.replaceAll("(" + index + ")", filter_params.get(index).toString());
        filter_params.remove(index);
      }
      Hql += filterQuery;

      ll = executeQuery(Hql, filter_params.toArray());
      dl = ll.size();
    } catch (Exception e) {
      throw ServiceException.FAILURE("crmAccountDAOImpl.getActiveAccount : " + e.getMessage(), e);
    }
    return new KwlReturnObject(true, "002", "", ll, dl);
  }
  /* (non-Javadoc)
   * @see com.krawler.spring.crm.accountModule.crmAccountDAO#getCrmAccountCustomData(java.util.HashMap)
   */
  public KwlReturnObject getCrmAccountCustomData(HashMap<String, Object> requestParams)
      throws ServiceException {
    List ll = null;
    int dl = 0;
    try {
      ArrayList filter_names = new ArrayList();
      ArrayList filter_params = new ArrayList();

      if (requestParams.containsKey("filter_names")) {
        filter_names = new ArrayList((List<String>) requestParams.get("filter_names"));
      }
      if (requestParams.containsKey("filter_values")) {
        filter_params = new ArrayList((List<String>) requestParams.get("filter_values"));
      }

      String Hql = "from CrmAccountCustomData ";

      String filterQuery = StringUtil.filterQuery(filter_names, "where");
      int ind = filterQuery.indexOf("(");
      if (ind > -1) {
        int index = Integer.valueOf(filterQuery.substring(ind + 1, ind + 2));
        filterQuery =
            filterQuery.replaceAll("(" + index + ")", filter_params.get(index).toString());
        filter_params.remove(index);
      }
      Hql += filterQuery;

      ll = executeQueryPaging(Hql, filter_params.toArray(), new Integer[] {0, 1});
      dl = ll.size();
    } catch (Exception e) {
      e.printStackTrace();
      throw ServiceException.FAILURE(
          "crmAccountDAOImpl.getCrmAccountCustomData : " + e.getMessage(), e);
    }
    return new KwlReturnObject(true, KWLErrorMsgs.S01, "", ll, dl);
  }
 public static String getDateString(Connection conn, HttpServletRequest request, String loginid)
     throws ServiceException {
   String d = "";
   try {
     String fromdate = request.getParameter("fromdate"), todate = request.getParameter("todate");
     if (!StringUtil.isNullOrEmpty(fromdate) && StringUtil.isNullOrEmpty(todate)) {
       fromdate = Timezone.fromCompanyToSystem(conn, fromdate, loginid);
       d = " and timestamp >= TIMESTAMP('" + fromdate + "')";
     } else if (!StringUtil.isNullOrEmpty(todate) && StringUtil.isNullOrEmpty(fromdate)) {
       todate = Timezone.fromCompanyToSystem(conn, todate, loginid);
       d = " and timestamp <= TIMESTAMP('" + todate + "')";
     } else if (!StringUtil.isNullOrEmpty(todate) && !StringUtil.isNullOrEmpty(fromdate)) {
       fromdate = Timezone.fromCompanyToSystem(conn, fromdate, loginid);
       todate = Timezone.fromCompanyToSystem(conn, todate, loginid);
       d = " and timestamp BETWEEN TIMESTAMP('" + fromdate + "') and TIMESTAMP('" + todate + "')";
     } else {
       d = "";
     }
   } catch (Exception e) {
     d = "";
   } finally {
     return d;
   }
 }
 public void setFullName(String fullName) {
   if (!StringUtil.isNullOrEmpty(firstName)) this.fullName = fullName;
   else {
     this.fullName = this.firstName.concat(" ").concat(this.lastName);
   }
 }
  public KwlReturnObject getAuditData(HashMap<String, Object> requestParams)
      throws ServiceException {
    int start = 0;
    int limit = 30;
    String groupid = "";
    String searchtext = "";
    String companyid = "";
    List ll = null;
    int dl = 0;
    try {
      if (requestParams.containsKey("start")
          && requestParams.containsKey("limit")
          && !StringUtil.isNullOrEmpty(requestParams.get("start").toString())) {
        start = Integer.parseInt(requestParams.get("start").toString());
        limit = Integer.parseInt(requestParams.get("limit").toString());
      }
      if (requestParams.containsKey("groupid") && requestParams.get("groupid") != null) {
        groupid = requestParams.get("groupid").toString();
      }
      if (requestParams.containsKey("search") && requestParams.get("search") != null) {
        searchtext = requestParams.get("search").toString();
      }
      if (requestParams.containsKey("companyid") && requestParams.get("companyid") != null) {
        companyid = requestParams.get("companyid").toString();
      }

      String auditID = "";
      if (searchtext.compareTo("") != 0) {
        String query2 = searchtext + "*";
        SearchBean bean = new SearchBean();
        String indexPath = storageHandlerImplObj.GetAuditTrailIndexPath();
        String[] searchWithIndex = {"details", "ipaddr", "username"};
        Hits hitResult = bean.skynetsearchMulti(query2, searchWithIndex, indexPath);
        if (hitResult != null) {
          Iterator itrH = hitResult.iterator();
          while (itrH.hasNext()) {
            Hit hit1 = (Hit) itrH.next();
            org.apache.lucene.document.Document doc = hit1.getDocument();
            auditID += "'" + doc.get("transactionid") + "',";
          }
          if (auditID.length() > 0) {
            auditID = auditID.substring(0, auditID.length() - 1);
          }
        }
      }

      if (groupid.compareTo("") != 0 && searchtext.compareTo("") != 0) {
        /* query for both gid and search  */
        if (auditID.length() > 0) {
          String query =
              "from AuditTrail where user.company.companyID=? and ID in ("
                  + auditID
                  + ") and action.auditGroup.ID = ? order by auditTime desc";
          ll =
              HibernateUtil.executeQuery(
                  hibernateTemplate, query, new Object[] {companyid, groupid});
          dl = ll.size();
          ll =
              HibernateUtil.executeQueryPaging(
                  hibernateTemplate,
                  query,
                  new Object[] {companyid, groupid},
                  new Integer[] {start, limit});
        } else {
          dl = 0;
          ll = new ArrayList();
        }
      } else if (groupid.compareTo("") != 0 && searchtext.compareTo("") == 0) {
        /* query only for gid  */
        String query =
            "from AuditTrail where user.company.companyID=? and action.auditGroup.ID = ? order by auditTime desc";
        ll =
            HibernateUtil.executeQuery(hibernateTemplate, query, new Object[] {companyid, groupid});
        dl = ll.size();
        ll =
            HibernateUtil.executeQueryPaging(
                hibernateTemplate,
                query,
                new Object[] {companyid, groupid},
                new Integer[] {start, limit});
      } else if (groupid.compareTo("") == 0 && searchtext.compareTo("") != 0) {
        /* query only for search  */
        if (auditID.length() > 0) {
          String query =
              "from AuditTrail where user.company.companyID=? and ID in ("
                  + auditID
                  + ")  order by auditTime desc";
          ll = HibernateUtil.executeQuery(hibernateTemplate, query, new Object[] {companyid});
          dl = ll.size();
          ll =
              HibernateUtil.executeQueryPaging(
                  hibernateTemplate, query, new Object[] {companyid}, new Integer[] {start, limit});
        } else {
          dl = 0;
          ll = new ArrayList();
        }
      } else {
        /* query for all  */
        String query = "from AuditTrail where user.company.companyID=?  order by auditTime desc";
        ll = HibernateUtil.executeQuery(hibernateTemplate, query, new Object[] {companyid});
        dl = ll != null ? ll.size() : 0;
        ll =
            HibernateUtil.executeQueryPaging(
                hibernateTemplate, query, new Object[] {companyid}, new Integer[] {start, limit});
      }
    } catch (IOException ex) {
      throw ServiceException.FAILURE(ex.getMessage(), ex);
    } catch (ServiceException ex) {
      throw ServiceException.FAILURE(ex.getMessage(), ex);
    } catch (Exception ex) {
      throw ServiceException.FAILURE(ex.getMessage(), ex);
    }
    return new KwlReturnObject(true, KwlReturnMsg.S01, "", ll, dl);
  }
  public ModelAndView addDocuments(HttpServletRequest request, HttpServletResponse response)
      throws ServletException {
    JSONObject jobj = new JSONObject();
    JSONObject myjobj = new JSONObject();
    List fileItems = null;
    KwlReturnObject kmsg = null;
    String auditAction = "";
    boolean applicant = false;
    String id = java.util.UUID.randomUUID().toString();
    PrintWriter out = null;
    // Create transaction
    DefaultTransactionDefinition def = new DefaultTransactionDefinition();
    def.setName("JE_Tx");
    def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
    def.setIsolationLevel(TransactionDefinition.ISOLATION_READ_UNCOMMITTED);
    TransactionStatus status = txnManager.getTransaction(def);
    try {
      response.setContentType("text/html;charset=UTF-8");
      out = response.getWriter();
      String userid = sessionHandlerImplObj.getUserid(request);
      String map = request.getParameter("mapid");
      HashMap<String, String> arrParam = new HashMap<String, String>();
      boolean fileUpload = false;
      String docdesc;
      ArrayList<FileItem> fi = new ArrayList<FileItem>();
      if (request.getParameter("fileAdd") != null) {
        DiskFileUpload fu = new DiskFileUpload();
        fileItems = fu.parseRequest(request);
        documentDAOObj.parseRequest(fileItems, arrParam, fi, fileUpload);
        arrParam.put("IsIE", request.getParameter("IsIE"));
        if (arrParam.get("applicantid").equalsIgnoreCase("applicant")) {
          applicant = true;
          userid = arrParam.get("refid");
        }
        if (StringUtil.isNullOrEmpty((String) arrParam.get("docdesc")) == false) {
          docdesc = (String) arrParam.get("docdesc");
        }
      }
      for (int cnt = 0; cnt < fi.size(); cnt++) {
        String docID;
        if (applicant) {
          kmsg =
              hrmsExtApplDocsDAOObj.uploadFile(
                  fi.get(cnt),
                  userid,
                  arrParam,
                  profileHandlerDAOObj.getUserFullName(sessionHandlerImplObj.getUserid(request)));
          HrmsDocs doc = (HrmsDocs) kmsg.getEntityList().get(0);
          docID = doc.getDocid();
        } else {
          kmsg = documentDAOObj.uploadFile(fi.get(cnt), userid, arrParam);
          Docs doc = (Docs) kmsg.getEntityList().get(0);
          docID = doc.getDocid();
        }

        String companyID = sessionHandlerImplObj.getCompanyid(request);
        String userID = sessionHandlerImplObj.getUserid(request);
        String refid = arrParam.get("refid");
        jobj.put("userid", userID);
        jobj.put("docid", docID);
        jobj.put("companyid", companyID);
        jobj.put("id", id);
        jobj.put("map", map);
        jobj.put("refid", refid);
        if (arrParam.get("applicantid").equalsIgnoreCase("applicant")) {
          hrmsExtApplDocsDAOObj.saveDocumentMapping(jobj);
        } else {
          documentDAOObj.saveDocumentMapping(jobj);
        }
      }
      myjobj.put("ID", id);
      txnManager.commit(status);
    } catch (Exception e) {
      System.out.println(e.getMessage());
      txnManager.rollback(status);
    } finally {
      out.close();
    }
    return new ModelAndView("jsonView", "model", myjobj.toString());
  }
  protected void processRequest(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException, SessionExpiredException {
    JSONObject j = null;
    Connection conn = null;

    clearAll();
    String projectId = request.getParameter("projectid");
    ProjectName = request.getParameter("projname");
    ReportName = request.getParameter("reportname");
    String loginid = AuthHandler.getUserid(request);
    String userName = AuthHandler.getUserName(request);
    String companyid = AuthHandler.getCompanyid(request);
    String ipAddress = AuthHandler.getIPAddress(request);
    String exportType = request.getParameter("exporttype");
    String filename = filename = ProjectName + "_" + ReportName + "." + exportType;
    ByteArrayOutputStream baos = null;
    try {
      conn = DbPool.getConnection();
      String cmpcurr = ProfileHandler.getCmpCurrFromProj(conn, projectId);
      try {
        char a1 = (char) Integer.parseInt(cmpcurr, 16);
        currSymbol = Character.toString(a1);
      } catch (Exception e) {
        currSymbol = cmpcurr;
      }
      String baseid = request.getParameter("baselineid");
      String jbase = projdb.getBaselineDetails(conn, baseid);
      JSONObject temp = new JSONObject(jbase);
      baseName = temp.getJSONArray("data").getJSONObject(0).getString("baselinename");
      String reportJson = projdb.getProjectSummaryData(conn, projectId, baseid, loginid);
      j = projdb.getAllProjectSummaryData(reportJson);
      JSONArray store = j.getJSONArray("data");
      JSONArray rstore = j.getJSONArray("resources");
      if (StringUtil.equal(exportType, "pdf")) {
        baos = getPdfData(store, rstore, request);
      } else if (StringUtil.equal(exportType, "csv")) {
        JSONObject jtemp = new JSONObject(reportJson);
        rstore = jtemp.getJSONArray("resources");
        baos = getCsvData(rstore, store, request);
      }
      String params =
          AuthHandler.getAuthor(conn, loginid)
              + " ("
              + userName
              + "), "
              + ReportName
              + ", "
              + exportType
              + " , "
              + ProjectName;
      AuditTrail.insertLog(
          conn, "1111", loginid, projectId, projectId, companyid, params, ipAddress, 0);
    } catch (ServiceException ex) {
      filename = "Problem_in_exporting_file." + exportType;
      DbPool.quietRollback(conn);
    } catch (JSONException e) {
      filename = "Problem_in_exporting_file." + exportType;
      DbPool.quietRollback(conn);
    } finally {
      DbPool.quietClose(conn);
      try {
        if (baos != null) {
          baos.close();
        }
      } catch (IOException e) {
      }
      writeDataToFile(filename, baos, response);
    }
  }
 public static String getActionLog(Connection conn, HttpServletRequest request)
     throws ServiceException {
   ResultSet rs = null;
   String returnStr = "";
   PreparedStatement pstmt = null;
   String searchString = request.getParameter("ss");
   String limit = request.getParameter("limit");
   String offset = request.getParameter("start");
   JSONObject resobj = new JSONObject();
   JSONObject tempobj = new JSONObject();
   JSONArray jarr = new JSONArray();
   String likeClause = "";
   try {
     String companyid = AuthHandler.getCompanyid(request);
     String loginid = AuthHandler.getUserid(request);
     String[] searchStrObj = new String[] {"params", "actiontext"};
     String myLikeString = StringUtil.getMySearchString(searchString, "and", searchStrObj);
     String flag = "";
     int count1 = 0;
     String type = request.getParameter("type");
     String dateSting = getDateString(conn, request, loginid);
     if (StringUtil.isNullOrEmpty(type)) {
       flag = "no";
       returnStr = getAllLog(conn, request, companyid, limit, offset, searchString, dateSting);
     } else {
       switch (Integer.parseInt(type)) {
         case 0:
           flag = "projname";
           returnStr =
               getLog(conn, request, companyid, limit, offset, searchString, dateSting, flag);
           flag = "no";
           break;
         case 1:
           String admintype = request.getParameter("admintype");
           if (admintype.equals("0")) {
             likeClause = "and al.actionid like '31%' ";
           } else if (admintype.equals("1")) {
             likeClause = "and al.actionid like '32%' ";
           } else {
             likeClause = "and al.actionid like '33%' or al.actionid like '40%' ";
           }
           flag = "admin";
           break;
         case 2:
           flag = "doc";
           likeClause = "and al.actionid like '21%' ";
           break;
         case 3:
           flag = "all";
           likeClause = "and projectid != '' ";
           break;
         case 4:
           flag = "admin";
           likeClause =
               "and (al.actionid like '31%' or al.actionid like '32?' or al.actionid like '33?' or al.actionid like '40%')";
           break;
         case 5:
           flag = "all";
           likeClause = "and (al.actionid like '41%')";
           break;
       }
     }
     if (!flag.equals("no")) {
       count1 =
           getCountQuery(
               conn,
               pstmt,
               companyid,
               likeClause,
               myLikeString,
               searchStrObj,
               searchString,
               dateSting);
       String query =
           "select logid, al.actionid, actionby, params, timestamp, projectid from actionlog al inner join actions a on al.actionid = a.actionid where companyid = ? "
               + likeClause
               + myLikeString
               + dateSting
               + " order by timestamp DESC limit ? offset ?";
       pstmt = conn.prepareStatement(query);
       pstmt.setString(1, companyid);
       int cnt = StringUtil.insertParamSearchString(2, pstmt, searchString, searchStrObj.length);
       pstmt.setInt(cnt++, Integer.parseInt(limit));
       pstmt.setInt(cnt++, Integer.parseInt(offset));
       rs = pstmt.executeQuery();
       while (rs.next()) {
         tempobj = getJsonForAction(conn, pstmt, rs, request, flag);
         jarr.put(tempobj);
       }
       resobj.put("data", jarr);
       resobj.append("count", count1);
       returnStr = resobj.toString();
     }
   } catch (ServiceException ex) {
     Logger.getLogger(AuditTrail.class.getName()).log(Level.SEVERE, null, ex);
   } catch (Exception ex) {
     throw ServiceException.FAILURE("AuditTrail.getActionLog :" + ex.getMessage(), ex);
   } finally {
     return returnStr;
   }
 }
  /* (non-Javadoc)
   * @see com.krawler.spring.crm.accountModule.crmAccountDAO#getAllAccounts(java.util.HashMap, java.util.ArrayList, java.util.ArrayList)
   */
  public KwlReturnObject getAllAccounts(
      HashMap<String, Object> requestParams, ArrayList filter_names, ArrayList filter_params)
      throws ServiceException {
    List ll = null;
    int dl = 0;
    try {
      String Hql = "select distinct c from accountOwners ao inner join ao.account c ";
      //            String Hql = "select c from CrmAccount c ";
      String filterQuery = StringUtil.filterQuery(filter_names, "where");
      Hql += filterQuery;
      int ind = Hql.indexOf("(");
      if (ind > -1) {
        int index = Integer.valueOf(Hql.substring(ind + 1, ind + 2));
        Hql = Hql.replaceAll("(" + index + ")", filter_params.get(index).toString());
        filter_params.remove(index);
      }

      if (requestParams.containsKey("ss") && requestParams.get("ss") != null) {
        String ss = StringEscapeUtils.escapeJavaScript(requestParams.get("ss").toString());
        if (!StringUtil.isNullOrEmpty(ss)) {
          String[] searchcol = new String[] {"c.accountname"};
          StringUtil.insertParamSearchString(filter_params, ss, 1);
          String searchQuery = StringUtil.getSearchString(ss, "and", searchcol);
          Hql += searchQuery;
        }
      }

      String selectInQuery = Hql;
      boolean pagingFlag = false;
      if (requestParams.containsKey("pagingFlag") && requestParams.get("pagingFlag") != null) {
        pagingFlag = Boolean.parseBoolean(requestParams.get("pagingFlag").toString());
      }
      boolean countFlag = true;
      if (requestParams.containsKey("countFlag") && requestParams.get("countFlag") != null) {
        countFlag = Boolean.parseBoolean(requestParams.get("countFlag").toString());
      }

      ArrayList order_by = null;
      ArrayList order_type = null;
      if (requestParams.containsKey("order_by"))
        order_by = (ArrayList) requestParams.get("order_by");
      if (requestParams.containsKey("order_type"))
        order_type = (ArrayList) requestParams.get("order_type");
      String orderQuery = StringUtil.orderQuery(order_by, order_type);
      if (StringUtil.isNullOrEmpty(orderQuery)) {
        orderQuery = " order by c.accountname ";
      }
      selectInQuery += orderQuery;

      if (countFlag) {
        ll = executeQuery(selectInQuery, filter_params.toArray());
        dl = ll.size();
      }
      if (pagingFlag) {
        int start = 0;
        int limit = 25;
        if (requestParams.containsKey("start") && requestParams.containsKey("limit")) {
          start = Integer.parseInt(requestParams.get("start").toString());
          limit = Integer.parseInt(requestParams.get("limit").toString());
        }
        ll =
            executeQueryPaging(
                selectInQuery, filter_params.toArray(), new Integer[] {start, limit});
        if (!countFlag) {
          dl = ll.size();
        }
      }
    } catch (Exception e) {
      throw ServiceException.FAILURE("crmAccountDAOImpl.getAllAccounts : " + e.getMessage(), e);
    }
    return new KwlReturnObject(true, KWLErrorMsgs.S01, "", ll, dl);
  }
  /* (non-Javadoc)
   * @see com.krawler.spring.crm.accountModule.crmAccountDAO#getAccounts(java.util.HashMap, java.lang.StringBuffer)
   */
  public KwlReturnObject getAccounts(HashMap<String, Object> requestParams, StringBuffer usersList)
      throws ServiceException {
    List ll = null;
    Long dl = 0l;
    try {
      requestParams.put(Constants.moduleid, 1);
      boolean archive = false;
      if (requestParams.containsKey("isarchive") && requestParams.get("isarchive") != null) {
        archive = Boolean.parseBoolean(requestParams.get("isarchive").toString());
      }
      String companyid = requestParams.get("companyid").toString();
      String appendCase = "and";
      ArrayList filter_params = new ArrayList();

      String selQuery = "select distinct c ";
      String selCountQuery = "select count(distinct c.accountid) ";
      String Hql =
          " from accountOwners ao inner join ao.account c "
              + crmManagerCommon.getJoinQuery(requestParams);
      String filterQuery = " where  c.deleteflag=0  and c.isarchive= ? and c.company.companyID= ? ";

      filter_params.add(archive);
      filter_params.add(companyid);

      String Searchjson = "";
      if (requestParams.containsKey("searchJson") && requestParams.get("searchJson") != null) {
        Searchjson = requestParams.get("searchJson").toString();
        if (Searchjson.contains("p.productId.productid")) {
          Hql += " inner join c.crmProducts as p ";
        }
        if (!StringUtil.isNullOrEmpty(Searchjson)) {
          requestParams.put(Constants.Searchjson, Searchjson);
          requestParams.put(Constants.appendCase, appendCase);
          String mySearchFilterString =
              String.valueOf(
                  StringUtil.getMyAdvanceSearchString(requestParams).get(Constants.myResult));
          filterQuery += mySearchFilterString;
          StringUtil.insertParamAdvanceSearchString(filter_params, Searchjson);
        }
      }

      if (requestParams.containsKey("config") && requestParams.get("config") != null) {
        filterQuery += " and c.validflag=1 ";
      }
      if (requestParams.containsKey("ss") && requestParams.get("ss") != null) {
        String ss = requestParams.get("ss").toString();
        if (!StringUtil.isNullOrEmpty(ss)) {
          String[] searchcol = new String[] {"c.accountname", "c.website"};
          StringUtil.insertParamSearchString(filter_params, ss, 2);
          String searchQuery = StringUtil.getSearchString(ss, "and", searchcol);
          filterQuery += searchQuery;
        }
      }

      int start = 0;
      int limit = 25;
      boolean ispaging =
          requestParams.containsKey("start")
              && requestParams.containsKey("limit")
              && !StringUtil.isNullOrEmpty(requestParams.get("start").toString())
              && !StringUtil.isNullOrEmpty(requestParams.get("start").toString());
      if (ispaging) {
        if (requestParams.containsKey("iPhoneCRM") && requestParams.get("iPhoneCRM") != null) {
          limit = Integer.parseInt(requestParams.get("limit").toString());
          start = Integer.parseInt(requestParams.get("start").toString()) * limit;
        } else {
          start = Integer.parseInt(requestParams.get("start").toString());
          limit = Integer.parseInt(requestParams.get("limit").toString());
        }
      }

      boolean heirarchyPerm = false;
      if (requestParams.containsKey("heirarchyPerm")
          && requestParams.get("heirarchyPerm") != null) {
        heirarchyPerm = Boolean.parseBoolean(requestParams.get("heirarchyPerm").toString());
      }
      if (!heirarchyPerm) {
        filterQuery += " and ao.usersByUserid.userID in (" + usersList + ") ";
      }

      String orderQuery = " order by c.createdOn desc";
      String dbname = null;
      String dir = null;
      if (requestParams.containsKey("field") && requestParams.get("xfield") != null) {
        dbname = crmManagerCommon.getFieldDbName(requestParams);
        if (dbname != null) {
          dir = requestParams.get("direction").toString();
          orderQuery = " order by " + dbname + " " + dir + " ";
        }
      }
      String countQuery = selCountQuery + Hql + filterQuery;
      String query = selQuery + Hql + filterQuery + orderQuery;
      String export = "";
      if (requestParams.containsKey("export") && requestParams.get("export") != null) {
        countQuery = query;
        export = requestParams.get("export").toString();
      }

      ll = executeQuery(countQuery, filter_params.toArray());

      if (ll != null && !ll.isEmpty() && StringUtil.isNullOrEmpty(export)) {
        dl = (Long) ll.get(0);
      }
      String association = null;
      String property = null;
      if (dbname != null && dbname.split("\\.").length > 2) {
        association = dbname.substring(0, dbname.lastIndexOf("."));
        property = dbname.substring(dbname.lastIndexOf(".") + 1, dbname.length());
      }
      if (StringUtil.isNullOrEmpty(export)) {
        ll = executeQueryPaging(query, filter_params.toArray(), new Integer[] {start, limit});
      }
    } catch (Exception e) {
      throw ServiceException.FAILURE("crmAccountDAOImpl.getAccounts : " + e.getMessage(), e);
    }
    return new KwlReturnObject(true, KWLErrorMsgs.S01, "", ll, dl.intValue());
  }