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;
   }
 }
  @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 void getCompanyDetails(HttpServletRequest request) {
    String res1 = null;
    String res2 = null;
    String res3 = null;
    PreparedStatement pstmt = null;
    ResultSet rs = null;
    com.krawler.database.DbPool.Connection conn = null;
    String GET_COMPNY_IMGPATH =
        "SELECT companyname,subdomain,image FROM company WHERE companyid = ?";
    try {
      conn = DbPool.getConnection();
      pstmt = conn.prepareStatement(GET_COMPNY_IMGPATH);
      pstmt.setString(1, AuthHandler.getCompanyid(request));
      rs = pstmt.executeQuery();
      if (rs.next()) {

        res1 = rs.getString("image").trim();
        String tmp[] = res1.split("/");
        res1 = tmp[tmp.length - 1].toString().trim();
        res3 = rs.getString("subdomain");
        res2 = rs.getString("companyname");
      } else {
        res1 = "";
        res2 = "";
        res3 = "";
      }
      //                conn.close();
    } catch (SessionExpiredException ex) {
      KrawlerLog.op.warn("Problem While Creating PDF :" + ex.toString());
      DbPool.quietRollback(conn);
      res1 = "";
      res2 = "";
      res3 = "";
    } catch (SQLException ex) {
      KrawlerLog.op.warn("Problem While Creating PDF :" + ex.toString());
      DbPool.quietRollback(conn);
      res1 = "";
      res2 = "";
      res3 = "";
    } catch (ServiceException ex) {
      KrawlerLog.op.warn("Problem While Creating PDF :" + ex.toString());
      DbPool.quietRollback(conn);
      res1 = "";
      res2 = "";
      res3 = "";
    } finally {
      imgPath = res1;
      companyName = res2;
      companySubDomain = res3;
      DbPool.quietClose(conn);
    }
  }
 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;
   }
 }
  public KwlReturnObject documentSearch(HashMap<String, Object> requestParams)
      throws ServiceException {
    List ll = null;
    int dl = 0;
    String MyQuery1 = "";
    String MyQuery = "";
    String querytxt = "";
    String companyid = "";
    try {
      if (requestParams.containsKey("companyid") && requestParams.get("companyid") != null) {
        companyid = requestParams.get("companyid").toString();
      }
      if (requestParams.containsKey("keyword") && requestParams.get("keyword") != null) {
        querytxt = requestParams.get("keyword").toString();
      }

      Pattern p = Pattern.compile("^(?i)tag:[[\\s]*([\\w\\s]+[(/|\\{1})]?)*[\\s]*[\\w]+[\\s]*]*$");
      Matcher m = p.matcher(querytxt);
      boolean b = m.matches();
      ArrayList filter_params = new ArrayList();

      if (!b) {
        MyQuery = querytxt;
        MyQuery1 = querytxt;
        if (querytxt.length() > 2) {
          MyQuery = querytxt + "%";
          MyQuery1 = "% " + MyQuery;
        }
        String Hql =
            "select c from com.krawler.common.admin.Docs c  where c.company.companyID=? and c.deleteflag=0";
        Hql =
            Hql
                + "and ( c.docname like ? or c.docsize like ? or c.doctype like ? or c.userid.firstName like ? or c.userid.lastName like ? ) ";
        filter_params.add(companyid);
        filter_params.add(MyQuery);
        filter_params.add(MyQuery);
        filter_params.add(MyQuery);
        filter_params.add(MyQuery);
        filter_params.add(MyQuery);

        ll = HibernateUtil.executeQuery(hibernateTemplate, Hql, filter_params.toArray());
        dl = ll.size();
      }
    } catch (ServiceException e) {
      throw ServiceException.FAILURE("documentDAOImpl.documentSearch", e);
    } catch (Exception e) {
      throw ServiceException.FAILURE("documentDAOImpl.documentSearch", e);
    }
    return new KwlReturnObject(true, KwlReturnMsg.S01, "", ll, dl);
  }
 @Override
 public HashMap<String, CrmAccountCustomData> getAccountCustomDataMap(
     List<String> list, String companyid) throws ServiceException {
   List<CrmAccountCustomData> ll = null;
   HashMap<String, CrmAccountCustomData> accountCustomDataMap =
       new HashMap<String, CrmAccountCustomData>();
   try {
     String filterQuery = "";
     List<List> paramll = new ArrayList();
     List<String> paramnames = new ArrayList();
     if (!list.isEmpty()) {
       filterQuery = " and c.accountid in (:recordlist) ";
       paramll.add(list);
       paramnames.add("recordlist");
     }
     String Hql =
         "select c from CrmAccountCustomData c where c.company.companyID = '"
             + companyid
             + "' "
             + filterQuery;
     ll = executeCollectionQuery(Hql, paramnames, paramll);
     for (CrmAccountCustomData accountCustomObj : ll) {
       accountCustomDataMap.put(accountCustomObj.getAccountid(), accountCustomObj);
     }
   } catch (Exception ex) {
     throw ServiceException.FAILURE("crmAccountDAOImpl.getAccountCustomDataMap", ex);
   }
   return accountCustomDataMap;
 }
  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);
    }
  }
 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 getRecentActivityDetails(HashMap<String, Object> requestParams)
      throws ServiceException {
    List ll = null;
    int dl = 0;
    String recid = "";
    String companyid = "";
    try {
      if (requestParams.containsKey("recid") && requestParams.get("recid") != null) {
        recid = requestParams.get("recid").toString();
      }
      if (requestParams.containsKey("companyid") && requestParams.get("companyid") != null) {
        companyid = requestParams.get("companyid").toString();
      }
      String query =
          "from AuditTrail where user.company.companyID=? and recid=? order by auditTime desc";
      ll =
          HibernateUtil.executeQueryPaging(
              hibernateTemplate, query, new Object[] {companyid, recid}, new Integer[] {0, 15});
      dl = ll.size();

    } catch (Exception e) {
      throw ServiceException.FAILURE(
          "detailPanelDAOImpl.getRecentActivityDetails : " + e.getMessage(), e);
    }
    return new KwlReturnObject(true, KwlReturnMsg.S01, "", ll, dl);
  }
 private ByteArrayOutputStream getPdfData(
     JSONArray data, JSONArray res, HttpServletRequest request) throws ServiceException {
   ByteArrayOutputStream baos = new ByteArrayOutputStream();
   try {
     String[] colHeader = getColHeader();
     String[] colIndex = getColIndexes();
     String[] val = getColValues(colHeader, data);
     String[] resources = getResourcesColHeader(res, data);
     String[] mainHeader = {"Dates", "Duration", "Work", "Cost", "Tasks", "Resources"};
     Document document = null;
     if (landscape) {
       Rectangle recPage = new Rectangle(PageSize.A4.rotate());
       recPage.setBackgroundColor(new java.awt.Color(255, 255, 255));
       document = new Document(recPage, 15, 15, 30, 30);
     } else {
       Rectangle recPage = new Rectangle(PageSize.A4);
       recPage.setBackgroundColor(new java.awt.Color(255, 255, 255));
       document = new Document(recPage, 15, 15, 30, 30);
     }
     PdfWriter writer = PdfWriter.getInstance(document, baos);
     writer.setPageEvent(new EndPage());
     document.open();
     if (showLogo) {
       getCompanyDetails(request);
       addComponyLogo(document, request);
     }
     addTitleSubtitle(document);
     addTable(data, resources, colIndex, colHeader, mainHeader, val, document);
     document.close();
     writer.close();
     baos.close();
   } catch (ConfigurationException ex) {
     throw ServiceException.FAILURE("ExportProjectReport.getPdfData", ex);
   } catch (DocumentException ex) {
     throw ServiceException.FAILURE("ExportProjectReport.getPdfData", ex);
   } catch (JSONException e) {
     throw ServiceException.FAILURE("ExportProjectReport.getPdfData", e);
   } catch (IOException e) {
     throw ServiceException.FAILURE("ExportProjectReport.getPdfData", e);
   } catch (Exception e) {
     throw ServiceException.FAILURE("ExportProjectReport.getPdfData", e);
   }
   return baos;
 }
 public KwlReturnObject getDocumentsForTable(HashMap<String, Object> queryParams, boolean allflag)
     throws ServiceException {
   KwlReturnObject kmsg = null;
   try {
     kmsg = HibernateUtil.getTableData(hibernateTemplate, queryParams, allflag);
   } catch (Exception e) {
     throw ServiceException.FAILURE("documentDAOImpl.getDocumentsForTable : " + e.getMessage(), e);
   }
   return kmsg;
 }
 public void insertAuditLog(
     String actionid, String details, HttpServletRequest request, String recid)
     throws ServiceException {
   try {
     AuditAction action = (AuditAction) hibernateTemplate.load(AuditAction.class, actionid);
     insertAuditLog(action, details, request, recid, "0");
   } catch (Exception e) {
     throw ServiceException.FAILURE(e.getMessage(), e);
   }
 }
 public KwlReturnObject getCompanyTypes() throws ServiceException {
   List ll = new ArrayList();
   try {
     String query = "from CompanyType";
     ll = HibernateUtil.executeQuery(hibernateTemplate, query);
   } catch (Exception e) {
     throw ServiceException.FAILURE("AccCommonTablesDAOImpl.getCompanyTypes", e);
   }
   return new KwlReturnObject(true, KwlReturnMsg.S01, "", ll, ll.size());
 }
 public void insertAuditLog(
     String actionid, String details, String ipAddress, String userid, String recid)
     throws ServiceException {
   try {
     AuditAction action = (AuditAction) hibernateTemplate.load(AuditAction.class, actionid);
     User user = (User) hibernateTemplate.load(User.class, userid);
     insertAuditLog(action, details, ipAddress, user, recid, "0");
   } catch (Exception e) {
     throw ServiceException.FAILURE(e.getMessage(), e);
   }
 }
 public KwlReturnObject getAuditGroupData() throws ServiceException {
   List ll = null;
   int dl = 0;
   try {
     String query =
         "from AuditGroup where groupName not in ('User', 'Company', 'Log in', 'Log out')";
     ll = HibernateUtil.executeQuery(hibernateTemplate, query);
     dl = ll.size();
   } catch (Exception e) {
     throw ServiceException.FAILURE(e.getMessage(), e);
   }
   return new KwlReturnObject(true, KwlReturnMsg.S01, "", ll, dl);
 }
 public void uploadFile(FileItem fi, String destinationDirectory, String fileName)
     throws ServiceException {
   try {
     File destDir = new File(destinationDirectory);
     if (!destDir.exists()) {
       destDir.mkdirs();
     }
     File uploadFile = new File(destinationDirectory + "/" + fileName);
     fi.write(uploadFile);
   } catch (Exception ex) {
     throw ServiceException.FAILURE("documentDAOImpl.uploadFile", ex);
   }
 }
 public KwlReturnObject addTag(HashMap<String, Object> requestParams) throws ServiceException {
   String tag = requestParams.containsKey("tag") ? requestParams.get("tag").toString() : "";
   List ll = new ArrayList();
   int dl = 0;
   try {
     String tags[] = tag.split(",,");
     Docs c = (Docs) hibernateTemplate.get(Docs.class, tags[0]);
     c.setTags(tags[1]);
     ll.add(c);
   } catch (Exception ex) {
     throw ServiceException.FAILURE("documentDAOImpl.addTag", ex);
   }
   return new KwlReturnObject(true, KwlReturnMsg.S01, "", ll, dl);
 }
  /* (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);
  }
  public KwlReturnObject downloadDocument(String id) throws ServiceException {

    List ll = null;
    int dl = 0;
    try {
      ll =
          HibernateUtil.executeQuery(
              hibernateTemplate,
              "FROM " + "com.krawler.common.admin.Docmap AS crmdocs1 where crmdocs1.docid.docid =?",
              new Object[] {id});
      dl = ll.size();
    } catch (Exception e) {
      throw ServiceException.FAILURE(e.getMessage(), e);
    }
    return new KwlReturnObject(true, KwlReturnMsg.S01, "", ll, dl);
  }
 public KwlReturnObject getDocuments(HashMap<String, Object> requestParams)
     throws ServiceException {
   List ll = null;
   int dl = 0;
   String recid = "";
   try {
     if (requestParams.containsKey("recid") && requestParams.get("recid") != null) {
       recid = requestParams.get("recid").toString();
     }
     String Hql = "select dm.docid FROM com.krawler.common.admin.Docmap dm where dm.recid=? ";
     ll = HibernateUtil.executeQuery(hibernateTemplate, Hql, new Object[] {recid});
     dl = ll.size();
   } catch (Exception e) {
     throw ServiceException.FAILURE("documentDAOImpl.getDocuments : " + e.getMessage(), e);
   }
   return new KwlReturnObject(true, KwlReturnMsg.S01, "", 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 JSONArray getProductTypesJson(HttpServletRequest request, List list)
      throws ServiceException, SessionExpiredException {
    JSONArray jArr = new JSONArray();
    try {
      Iterator itr = list.iterator();
      while (itr.hasNext()) {
        Producttype ptype = (Producttype) itr.next();
        JSONObject obj = new JSONObject();
        obj.put("id", ptype.getID());
        obj.put("name", ptype.getName());
        jArr.put(obj);
      }

    } catch (JSONException ex) {
      throw ServiceException.FAILURE("getProductTypesJson : " + ex.getMessage(), ex);
    }
    return jArr;
  }
  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#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;
 }
  /* (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);
  }
  public void insertAuditLog(
      AuditAction action, String details, String ipAddress, User user, String recid, String extraid)
      throws ServiceException {
    try {
      String aid = UUID.randomUUID().toString();
      AuditTrail auditTrail = new AuditTrail();
      auditTrail.setID(aid);
      auditTrail.setAction(action);
      auditTrail.setAuditTime(new Date());
      auditTrail.setDetails(details);
      auditTrail.setIPAddress(ipAddress);
      auditTrail.setRecid(recid);
      auditTrail.setUser(user);
      auditTrail.setExtraid(extraid);
      hibernateTemplate.save(auditTrail);

      ArrayList<Object> indexFieldDetails = new ArrayList<Object>();
      ArrayList<String> indexFieldName = new ArrayList<String>();
      indexFieldDetails.add(details);
      indexFieldName.add("details");
      indexFieldDetails.add(aid);
      indexFieldName.add("transactionid");
      indexFieldDetails.add(action.getID());
      indexFieldName.add("actionid");
      indexFieldDetails.add(ipAddress);
      indexFieldName.add("ipaddr");
      String userName =
          user.getUserLogin().getUserName() + " " + user.getFirstName() + " " + user.getLastName();
      indexFieldDetails.add(userName);
      indexFieldName.add("username");
      indexFieldDetails.add(auditTrail.getAuditTime());
      indexFieldName.add("timestamp");
      String indexPath = storageHandlerImplObj.GetAuditTrailIndexPath();
      com.krawler.esp.indexer.KrawlerIndexCreator kwlIndex =
          new com.krawler.esp.indexer.KrawlerIndexCreator();
      kwlIndex.setIndexPath(indexPath);
      com.krawler.esp.indexer.CreateIndex cIndex = new com.krawler.esp.indexer.CreateIndex();
      cIndex.indexAlert(kwlIndex, indexFieldDetails, indexFieldName);

    } 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);
  }
  public KwlReturnObject uploadFile(FileItem fi, String userid) throws ServiceException {
    Docs docObj = new Docs();
    List ll = new ArrayList();
    int dl = 0;
    try {
      String fileName = new String(fi.getName().getBytes(), "UTF8");
      String Ext = "";
      String a = "";

      if (fileName.contains(".")) {
        Ext = fileName.substring(fileName.indexOf(".") + 1, fileName.length());
        a = Ext.toUpperCase();
      }

      User userObj = (User) hibernateTemplate.get(User.class, userid);
      docObj.setDocname(fileName);
      docObj.setUserid(userObj);
      docObj.setStorename("");
      docObj.setDoctype(a + " " + "File");
      docObj.setUploadedon(new Date());
      docObj.setStorageindex(1);
      docObj.setDocsize(fi.getSize() + "");

      hibernateTemplate.save(docObj);

      String fileid = docObj.getDocid();
      if (Ext.length() > 0) {
        fileid = fileid + Ext;
      }
      docObj.setStorename(fileid);

      hibernateTemplate.update(docObj);

      ll.add(docObj);

      //            String temp = "/home/trainee";
      String temp = storageHandlerImplObj.GetDocStorePath();
      uploadFile(fi, temp, fileid);
    } catch (Exception e) {
      throw ServiceException.FAILURE(e.getMessage(), e);
    }
    return new KwlReturnObject(true, KwlReturnMsg.S01, "", ll, dl);
  }
  // ******************* 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);
  }
  /* (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);
  }