Commit 9650b6f5 authored by ManishKumar C's avatar ManishKumar C

Upload New File

parent 8a02b362
package ibase.hibernate.dao;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.core.Context;
import org.apache.commons.io.FileUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import ibase.ejb.CommonDBAccessEJB;
//import ibase.dashboard.common.hibernate.dao.E12GenericUtility;
import ibase.hibernate.bean.InviteUser;
import ibase.system.config.ConnDriver;
import ibase.utility.BaseLogger;
import ibase.utility.CommonConstants;
import ibase.utility.E12GenericUtility;
import ibase.utility.EMail;
import ibase.utility.UserInfoBean;
import ibase.webitm.ejb.ITMDBAccessEJB;
import ibase.webitm.ejb.UserActivationEJB;
import ibase.webitm.utility.ITMException;
import ibase.webitm.utility.TransIDGenerator;
import org.json.XML;//Added by Nikhil on 28-05-21
//Created by chitranga Tandel on 14 AUG 2018
public class UserInvitationDAO
{
private String transDB = "DEFAULT";
private UserInfoBean userInfoBean= null;
private String hostName;
public UserInvitationDAO(UserInfoBean userInfo) {
userInfoBean = userInfo;
transDB = userInfoBean.getTransDB();
BaseLogger.log("1",userInfo,null,"transDB in userInvitation dao == >" +transDB);
}
public UserInvitationDAO() {
}
public ArrayList<InviteUser> getInvitedUsers(String chgUser) throws Exception
{
ArrayList<InviteUser> invitedUsers = new ArrayList<>();
BaseLogger.log("2",null,null,"InviteUser dao in getInvitedUsers method == >220219 ==>" + transDB);
Connection autConn = null;
Connection userConn = null;
java.sql.PreparedStatement pstmt = null;
JSONArray invitedUserJsonArr = null;
ResultSet rs = null;
try
{
JSONObject invitedUsrJson = null;
ConnDriver connDriver = new ConnDriver();
//Change by Priyanka B on 25/Jan/19 Start
autConn = connDriver.getConnectDB( "Driver");
userConn = connDriver.getConnectDB( transDB );
String prefix = "";
BaseLogger.log("3",null,null,"conn in getInvitedUsers method == >" );
String profileIdSql= "SELECT PROFILE_ID,DESCR FROM PROFILE";
pstmt = userConn.prepareStatement(profileIdSql);
rs = pstmt.executeQuery();
StringBuffer profileIdString= new StringBuffer ();
HashMap<String, String> profileMap= new HashMap<String, String> ();
while(rs.next())
{
profileIdString.append(prefix);
prefix = ",";
System.out.println("Inside profile id "+rs);
String profileId=rs.getString("PROFILE_ID");
String descr=rs.getString("DESCR");
profileIdString =profileIdString.append("'"+profileId+"'");
profileMap.put(profileId, descr);
}
System.out.println("profileIdString in getInvitedUsers "+profileIdString);
System.out.println("profileMap in getInvitedUsers "+profileMap);
pstmt.close();
rs.close();
userConn.close();
pstmt = null;
rs=null;
//String userSql = "SELECT (SELECT USER_LIC_TYPE FROM USERS WHERE CODE = U.CODE) as USER_LICTYPE ,U.CODE,U.EMAIL_ID,U.MOBILE_NO,P.PROFILE_ID,P.DESCR,R.USER_NAME,R.LAST_NAME,U.REGST_STAT,U.SITE_CODE__DEF,U.USR_LEV,U.UUID,U.ACC_PARM1 ,U.ENTITY_CODE, U.USER_TYPE FROM USER_INVITE U, PROFILE P,USER_REGISTRATION R WHERE R.EMAIL_ID = U.EMAIL_ID AND TRIM(P.PROFILE_ID) = TRIM(U.PROFILE_ID) AND U.CHG_USER = ?";
//Change By Nikhil on 28-05-21 to get a distinct value
StringBuffer userSql=new StringBuffer();
userSql.append("SELECT DISTINCT").
append(" (SELECT USER_LIC_TYPE FROM USERS WHERE CODE = U.CODE ").
append(" ) AS USER_LICTYPE , ").
append(" U.CODE, " ).
append(" U.EMAIL_ID, ").
append(" U.MOBILE_NO, ").
append(" U.PROFILE_ID, ").
append(" R.USER_NAME, ").
append(" R.LAST_NAME, ").
append(" U.REGST_STAT, ").
append(" U.SITE_CODE__DEF, ").
append(" U.USR_LEV, ").
append(" U.UUID, ").
append(" U.ACC_PARM1 , ").
append(" U.ENTITY_CODE, ").
append(" U.USER_TYPE, " ).
//Changes added to get values for designation,reportTo,headquarter into EDI_ADDR field on 27-MAR-24
append(" U.EDI_ADDR " ).
//Changes added to get values for designation,reportTo,headquarter into EDI_ADDR field on 27-MAR-24
append(" FROM USER_INVITE U, ").
append(" USER_REGISTRATION R ").
append(" WHERE R.EMAIL_ID = U.EMAIL_ID ").
append(" AND U.PROFILE_ID IN ("+profileIdString+") ").
append(" AND U.CHG_USER = ? ") ;
pstmt = autConn.prepareStatement(userSql.toString());
pstmt.setString(1, chgUser);
rs = pstmt.executeQuery();
invitedUserJsonArr = new JSONArray();
while(rs.next())
{
String profileId=rs.getString("PROFILE_ID");
InviteUser inviteUser = new InviteUser();
inviteUser.setCode(rs.getString("CODE"));
inviteUser.setUserFirstName(rs.getString("USER_NAME"));
inviteUser.setUserLastName(rs.getString("LAST_NAME"));
inviteUser.setEmailId(rs.getString("EMAIL_ID"));
inviteUser.setMobileNo(rs.getString("MOBILE_NO"));
inviteUser.setProfileId(profileId);
if(profileMap.get(profileId) != null) {
System.out.println("Inside profile id not null "+profileId+"profileMap.get(profileId)"+profileMap.get(profileId));
inviteUser.setProfileName(profileMap.get(profileId));
}
//inviteUser.setProfileName(rs.getString("DESCR"));
//Change by Priyanka B on 25/Jan/19 end
inviteUser.setSiteCode(rs.getString("SITE_CODE__DEF"));
inviteUser.setUserLevel(rs.getString("USR_LEV"));
inviteUser.setUuid(rs.getString("UUID"));
inviteUser.setEntityCode(rs.getString("ENTITY_CODE"));
inviteUser.setUserType(rs.getString("USER_TYPE"));
inviteUser.setLicType(rs.getString("USER_LICTYPE"));
String entityCode = rs.getString("ACC_PARM1");
BaseLogger.log("2",null,null,"entityCode ::["+entityCode+"]");
if(entityCode != null && !entityCode.isEmpty())
{
String [] deptGradeItmSer = entityCode.split("\\$");
String dept = deptGradeItmSer[0];
String grade = deptGradeItmSer[1];
String itmSer = deptGradeItmSer[2];
dept = dept.substring(dept.lastIndexOf(":") + 1);
grade = grade.substring(grade.lastIndexOf(":") + 1);
itmSer = itmSer.substring(itmSer.lastIndexOf(":") + 1);
BaseLogger.log("2",null,null,"dept ::["+dept+"]"+"grade ::["+grade+"]"+"itmSer ::["+itmSer+"]");
inviteUser.setItemSer(itmSer);
inviteUser.setGrade(grade);
inviteUser.setDeptCode(dept);
}
//Changes added to get values for designation,reportTo,headquarter into EDI_ADDR field on 27-MAR-24[START]
String ediAddr = rs.getString("EDI_ADDR");
BaseLogger.log("2",null,null,"ediAddr ::["+ediAddr+"]");
if(ediAddr != null && !ediAddr.isEmpty())
{
String [] reportToDesCodeHq = ediAddr.split("\\$");
String designCode = reportToDesCodeHq[0];
String reportTo = reportToDesCodeHq[1];
String stanCodeHq = reportToDesCodeHq[2];
designCode = designCode.substring(designCode.lastIndexOf(":") + 1);
reportTo = reportTo.substring(reportTo.lastIndexOf(":") + 1);
stanCodeHq = stanCodeHq.substring(stanCodeHq.lastIndexOf(":") + 1);
BaseLogger.log("2",null,null,"designCode ::["+designCode+"]"+"reportTo ::["+reportTo+"]"+"stanCodeHq ::["+stanCodeHq+"]");
inviteUser.setDesignCode(designCode);
inviteUser.setReportTo(reportTo);
inviteUser.setStanCodeHq(stanCodeHq);
}
//Changes added to get values for designation,reportTo,headquarter into EDI_ADDR field on 27-MAR-24[END]
if(rs.getString("REGST_STAT") == null || rs.getString("REGST_STAT").equalsIgnoreCase(""))
{
inviteUser.setStatus("P");
}
else
{
inviteUser.setStatus(rs.getString("REGST_STAT"));
}
invitedUsers.add(inviteUser);
}
pstmt.close();
rs.close();
autConn.close();
userConn.close();
}
catch ( Exception e )
{
throw new Exception(e) ;
}
finally
{
if (pstmt != null )
{
try
{
if(autConn != null)
autConn.close();
if(userConn != null)
userConn.close();
if(pstmt != null)
pstmt.close();
if(rs != null)
rs.close();
} catch (SQLException e) {
}
}
}
BaseLogger.log("2",null,null,"invitedUsers which is going to be return == >" +invitedUsers);
return invitedUsers;
}
public InviteUser getInviteUser(String userCode) throws Exception
{
InviteUser inviteUser = new InviteUser();
Connection autConn = null;
Connection userConn = null;
java.sql.PreparedStatement pstmt = null;
ResultSet rs = null;
String entityCode = "";
//Changes added to get values for designation,reportTo,headquarter into EDI_ADDR field on 27-MAR-24
String ediAddr = "";
//Changes added to get values for designation,reportTo,headquarter into EDI_ADDR field on 27-MAR-24
BaseLogger.log("2",null,null,"getInviteUser :: 99999== >" +userCode);
try
{
ConnDriver connDriver = new ConnDriver();
//Change by Priyanka B on 25/Jan/19 Start
autConn = connDriver.getConnectDB("Driver");
userConn = connDriver.getConnectDB( transDB );
String profileIdSql= "SELECT PROFILE_ID,DESCR FROM PROFILE";
pstmt = userConn.prepareStatement(profileIdSql);
rs = pstmt.executeQuery();
StringBuffer profileIdString=new StringBuffer();
String prefix = "";
HashMap<String, String> profileMap=new HashMap<String, String> ();
while(rs.next())
{
profileIdString.append(prefix);
prefix = ",";
String profileId=rs.getString("PROFILE_ID");
String descr=rs.getString("DESCR");
profileIdString =profileIdString.append("'"+profileId+"'");
profileMap.put(profileId, descr);
}
System.out.println("profileIdString in getInviteUser "+profileIdString);
System.out.println("profileMap in getInviteUser "+profileMap);
pstmt.close();
rs.close();
userConn.close();
pstmt=null;
rs=null;
//String userSql = "SELECT (SELECT USER_LIC_TYPE FROM USERS WHERE CODE = U.CODE) as USER_LICTYPE , U.CODE,U.EMAIL_ID,U.MOBILE_NO,P.PROFILE_ID,P.DESCR,R.USER_NAME,R.LAST_NAME,U.REGST_STAT,U.SITE_CODE__DEF,U.USR_LEV,U.UUID,U.ACC_PARM1 ,U.ENTITY_CODE, U.USER_TYPE FROM USER_INVITE U, PROFILE P,USER_REGISTRATION R WHERE R.EMAIL_ID = U.EMAIL_ID AND TRIM(P.PROFILE_ID) = TRIM(U.PROFILE_ID) AND U.CODE = ?";
StringBuffer userSql =new StringBuffer();
userSql.append("SELECT ").
append(" (SELECT USER_LIC_TYPE FROM USERS WHERE CODE = U.CODE " ).
append(" ) AS USER_LICTYPE , ").
append(" U.CODE, ").
append(" U.EMAIL_ID, ").
append(" U.PROFILE_ID, ").
append(" U.MOBILE_NO, ").
append(" R.USER_NAME, ").
append(" R.LAST_NAME, ").
append(" U.REGST_STAT, ").
append(" U.SITE_CODE__DEF, ").
append(" U.USR_LEV, ").
append(" U.UUID, ").
append(" U.ACC_PARM1 , ").
append(" U.ENTITY_CODE, ").
append(" U.USER_TYPE, ").
//Changes added to get values for designation,reportTo,headquarter into EDI_ADDR field on 27-MAR-24
append(" U.EDI_ADDR ").
//Changes added to get values for designation,reportTo,headquarter into EDI_ADDR field on 27-MAR-24
append("FROM USER_INVITE U, ").
append(" USER_REGISTRATION R ").
append("WHERE R.EMAIL_ID = U.EMAIL_ID ").
append("AND U.PROFILE_ID IN ("+profileIdString+") ").
append("AND U.CODE = ?");
pstmt = autConn.prepareStatement(userSql.toString());
pstmt.setString(1, userCode);
rs = pstmt.executeQuery();
if(rs.next())
{
String profileId=rs.getString("PROFILE_ID");
inviteUser.setCode(rs.getString("CODE"));
inviteUser.setUserFirstName(rs.getString("USER_NAME"));
inviteUser.setUserLastName(rs.getString("LAST_NAME"));
inviteUser.setEmailId(rs.getString("EMAIL_ID"));
inviteUser.setMobileNo(rs.getString("MOBILE_NO"));
inviteUser.setProfileId(rs.getString("PROFILE_ID"));
if(profileMap.get(profileId) != null) {
System.out.println("Inside getInviteUser id not null "+profileId+"profileMap.get(profileId)"+profileMap.get(profileId));
inviteUser.setProfileName(profileMap.get(profileId));
}
//inviteUser.setProfileName(rs.getString("DESCR"));
//Change by Priyanka B on 25/Jan/19 end
inviteUser.setSiteCode(rs.getString("SITE_CODE__DEF"));
inviteUser.setUserLevel(rs.getString("USR_LEV"));
inviteUser.setUuid(rs.getString("UUID"));
inviteUser.setEntityCode(rs.getString("ENTITY_CODE"));
inviteUser.setUserType(rs.getString("USER_TYPE"));
inviteUser.setLicType(rs.getString("USER_LICTYPE"));
entityCode = rs.getString("ACC_PARM1");
//Changes added to get values for designation,reportTo,headquarter into EDI_ADDR field on 27-MAR-24
ediAddr = rs.getString("EDI_ADDR");
//Changes added to get values for designation,reportTo,headquarter into EDI_ADDR field on 27-MAR-24
}
BaseLogger.log("3",null,null,"entityCode ::["+entityCode+"]");
//Changes added to get values for designation,reportTo,headquarter into EDI_ADDR field on 27-MAR-24
BaseLogger.log("3",null,null,"ediAddr ::["+ediAddr+"]");
//Changes added to get values for designation,reportTo,headquarter into EDI_ADDR field on 27-MAR-24
if(entityCode != null && !entityCode.isEmpty())
{
String [] deptGradeItmSer = entityCode.split("\\$");
BaseLogger.log("3",null,null,"deptGradeItmSer ::["+deptGradeItmSer+"]");
String dept = deptGradeItmSer[0];
String grade = deptGradeItmSer[1];
String itmSer = deptGradeItmSer[2];
dept = dept.substring(dept.lastIndexOf(":") + 1);
grade = grade.substring(grade.lastIndexOf(":") + 1);
itmSer = itmSer.substring(itmSer.lastIndexOf(":") + 1);
BaseLogger.log("3",null,null,"dept ::["+dept+"]"+"grade ::["+grade+"]"+"itmSer ::["+itmSer+"]");
inviteUser.setItemSer(itmSer);
inviteUser.setGrade(grade);
inviteUser.setDeptCode(dept);
}
//Changes added to get values for designation,reportTo,headquarter into EDI_ADDR field on 27-MAR-24[START]
if(ediAddr != null && !ediAddr.isEmpty())
{
String [] reportToDesCodeHq = ediAddr.split("\\$");
String designCode = reportToDesCodeHq[0];
String reportTo = reportToDesCodeHq[1];
String stanCodeHq = reportToDesCodeHq[2];
designCode = designCode.substring(designCode.lastIndexOf(":") + 1);
reportTo = reportTo.substring(reportTo.lastIndexOf(":") + 1);
stanCodeHq = stanCodeHq.substring(stanCodeHq.lastIndexOf(":") + 1);
BaseLogger.log("2",null,null,"designCode ::["+designCode+"]"+"reportTo ::["+reportTo+"]"+"stanCodeHq ::["+stanCodeHq+"]");
inviteUser.setDesignCode(designCode);
inviteUser.setReportTo(reportTo);
inviteUser.setStanCodeHq(stanCodeHq);
}
//Changes added to get values for designation,reportTo,headquarter into EDI_ADDR field on 27-MAR-24[END]
pstmt.close();
rs.close();
autConn.close();
}
catch ( Exception e )
{
throw new Exception(e) ;
}
finally
{
if (pstmt != null )
{
try
{
if(autConn != null)
autConn.close();
if(userConn != null)
userConn.close();
if(pstmt != null)
pstmt.close();
if(rs != null)
rs.close();
} catch (SQLException e) {
}
}
}
return inviteUser;
}
//Updated by Priyanka B on 12/11/2018 Start
// Added by Nikhil on 28-05-21 added boolean isMultiple as parameter
public String addInviteUser(InviteUser inviteUser ,boolean isMultiple) throws Exception
{
boolean isInviteSuccess = false;
BaseLogger.log("2",null,null," ** In addInviteUser method ** " + new JSONObject(inviteUser));
Connection autConn1 = null;
Connection autConn2 = null;
Connection userConn = null;
String resultStr = "";
String descrResponse = "";
ArrayList<InviteUser> inviteUsersNew = new ArrayList<>();
String uuid = "";
try
{
ConnDriver connDriver = new ConnDriver();
//Change by Priyanka B on 25/Jan/19 Start
autConn1 = connDriver.getConnectDB("Driver");
//conn = connDriver.getConnectDB(transDB);
//conn1 = connDriver.getConnectDB("Driver")
autConn2 = connDriver.getConnectDB("Driver");
userConn = connDriver.getConnectDB(transDB);
//Change by Priyanka B on 25/Jan/19 end
resultStr = validateInviteRequest(inviteUser,autConn1);
BaseLogger.log("3",null,null,"resultStr [" +resultStr +"]");
//Updated By Saitej D [On 16 APR 2019] [To avoid multiple check of validUserRights]
if("".equals(resultStr))
{
resultStr = validateUserRights(inviteUser,userConn);
}
if("".equals(resultStr))
{
uuid = UUID.randomUUID().toString();
String userId = addInviteUser(inviteUser,uuid, autConn1);
inviteUser.setCode(userId);
inviteUser.setSelected(true);
inviteUser.setUuid(uuid);
inviteUsersNew.add(inviteUser);
String responseMessage = activateUser(userId, inviteUser, autConn2,userConn, false);
BaseLogger.log("3",null,null,"responseMessage >> " + responseMessage);
if( responseMessage != null && !isError(responseMessage))
{
BaseLogger.log("3",null,null,"is error not found");
isInviteSuccess = true;
sendInvitation(inviteUsersNew);
}
else
{
BaseLogger.log("3",null,null,"is error found ");
activateUser(userId, inviteUser, autConn2,userConn, true);
}
BaseLogger.log("3",null,null,"isInviteSuccess >>:: " + isInviteSuccess+" ] responseMessage ["+responseMessage+"]" );
resultStr=responseMessage;
}
// Changes by Nikhil on 28-05-21 for multiple user invitation [Start]
if (isMultiple)
{
descrResponse=resultStr;
}
// Changes by Nikhil on 28-05-21 for multiple user invitation [End]
else
{
if( resultStr != null && resultStr.indexOf("Errors") > 0 )
{
resultStr=resultStr.replaceAll("\\<\\?xml(.+?)\\?\\>", "").trim();
BaseLogger.log("3",null,null,"resultStr == >" + resultStr);
JSONObject jsonResonse = xmlToJson(resultStr);
BaseLogger.log("3",null,null,"resultStr in json>>" + jsonResonse);
if(jsonResonse != null) {
JSONObject errsResponse=jsonResonse.optJSONObject("Errors");
JSONObject errorResponse=errsResponse.optJSONObject("error");
descrResponse=errorResponse.optString("message");
descrResponse = descrResponse.replace("Error :", "");
}
}
}
}
catch ( Exception e )
{
BaseLogger.log("3", null, null,"addInviteUser UserInvitationDAO throws Exception : "+e.getMessage());
throw new Exception(e) ;
}
finally
{
try
{
if( isInviteSuccess )
{
autConn1.commit();
}
else
{
autConn1.rollback();
}
if(autConn1 != null)
{
autConn1.close();
}
if(autConn2 != null)
{
autConn2.close();
}
if(userConn != null)
{
userConn.close();
}
}
catch (SQLException e)
{
}
}
//Updated by Priyanka B on 12/11/2018 Start
BaseLogger.log("3", null, null,"addInviteUser UserInvitationDAO "+descrResponse);
return descrResponse;
}
//Added by Priyanka B on 12/11/2018 Start
//Call UserActivationEJB activateUser()
//Change by Priyanka B on 25/Jan/19 Start
private String activateUser(String userCode, InviteUser inviteUser, Connection autConn,Connection userConn, boolean isDelete) throws Exception
{
String responseMessage = "";
BaseLogger.log("3", null, null,"Inside Invite user"+inviteUser);
java.sql.PreparedStatement pstmt = null;
ResultSet rs = null;
int count = 0;
String chgTerm = "SYSTEM";
String enterprise= inviteUser.getEnterprise();
String entType="";
String userLicType=inviteUser.getLicType(); //inviteUser.getUserLicType();
String siteCode = inviteUser.getSiteCode();
String profileId = inviteUser.getProfileId();
BaseLogger.log("3", null, null,"Inside Invite usersiteCode ["+siteCode +"] profileId ["+profileId+"] userLicType ["+userLicType+"] enterprise ["+enterprise+"]" );
try
{
java.sql.Date currentDate = new java.sql.Date(new java.util.Date().getTime());
BaseLogger.log("3", null, null,"isDelete: "+ isDelete +"::user code ::"+userCode);
if(isDelete)
{
//Insert into USERS (Code, user_lic_type, status = A ) and USER_SITE
String sql = "delete from users where CODE = ? ";
BaseLogger.log("3", null, null,"Delete Sql Users "+sql);
pstmt = autConn.prepareStatement(sql);
pstmt.setString(1, userCode);
count = pstmt.executeUpdate();
pstmt.close();
pstmt = null;
rs = null;
autConn.commit();
BaseLogger.log("3", null, null,"Delete count User :"+count);
String userSite = "delete from user_site where USER_ID = ? AND SITE_CODE = ? AND PROFILE_ID = ? ";
pstmt = userConn.prepareStatement(userSite);
pstmt.setString(1, userCode);
pstmt.setString(2, siteCode);
pstmt.setString(3, profileId);
count = pstmt.executeUpdate();
pstmt.close();
pstmt = null;
rs = null;
BaseLogger.log("3", null, null,"Delete count User Site :"+count);
userConn.commit();
}
else
{
//Insert into USERS (Code, user_lic_type, status = A ) and USER_SITE
String sql = "insert into users (CODE,USER_LIC_TYPE , ENTERPRISE, ADD_DATE) values (?, ?, ?, ?) ";
pstmt = autConn.prepareStatement(sql);
pstmt.setString(1, userCode);
pstmt.setString(2, userLicType);
pstmt.setString(3, enterprise);
pstmt.setDate(4, currentDate);//added by mayuri on 24 aug 2023
// pstmt.setString(3, "A");
count = pstmt.executeUpdate();
pstmt.close();
autConn.commit();
pstmt = null;
rs = null;
BaseLogger.log("3", null, null,"Inser count Users :"+count);
String userSite = "Insert into user_site (USER_ID,SITE_CODE,CHG_DATE,PROFILE_ID,CHG_USER,CHG_TERM) values (?,?,?,?,?,?)";
pstmt = userConn.prepareStatement(userSite);
pstmt.setString(1, userCode);
pstmt.setString(2, siteCode);
pstmt.setDate(3, currentDate);
pstmt.setString(4, profileId);
pstmt.setString(5, userCode);
pstmt.setString(6, chgTerm);
pstmt.executeQuery();
pstmt.close();
userConn.commit();
UserActivationEJB userActivationEjb = new UserActivationEJB();
String XTRAParams = getXtraParams();
BaseLogger.log("3", null, null,"XTRAParams tranId userActivationEjb [::::"+XTRAParams+"] userCode ["+userCode+"] enterprise: ["+enterprise+"]");
responseMessage = userActivationEjb.activateUser( userCode, XTRAParams, "N",userInfoBean, this.hostName, enterprise );
}
}
catch ( Exception e )
{
BaseLogger.log("3", null, null,"activateUser UserInvitationDAO throws Exception : "+e.getMessage());
throw new Exception(e) ;
}
finally
{
if (pstmt != null )
{
try
{
if(pstmt != null)
pstmt.close();
if(rs != null)
rs.close();
} catch (SQLException e) {
}
}
}
BaseLogger.log("3", null, null,"responseMessage UserInvitationDAO activateUser [::::"+responseMessage+"]");
return responseMessage;
}
//Added by Priyanka B on 12/11/2018 End
//Change by Priyanka B on 25/Jan/19 Start
public String addInviteUser(InviteUser inviteUser,String uuid, Connection autConn) throws Exception
{
java.sql.PreparedStatement pstmt = null;
ResultSet rs = null;
String userCode = "";
try
{
//Change by Priyanka B on 25/Jan/19 Start
//Changes by Prajyot R. on 12-DEC-2019
//To use USER_INVITE_SEQ directly without referring from Transetup and Refser table.
//userCode = generateTranId("w_registration", inviteUser.getUserFirstName().toUpperCase(), "", inviteUser.getChgUser());
userCode = generateSeq("USER_INVITE_SEQ", "_seq10", autConn);
//Change by Priyanka B on 25/Jan/19 end
String entityCode = "DEPT:"+checkNull(inviteUser.getDeptCode())+"$GRADE:"+checkNull(inviteUser.getGrade())+"$ITMSER:"+ checkNull(inviteUser.getItemSer());
BaseLogger.log("3",null,null,"entityCode in addInviteUser::["+entityCode+"]");
//Changes added to get values for designation,reportTo,headquarter on 27-MAR-24[START]
String ediAddr = "DESIGNCODE:"+checkNull(inviteUser.getDesignCode())+"$REPORTTO:"+checkNull(inviteUser.getReportTo()+"$HQ:"+checkNull(inviteUser.getStanCodeHq()));
BaseLogger.log("3",null,null,"ediAddr in addInviteUser::["+ediAddr+"]");
//Changes added to get values for designation,reportTo,headquarter on 27-MAR-24[END]
// To get registered Invitee User's Information
String registerUserId = inviteUser.getChgUser();
String acc_lock = "";
String ascertion_attentdence = "";
String pass_freq = "";
String wrong_login_cnt ="";
String sql = "Select * from users where code= ?";
pstmt = autConn.prepareStatement(sql);
pstmt.setString(1, registerUserId);
rs = pstmt.executeQuery();
if (rs.next())
{
acc_lock = checkNull(rs.getString("ACCT_LOCK")).trim();
ascertion_attentdence = checkNull(rs.getString("ASCERTAIN_ATTENDANCE")).trim();
pass_freq = checkNull(rs.getString("PASSWD_FREQ")).trim();
wrong_login_cnt = checkNull(rs.getString("WRONG_LOGIN_CNT")).trim();
}
pstmt.close();
rs.close();
pstmt = null;
rs = null;
java.sql.Date currentDate = new java.sql.Date(new java.util.Date().getTime());
String userSql = "INSERT INTO USER_INVITE(CODE,NAME,EMAIL_ID,MOBILE_NO,PROFILE_ID,SITE_CODE__DEF,USR_LEV,UUID, CHG_USER ,TRANS_DB, ENTERPRISE, ACCT_LOCK, ASCERTAIN_ATTENDANCE, PASSWD_FREQ, WRONG_LOGIN_CNT, ENTITY_CODE, USER_TYPE , ACC_PARM1,INVITATION_DATE,EDI_ADDR) VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
//Changes added to get values for designation,reportTo,headquarter into EDI_ADDR field on 27-MAR-24
pstmt = autConn.prepareStatement(userSql);
pstmt.setString(1, userCode);
pstmt.setString(2, inviteUser.getUserFirstName()+ " " +inviteUser.getUserLastName());
pstmt.setString(3, inviteUser.getEmailId());
pstmt.setString(4, inviteUser.getMobileNo());
pstmt.setString(5, inviteUser.getProfileId());
pstmt.setString(6, inviteUser.getSiteCode());
pstmt.setString(7, inviteUser.getUserLevel());
pstmt.setString(8, uuid);
pstmt.setString(9, inviteUser.getChgUser());
pstmt.setString(10, inviteUser.getTransDB());
pstmt.setString(11, inviteUser.getEnterprise());
pstmt.setString(12, acc_lock);
pstmt.setString(13, ascertion_attentdence);
pstmt.setString(14, pass_freq);
pstmt.setString(15, wrong_login_cnt);
pstmt.setString(16, inviteUser.getEntityCode());
pstmt.setString(17, inviteUser.getUserType());
pstmt.setString(18, entityCode);//ACC_PARM1
pstmt.setDate(19, currentDate);//added by mayuri on 24 aug 2023
pstmt.setString(20, ediAddr);//Changes added to get values for designation,reportTo,headquarter into EDI_ADDR field on 27-MAR-24
rs = pstmt.executeQuery();
pstmt.close();
rs.close();
pstmt = null;
rs = null;
// To get registered Invitee Registration Information
String addr1 = "", addr2 = "", addr3 = "", city = "", stateCode = "", pin = "", tele1 = "", tele2 = "", tele3 = "", lob = "";
sql = "Select * from user_registration where user_id= ?";
pstmt = autConn.prepareStatement(sql);
pstmt.setString(1, registerUserId);
rs = pstmt.executeQuery();
if (rs.next())
{
addr1 = checkNull(rs.getString("ADDR1")).trim();
addr2 = checkNull(rs.getString("ADDR2")).trim();
addr3 = checkNull(rs.getString("ADDR3")).trim();
city = checkNull(rs.getString("CITY")).trim();
stateCode = checkNull(rs.getString("STATE_CODE")).trim();
pin = checkNull(rs.getString("PIN")).trim();
tele1 = checkNull(rs.getString("TELE1")).trim();
tele2 = checkNull(rs.getString("TELE2")).trim();
tele3 = checkNull(rs.getString("TELE3")).trim();
lob = checkNull(rs.getString("LINE_OF_BUSINESS")).trim();
}
pstmt.close();
rs.close();
pstmt = null;
rs = null;
BaseLogger.log("3",null,null,"----updated---" +lob);
userSql = "INSERT INTO USER_REGISTRATION (USER_NAME,EMAIL_ID,CONTACT_NO,LAST_NAME,PASS_WD_SHA,USER_ID,SITE_CODE, ADDR1, ADDR2, ADDR3, CITY, STATE_CODE, PIN, TELE1, TELE2, TELE3, LINE_OF_BUSINESS)"
+ " VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
pstmt = autConn.prepareStatement(userSql);
pstmt.setString(1, inviteUser.getUserFirstName());
pstmt.setString(2, inviteUser.getEmailId());
pstmt.setString(3, inviteUser.getMobileNo());
pstmt.setString(4, inviteUser.getUserLastName());
pstmt.setString(5, uuid);
pstmt.setString(6, userCode);
pstmt.setString(7, inviteUser.getSiteCode());
pstmt.setString(8, addr1);
pstmt.setString(9, addr2);
pstmt.setString(10, addr3);
pstmt.setString(11, city);
pstmt.setString(12, stateCode);
pstmt.setString(13, pin);
pstmt.setString(14, tele1);
pstmt.setString(15, tele2);
pstmt.setString(16, tele3);
pstmt.setString(17, lob);
rs = pstmt.executeQuery();
pstmt.close();
rs.close();
}
catch ( Exception e )
{
throw new Exception(e) ;
}
finally
{
if (pstmt != null )
{
try
{
if(pstmt != null)
pstmt.close();
if(rs != null)
rs.close();
} catch (SQLException e) {
}
}
}
return userCode;
}
//Added by Nikhil 31-05-21 change the return type from ArrayList to String
public String addInviteUsers(ArrayList<InviteUser> inviteUsers) throws Exception
{
Connection autConn = null;
String userId = "";
String uuid = "";
ArrayList<InviteUser> inviteUsersNew = new ArrayList<>();
//Added by Nikhil on 31-05-21 for multiple user invitation [Start]
String responseStr = "";
String res;
JSONArray InviteUserArray = new JSONArray();
E12GenericUtility Utility = new E12GenericUtility();
try
{
StringBuffer response = new StringBuffer();
for (InviteUser inviteUser : inviteUsers)
{
BaseLogger.log("3",null,null,inviteUser);
responseStr = "";
uuid = UUID.randomUUID().toString();
responseStr = addInviteUser(inviteUser, true);
JSONObject cuurentInviteuser = new JSONObject();
if (responseStr != null && responseStr.indexOf("Errors") > 0) {
responseStr = responseStr.replaceAll("\\<\\?xml(.+?)\\?\\>", "").trim();
BaseLogger.log("3", null, null, "resultStr == >" + responseStr);
String jsonResonse = Utility.xmlToJSONString(responseStr);
BaseLogger.log("3", null, null, "resultStr in json>>" + jsonResonse);
if (jsonResonse != null)
{
JSONObject jsonObject = new JSONObject(jsonResonse);
JSONObject Rootobj = jsonObject.getJSONObject("Root");
JSONObject errorResponse = Rootobj.optJSONObject("Errors");
JSONObject errorRes = errorResponse.optJSONObject("error");
String message = errorRes.getString("message");
message = message.replace("Error :", "");
String description = errorRes.getString("description");
String type = errorRes.getString("type");
String emailId = inviteUser.getEmailId();
cuurentInviteuser.put("type", type);
cuurentInviteuser.put("Email", emailId);
cuurentInviteuser.put("Status", message);
cuurentInviteuser.put("Description", description);
}
}
InviteUserArray.put(cuurentInviteuser);
}
StringBuffer arrayXml = new StringBuffer();
arrayXml.append("<Root>");
arrayXml.append("<Inviteuser><![CDATA["+InviteUserArray+"]]></Inviteuser>");
arrayXml.append("</Root>");
res = arrayXml.toString();
JSONObject jsonObject = XML.toJSONObject(res);
res = jsonObject.toString();
//Added by Nikhil on 31-05-21 for multiple user invitation [End]
}
catch ( Exception e )
{
throw new Exception(e) ;
}
finally
{
try
{
if(autConn != null)
autConn.close();
} catch (SQLException e) {
}
}
//Added by Nikhil on 31-05-21
return res.toString();
}
public String updateRegstrationStatus(String userCode,String status) throws Exception
{
Connection authConn = null;
java.sql.PreparedStatement pstmt = null;
ResultSet rs = null;
ArrayList<InviteUser> inviteUserList = new ArrayList<InviteUser>();
InviteUser inviteUsr = null;
String currStatus = "";
String errStr = "";
BaseLogger.log("2",null,null,"<---userCode ---->" +userCode + "<--- status --->" +status);
try
{
ConnDriver connDriver = new ConnDriver();
//Change by Priyanka B on 25/Jan/19 Start
authConn = connDriver.getConnectDB("Driver");
//conn = connDriver.getConnectDB( transDB );
//Change by Priyanka B on 25/Jan/19 end
ITMDBAccessEJB itmDBAccessEJB = new ITMDBAccessEJB();
String userSql = "SELECT U.REGST_STAT FROM USER_INVITE U WHERE U.CODE = ?";
pstmt = authConn.prepareStatement(userSql);
pstmt.setString(1, userCode);
rs = pstmt.executeQuery();
if(rs.next())
{
currStatus = rs.getString("REGST_STAT");
}
if(currStatus != null && "R".equalsIgnoreCase(currStatus))
{
if(!rs.next())
{
/*errStr = itmDBAccessEJB.getErrorString("regst_status", "VTUSRALREG", "");
errStr=errStr.replaceAll("\\<\\?xml(.+?)\\?\\>", "").trim();
JSONObject jsonResonse = xmlToJson(errStr);
if(jsonResonse != null) {
JSONObject errsResponse=jsonResonse.optJSONObject("Errors");
JSONObject errorResponse=errsResponse.optJSONObject("error");
descrResponse=errorResponse.optString("message");
descrResponse = descrResponse.replace("Error :", "");
}
return descrResponse;*/
userSql = "UPDATE USERS SET PASS_WD_SHA = ? WHERE CODE = ?";
pstmt = authConn.prepareStatement(userSql);
pstmt.setString(1, "");
pstmt.setString(2, userCode);
pstmt.executeQuery();
pstmt.close();
}
rs.close();
}
BaseLogger.log("3",null,null,"<--- out of if loop --- >");
userSql = "UPDATE USER_INVITE SET REGST_STAT = ? WHERE CODE = ?";
pstmt = authConn.prepareStatement(userSql);
pstmt.setString(1, status);
pstmt.setString(2, userCode);
pstmt.executeQuery();
pstmt.close();
if(status.equalsIgnoreCase("P"))
{
inviteUsr = getInviteUser(userCode);
inviteUsr.selected = true;
BaseLogger.log("3",null,null,"inviteUsr :: == >" +inviteUsr);
inviteUserList.add(inviteUsr);
userSql = "UPDATE USER_REGISTRATION SET PASS_WD_SHA = ? WHERE EMAIL_ID = ?";
pstmt = authConn.prepareStatement(userSql);
pstmt.setString(1, inviteUsr.getUuid());
pstmt.setString(2, inviteUsr.getEmailId());
pstmt.executeQuery();
pstmt.close();
sendInvitation(inviteUserList);
}
//added by mayuri for change STATUS on 24 aug 2023 start
if(status.equalsIgnoreCase("C"))
{
String newStatus= "N";
userSql = "UPDATE USERS SET STATUS = ? WHERE CODE = ?";
pstmt = authConn.prepareStatement(userSql);
pstmt.setString(1, newStatus);
pstmt.setString(2, userCode);
pstmt.executeQuery();
pstmt.close();
pstmt = null;
}
//added by mayuri for change STATUS on 24 aug 2023 end
authConn.commit();
authConn.close();
}
catch ( Exception e )
{
throw new Exception(e) ;
}
finally
{
if (pstmt != null )
{
try
{
pstmt.close();
authConn.close();
} catch (SQLException e) {
}
}
}
return errStr;
}
//Updated By Saitej D [On 16 APR 2019] [To avoid multiple check of validUserRights]
//private String validateInviteRequest(InviteUser inviteUser, Connection autConn,Connection userConn) throws Exception
private String validateInviteRequest(InviteUser inviteUser, Connection autConn) throws Exception
{
String errStr = "";
String errCode = "";
String errFldName = "";
ITMDBAccessEJB itmDBAccessEJB = new ITMDBAccessEJB();
java.sql.PreparedStatement pstmt = null;
ResultSet rs = null;
try
{
String userSql = "SELECT R.EMAIL_ID FROM USER_REGISTRATION R WHERE R.EMAIL_ID = ?";
pstmt = autConn.prepareStatement(userSql);
pstmt.setString(1, inviteUser.getEmailId());
rs = pstmt.executeQuery();
if(rs.next())
{
errCode = "VTINVEIDE";
errFldName = "emailId";
errStr = itmDBAccessEJB.getErrorString(errFldName, errCode, "");
return errStr;
}
//errStr = validateUserRights(inviteUser,userConn);
pstmt.close();
rs.close();
userSql = "SELECT R.EMAIL_ID FROM USER_INVITE R WHERE R.EMAIL_ID = ?";
pstmt = autConn.prepareStatement(userSql);
pstmt.setString(1, inviteUser.getEmailId());
rs = pstmt.executeQuery();
if(rs.next())
{
errCode = "VTINVEIDE";
errFldName = "emailId";
errStr = itmDBAccessEJB.getErrorString(errFldName, errCode, "");
return errStr;
}
//errStr = validateUserRights(inviteUser,userConn);
pstmt.close();
rs.close();
userSql = "SELECT U.EMAIL_ID FROM USERS U WHERE U.EMAIL_ID = ?";
pstmt = autConn.prepareStatement(userSql);
pstmt.setString(1, inviteUser.getEmailId());
rs = pstmt.executeQuery();
if(rs.next())
{
errCode = "VTINVEIDE";
errFldName = "emailId";
errStr = itmDBAccessEJB.getErrorString(errFldName, errCode, "");
return errStr;
}
//errStr = validateUserRights(inviteUser,userConn);
pstmt.close();
rs.close();
userSql = "SELECT U.MOBILE_NO FROM USERS U WHERE U.MOBILE_NO = ?";
pstmt = autConn.prepareStatement(userSql);
pstmt.setString(1, inviteUser.getMobileNo());
rs = pstmt.executeQuery();
if(rs.next())
{
errCode = "VTINVEIDE";
errFldName = "emailId";
errStr = itmDBAccessEJB.getErrorString(errFldName, errCode, "");
return errStr;
}
//errStr = validateUserRights(inviteUser,userConn);
pstmt.close();
rs.close();
} catch (Exception e)
{
e.printStackTrace();
throw new Exception(e);
}
finally
{
pstmt.close();
rs.close();
}
return errStr;
}
public String sendInvitation(ArrayList<InviteUser> inviteUserList) throws Exception
{
String retString = "Success";
EMail email = new EMail();
String to = "";
String cc = "";
String bcc = "";
String sub = "";
String body = "";
Connection userConn = null;
java.sql.PreparedStatement pstmt = null;
ResultSet rs = null;
try
{
ConnDriver connDriver = new ConnDriver();
//conn = connDriver.getConnectDB("Driver");
userConn = connDriver.getConnectDB( transDB );
//ObjectMapper mapper = new ObjectMapper();
String userSql = "SELECT SEND_TO,COPY_TO,BLIND_COPY,SUBJECT,BODY_TEXT FROM MAIL_FORMAT WHERE FORMAT_CODE = ? ";
pstmt = userConn.prepareStatement(userSql);
pstmt.setString(1, "E12_INVIT_USER");
rs = pstmt.executeQuery();
if(rs.next())
{
to = rs.getString("SEND_TO");
cc = rs.getString("COPY_TO");
bcc = rs.getString("BLIND_COPY");
sub = rs.getString("SUBJECT");
body = rs.getString("BODY_TEXT");
}
pstmt.close();
rs.close();
userConn.close();
for (InviteUser inviteUser : inviteUserList)
{
if(inviteUser.selected)
{
BaseLogger.log("3",null,null,"transDB:"+transDB);
//Added to set transDB as enterprise to pass e12RegactionServlet through email(E12_INVIT_USER)
//inviteUser.setEnterprise(transDB);
inviteUser.setTransDB(transDB);
JSONObject jsonObj = new JSONObject(inviteUser);
String mailXmlData = "<root>"
+ "<TO_ADD><![CDATA["+jsonObj.optString(to)+"]]></TO_ADD>";
if(cc != null && cc.trim().length() > 0)
{
mailXmlData = mailXmlData + "<CC_ADD><![CDATA["+cc+"]]></CC_ADD>";
}
if(bcc != null && bcc.trim().length() > 0)
{
mailXmlData = mailXmlData + "<BCC_ADD><![CDATA["+bcc+"]]></BCC_ADD>";
}
mailXmlData = mailXmlData + "<SUBJECT><![CDATA["+sub+"]]></SUBJECT>"
+ "<MESSAGE><![CDATA["+getFormatedEmailBody(body,jsonObj)+"]]></MESSAGE>"
+ "<MESSAGE_TYPE><![CDATA[text/html]]></MESSAGE_TYPE>"
+ "<EMAIL_TYPE><![CDATA[page]]></EMAIL_TYPE>"
+ "</root>";
BaseLogger.log("3",null,null,"Send invitation:mailXmlData:" + mailXmlData);
//Changed by pankaj T. on 10-04-2020 for Configure SMTP mail server against ENTERPRISE
BaseLogger.log("3",null,null,email.sendMail(mailXmlData, null, userInfoBean));
}
}
}
catch ( Exception e )
{
throw new Exception(e) ;
}
finally
{
if (pstmt != null )
{
try
{
if(userConn != null)
userConn.close();
if(pstmt != null)
pstmt.close();
if(rs != null)
rs.close();
} catch (SQLException e) {
}
}
}
return retString;
}
//Change by Priyanka B on 25/Jan/19 Start
//private String generateTranId( String windowName, String emp_Fname, String orgType )throws ITMException
private String generateTranId( String windowName, String emp_Fname, String orgType, String loginUser )throws ITMException
{
java.sql.PreparedStatement pstmt = null;
ResultSet rs = null;
String selSql = "";
String tranId = "";
String tranSer = "";
String keyString = "";
String keyCol = "";
String xmlValues = "";
Connection authConn = null;
try
{
ConnDriver connDriver = new ConnDriver();
//System.out.println("Inside generateTranId trandb ::: "+transDB);
//authConn = connDriver.getConnectDB(transDB);
System.out.println("Inside generateTranId from AUTVIS");
authConn = connDriver.getConnectDB("Driver");
selSql = "SELECT KEY_STRING, TRAN_ID_COL, REF_SER FROM TRANSETUP WHERE TRAN_WINDOW = ? ";
pstmt = authConn.prepareStatement(selSql);
pstmt.setString( 1, windowName );
rs = pstmt.executeQuery();
if (rs.next())
{
keyString = rs.getString("KEY_STRING");
keyCol = rs.getString("TRAN_ID_COL");
tranSer = rs.getString("REF_SER");
}
rs.close();
rs = null;
pstmt.close();
pstmt = null;
BaseLogger.log("3",null,null,"keyString :"+keyString);
BaseLogger.log("3",null,null,"keyCol :"+keyCol);
BaseLogger.log("3",null,null,"tranSer :"+tranSer);
xmlValues ="<?xml version=\"1.0\" encoding=\"utf-8\"?><Root>";
xmlValues = xmlValues + "<Header></Header>";
xmlValues = xmlValues + "<Detail1>";
xmlValues = xmlValues + "<emp_code></emp_code>";
xmlValues = xmlValues + "<emp_fname>" + emp_Fname + "</emp_fname>";
xmlValues = xmlValues + "<org_type>" + orgType + "</org_type>";
xmlValues = xmlValues + "</Detail1></Root>";
BaseLogger.log("3",null,null,"xmlValues :["+xmlValues+"]");
//TransIDGenerator tg = new TransIDGenerator(xmlValues, "BASE", CommonConstants.DB_NAME);
TransIDGenerator tg = new TransIDGenerator(xmlValues, loginUser, CommonConstants.DB_NAME);
tranId = tg.generateTranSeqID(tranSer, keyCol, keyString, authConn);
//Change by Priyanka B on 25/Jan/19 end
BaseLogger.log("3",null,null,"tranId :"+tranId);
}
catch (SQLException ex)
{
BaseLogger.log("0",null,null,"Exception ::" +selSql+ ex.getMessage() + ":");
ex.printStackTrace();
throw new ITMException(ex);
}
catch (Exception e)
{
BaseLogger.log("0",null,null,"Exception ::" + e.getMessage() + ":");
e.printStackTrace();
throw new ITMException(e);
}
finally
{
try
{
if (rs != null)
{
rs.close();
rs = null;
}
if (pstmt != null)
{
pstmt.close();
pstmt = null;
}
if (authConn != null)
{
authConn.commit();
authConn.close();
}
}
catch(Exception e){}
}
return tranId;
}//generateTranTd()
public String validateUserRights(InviteUser inviteUser,Connection userConn) throws Exception
{
String errStr = "";
String errCode = "";
String errFldName = "";
ITMDBAccessEJB itmDBAccessEJB = new ITMDBAccessEJB();
java.sql.PreparedStatement pstmt = null;
ResultSet rs = null;
try
{
String sql = "SELECT PROFILE_ID FROM PROFILE WHERE TRIM(PROFILE_ID) = ?";
pstmt = userConn.prepareStatement(sql);
pstmt.setString(1, inviteUser.profileId.trim());
rs = pstmt.executeQuery();
if(!rs.next())
{
errCode = "VTINVPID";
errFldName = "profileId";
errStr = itmDBAccessEJB.getErrorString(errFldName, errCode, "");
return errStr;
}
pstmt.close();
rs.close();
sql = "SELECT SITE_CODE FROM SITE WHERE SITE_CODE = ?";
pstmt = userConn.prepareStatement(sql);
pstmt.setString(1, inviteUser.siteCode);
rs = pstmt.executeQuery();
if(!rs.next())
{
errCode = "VTINVSITE";
errFldName = "siteCode";
errStr = itmDBAccessEJB.getErrorString(errFldName, errCode, "");
return errStr;
}
pstmt.close();
rs.close();
} catch (Exception e)
{
throw new Exception(e);
}
finally
{
pstmt.close();
rs.close();
}
return errStr;
}
private String getFormatedEmailBody(String bodyTextData, JSONObject jsonObj ) throws ITMException
{
String startFindStr = "#:";
String endFindStr = ":#";
String colFullName = "";
String colName="";
String currColVal = "";
int currentIndex = 0;
int nextSearchIndex = 0;
try
{
if(bodyTextData != null)
{
while(bodyTextData.indexOf(startFindStr,nextSearchIndex) != -1)
{
BaseLogger.log("3",null,null,nextSearchIndex);
currColVal = "";
currentIndex = bodyTextData.indexOf(startFindStr,nextSearchIndex);
String firstPart = bodyTextData.substring(0,currentIndex);
String lastPart = bodyTextData.substring(currentIndex,bodyTextData.length());
colFullName = lastPart.substring(0,lastPart.indexOf(endFindStr)+2);
colName = colFullName.substring(startFindStr.length(),colFullName.lastIndexOf(endFindStr));
currColVal = jsonObj.optString(colName);
bodyTextData = firstPart + lastPart.replaceFirst(colFullName, currColVal);
nextSearchIndex = currentIndex+currColVal.length();
bodyTextData = bodyTextData.replaceAll("#TOMCATE_HOME#",CommonConstants.TOMCAT_HOME);
BaseLogger.log("3",null,null,"Formatted bodyTextData"+bodyTextData);
}
}
}catch(Exception e)
{
throw new ITMException(e);
}
return bodyTextData;
}
public InviteUser updateInviteUser(InviteUser inviteUser) throws Exception
{
Connection autConn = null;
java.sql.PreparedStatement pstmt = null;
try
{
ConnDriver connDriver = new ConnDriver();
//Change by Priyanka B on 25/Jan/19 Start
autConn = connDriver.getConnectDB("Driver");
//conn = connDriver.getConnectDB( transDB );
//Change by Priyanka B on 25/Jan/19 end
String userSql = "UPDATE USER_INVITE SET NAME = ?, EMAIL_ID = ?, MOBILE_NO = ?, PROFILE_ID = ? WHERE CODE = ?";
pstmt = autConn.prepareStatement(userSql);
pstmt.setString(1, inviteUser.getUserFirstName()+ " " +inviteUser.getUserLastName() );
pstmt.setString(2, inviteUser.getEmailId());
pstmt.setString(3, inviteUser.getMobileNo());
pstmt.setString(4, inviteUser.getProfileId());
pstmt.setString(5, inviteUser.getCode());
pstmt.executeQuery();
pstmt.close();
userSql = "UPDATE USER_REGISTRATION SET USER_NAME = ?, CONTACT_NO = ?, LAST_NAME = ?,PASS_WD_SHA = ? WHERE EMAIL_ID = ?";
pstmt = autConn.prepareStatement(userSql);
pstmt.setString(1, inviteUser.getUserFirstName() );
pstmt.setString(2, inviteUser.getMobileNo() );
pstmt.setString(3, inviteUser.getUserLastName() );
pstmt.setString(4, inviteUser.getCode() );
pstmt.setString(5, inviteUser.getEmailId() );
pstmt.executeQuery();
pstmt.close();
autConn.commit();
autConn.close();
}
catch ( Exception e )
{
throw new Exception(e) ;
}
finally
{
if (pstmt != null )
{
try
{
if(autConn != null)
autConn.close();
if(pstmt != null)
pstmt.close();
} catch (SQLException e)
{
e.printStackTrace();
}
}
}
return inviteUser;
}
public void deleteInviteUser(String userCode) throws Exception
{
Connection autConn = null;
java.sql.PreparedStatement pstmt = null;
try
{
ConnDriver connDriver = new ConnDriver();
//Change by Priyanka B on 25/Jan/19 Start
autConn = connDriver.getConnectDB("Driver");
//conn = connDriver.getConnectDB( transDB );
//Change by Priyanka B on 25/Jan/19 end
String userSql = "DELETE FROM USER_REGISTRATION WHERE EMAIL_ID = (SELECT EMAIL_ID FROM USER_INVITE WHERE CODE = ?)";
pstmt = autConn.prepareStatement(userSql);
pstmt.setString(1, userCode);
pstmt.executeQuery();
pstmt.close();
userSql = "DELETE FROM USER_INVITE WHERE CODE = ?";
pstmt = autConn.prepareStatement(userSql);
pstmt.setString(1, userCode);
pstmt.executeQuery();
pstmt.close();
autConn.commit();
autConn.close();
}
catch ( Exception e )
{
throw new Exception(e) ;
}
finally
{
if (pstmt != null )
{
try
{
autConn.close();
pstmt.close();
} catch (SQLException e) {
}
}
}
}
public JSONObject xmlToJson(String transData) throws JSONException
{
try
{
E12GenericUtility utility = new E12GenericUtility();
Document dashboardDom = utility.parseString(transData);
NodeList rootNodeList = dashboardDom.getElementsByTagName("Root");
Node rootNode = null;
rootNode = rootNodeList.item(0);
if( rootNodeList != null && rootNodeList.getLength() > 0 ){
return (JSONObject) xmlToJson(rootNode);
}
}
catch (ITMException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
public Object xmlToJson(Node xmlObj) throws JSONException
{
JSONObject jsonObj = new JSONObject();
if (xmlObj.getNodeType() == Node.ELEMENT_NODE) { // element
if (xmlObj.hasAttributes()) {
NamedNodeMap attributes = xmlObj.getAttributes();
int attribLen = attributes.getLength();
for (int j = 0; j < attribLen; j++) {
Node attribute = attributes.item(j);
String name = attribute.getNodeName();
String value = attribute.getNodeValue();
jsonObj.put(name, value);
}
}
}
if (xmlObj.hasChildNodes()) {
NodeList childNodes = xmlObj.getChildNodes();
int childNodeLen = childNodes.getLength();
for (int i = 0; i < childNodeLen; i++)
{
Node childNode = childNodes.item(i);
String childNodeName = childNode.getNodeName();
String childNodeValue = childNode.getNodeValue();
if("#cdata-section".equalsIgnoreCase(childNodeName) )
{
if (xmlObj.hasAttributes())
{
jsonObj.put("value", childNodeValue);
return jsonObj;
}
else
{
return childNodeValue;
}
}
else if( !"#text".equalsIgnoreCase(childNodeName) )
{
if( jsonObj.optJSONObject(childNodeName) != null )
{
JSONObject old = jsonObj.optJSONObject(childNodeName);
jsonObj.put(childNodeName, new JSONArray());
jsonObj.optJSONArray(childNodeName).put(old);
jsonObj.optJSONArray(childNodeName).put(xmlToJson(childNode));
}
else if( jsonObj.optJSONArray(childNodeName) != null )
{
jsonObj.optJSONArray(childNodeName).put(xmlToJson(childNode));
}
else
{
jsonObj.put(childNodeName, xmlToJson(childNode));
}
}
}
}
return jsonObj;
}
private String checkNull(String str)
{
if(str == null)
{
return "";
}
else
{
return str ;
}
}
//Added by Priyanka B on 12/11/2018 Start
private String getXtraParams() throws Exception
{
StringBuffer xtraParamsBuff = new StringBuffer();
try
{
BaseLogger.log("3",null,null,"get xtra param "+userInfoBean);
if ( userInfoBean != null )
{
UserInfoBean userInfo = userInfoBean;
String XTRA_PARAMS_SEPARATOR = "~~";
xtraParamsBuff.append("loginCode=" + userInfo.getLoginCode());
xtraParamsBuff.append(XTRA_PARAMS_SEPARATOR).append("loginEmpCode=" + userInfo.getEmpCode());
xtraParamsBuff.append(XTRA_PARAMS_SEPARATOR).append("loginSiteCode=" + userInfo.getSiteCode());
xtraParamsBuff.append(XTRA_PARAMS_SEPARATOR).append("entityCode=" + userInfo.getEntityCode());
xtraParamsBuff.append(XTRA_PARAMS_SEPARATOR).append("profileId=" + userInfo.getProfileId());
xtraParamsBuff.append(XTRA_PARAMS_SEPARATOR).append("userType=" + userInfo.getUserType());
xtraParamsBuff.append(XTRA_PARAMS_SEPARATOR).append("runMode=I");
xtraParamsBuff.append(XTRA_PARAMS_SEPARATOR).append("charEnc=" + userInfo.getCharEnc());
xtraParamsBuff.append(XTRA_PARAMS_SEPARATOR).append("termId=" + userInfo.getRemoteHost());
xtraParamsBuff.append(XTRA_PARAMS_SEPARATOR).append("user_lang=" + userInfo.getUserLanguage());
xtraParamsBuff.append(XTRA_PARAMS_SEPARATOR).append("user_country=" + userInfo.getUserCountry());
String chgTerm = userInfo.getRemoteHostName();
if (chgTerm != null && chgTerm.length() > 15)
{
chgTerm = chgTerm.substring(0, 15);
}
else if (chgTerm == null || chgTerm.length() == 0)
{
chgTerm = userInfo.getRemoteHost();
}
xtraParamsBuff.append(XTRA_PARAMS_SEPARATOR).append("chgTerm=" + chgTerm);
}
BaseLogger.log("3",null,null,"xtraParamsBuff ["+xtraParamsBuff+"]");
}
catch (Exception e)
{
e.printStackTrace();
}
return xtraParamsBuff.toString();
}
private boolean isError(String responseMessage) throws ITMException
{
boolean isError = false;
if( responseMessage.indexOf("<Errors>") != -1 )
{
isError = ( ( responseMessage.indexOf("<Errors></Errors>") == -1 ) && isErrorNodeFound( responseMessage ) );
}
// BaseLogger.log("3", userInfo,editorId, isError + " checkError :: returnStr " + returnString);
BaseLogger.log("3",null,null,"inside is error "+isError);
return isError;
}
private boolean isErrorNodeFound(String errXmlString) throws ITMException
{
boolean isErrorNodeFound = false;
try
{
if (errXmlString.indexOf("<Errors>") != -1)
{
NodeList errorNodeList = (new E12GenericUtility()).parseString(errXmlString).getElementsByTagName("error");
int errorNodeListLen = errorNodeList.getLength();
for (int i = 0; i < errorNodeListLen; i++)
{
String errorType = errorNodeList.item(i).getAttributes().getNamedItem("type").getNodeValue();
BaseLogger.log("3",null,null,"Inside i serror not fount error type "+errorType);
//Changed By Prajyot on 20-SEP-2012 for Fatal Error
//if ("E".equals(errorType) || "W".equals(errorType) || "P".equals(errorType) || "X".equals(errorType))
if("E".equals(errorType))
{
isErrorNodeFound = true;
break;
}
}
}
}
catch (Exception e)
{
e.printStackTrace();
throw new ITMException(e);
}
return isErrorNodeFound;
}
//Added by Priyanka B on 12/11/2018 End
public JSONArray getInviteUserLiscenceArr(String enterprise) throws Exception
{
//InviteUser inviteUser = new InviteUser();
ArrayList<InviteUser> inviteUsers = new ArrayList<>();
JSONArray userLicJsonArr = new JSONArray();
Connection autConn = null;
java.sql.PreparedStatement pstmt = null;
ResultSet rs = null;
try
{
ConnDriver connDriver = new ConnDriver();
autConn = connDriver.getConnectDB("Driver");
String userSql = "select USER_LIC_TYPE, \n" +
" CASE WHEN USER_LIC_TYPE = 'E' THEN 'Enterprise'\n" +
" WHEN USER_LIC_TYPE = 'P' THEN 'Portal User/ESS User/SFA User'\n" +
" WHEN USER_LIC_TYPE = 'R' THEN 'Read Only User'\n" +
" WHEN USER_LIC_TYPE = 'X' THEN 'External Access User'\n" +
" WHEN USER_LIC_TYPE = 'S' THEN 'Starter User'\n" +
" ELSE '' END as USER_LIC_DESCR, \n" +
" LIC_USERS from entp_users_licence where ENTERPRISE = ? ";
pstmt = autConn.prepareStatement(userSql);
pstmt.setString(1, enterprise);
rs = pstmt.executeQuery();
while(rs.next())
{
InviteUser inviteUser = new InviteUser();
JSONObject userLiscList = new JSONObject();
userLiscList.put("User_Lic_Type", rs.getString("USER_LIC_TYPE"));
userLiscList.put("User_Lic_Descr", rs.getString("USER_LIC_DESCR"));
userLiscList.put("Lic_Users", rs.getString("LIC_USERS"));
userLicJsonArr.put(userLiscList);
BaseLogger.log("3",null,null,"userLicJsonArr"+userLicJsonArr);
}
pstmt.close();
rs.close();
autConn.close();
}
catch ( Exception e )
{
throw new Exception(e) ;
}
finally
{
if (pstmt != null )
{
try
{
if(autConn != null)
autConn.close();
if(pstmt != null)
pstmt.close();
if(rs != null)
rs.close();
} catch (SQLException e) {
}
}
}
return userLicJsonArr;
}
/*
public String generateLicenseKey(String url, String licenseType) {
CommonDBAccessEJB commonDBAccessEJB = new CommonDBAccessEJB();
String licenseKey = url + licenseType;
String encryptedKey = commonDBAccessEJB.encrypt(licenseKey);
String response = "";
boolean isExist = false;
String licenseKeysFilePath = CommonConstants.JBOSSHOME + File.separator + "setting" + File.separator + "licenses" + File.separator +"licenseKeys"+".json";
BaseLogger.log("2",null,null,"File Path ::["+licenseKeysFilePath+"]");
try
{
File existingFile = new File(licenseKeysFilePath);
if(!existingFile.exists()) {
FileWriter file = new FileWriter(licenseKeysFilePath);
}
BufferedReader br = new BufferedReader(new FileReader(existingFile));
String fileString;
JSONArray licenseJsonArr = new JSONArray();
while ((fileString = br.readLine()) != null) {
licenseJsonArr = new JSONArray(fileString);
}
for (int i = 0; i < licenseJsonArr.length(); i++) {
JSONObject json = licenseJsonArr.getJSONObject(i);
if(json.optString("ServerUrl").equals(url) && json.optString("LicenseType").equals(licenseType)) {
isExist = true;
}
}
if(licenseType == null || (licenseType != null && licenseType.isEmpty())) {
response = "Invalid license type";
}
else if(!isExist) {
JSONObject licenseJson = new JSONObject();
licenseJson.put("ServerUrl", url);
licenseJson.put("LicenseType", licenseType);
licenseJson.put("SHA_256", encryptedKey);
licenseJsonArr.put(licenseJson);
try (FileWriter file = new FileWriter(licenseKeysFilePath)) {
file.write(licenseJsonArr.toString());
file.flush();
response = "License Key Added Successfully";
}
catch (IOException e) {
e.printStackTrace();
}
}else {
response = "License Key Already Exists";
}
}
catch(Exception e)
{
BaseLogger.log("0",null,null,"Exception in generateLicenseKey ::["+e+"]");
}
return response;
}
public String checkLicenseValidation(String url, String licenseType) {
BaseLogger.log("2",null,null,"key in checkUserValidation: ["+url+"] licenseType :["+licenseType+"]");
CommonDBAccessEJB commonDBAccessEJB = new CommonDBAccessEJB();
String response = "";
String licenseKey = url + licenseType;
boolean isValid = false;
String licenseKeysFilePath = CommonConstants.JBOSSHOME + File.separator + "setting" + File.separator + "licenses" + File.separator +"licenseKeys"+".json";
try
{
File file = new File(licenseKeysFilePath);
if(file.exists()) {
BufferedReader br = new BufferedReader(new FileReader(file));
String fileString;
JSONArray licenseJsonArr = null;
while ((fileString = br.readLine()) != null) {
licenseJsonArr = new JSONArray(fileString);
}
for (int i = 0; i < licenseJsonArr.length(); i++) {
JSONObject json = licenseJsonArr.getJSONObject(i);
BaseLogger.log("2",null,null,"json : ["+json+"]");
if (json.optString("ServerUrl").equals(url) && json.optString("LicenseType").equals(licenseType)) {
String storedEncryptedKey = json.getString("SHA_256");
String decryptedKey = commonDBAccessEJB.decrypt(storedEncryptedKey);
BaseLogger.log("2",null,null,"decryptedKey : ["+decryptedKey+"] key: ["+licenseKey+"]");
if(decryptedKey.equals(licenseKey)) {
isValid = true;
}
}
}
if(isValid) {
response = "valid";
}else {
response = "invalid";
}
}
}
catch(Exception e)
{
BaseLogger.log("0",null,null,"Exception in checkLicenseValidation ::["+e+"]");
}
BaseLogger.log("3",null,null,"response in user invitation dao "+response);
return response;
}
*/
public String getUserLicType(String userId) throws Exception{
Connection autConn = null;
java.sql.PreparedStatement pstmt = null;
ResultSet rs = null;
String userLicType = "";
String[] columns = {"CODE", "MOBILE_NO", "EMAIL_ID", "USER_ID"};
BaseLogger.log("3",null,null,"<--- userId in getUserLicType --> "+userId);
try
{
ConnDriver connDriver = new ConnDriver();
//Change by Priyanka B on 25/Jan/19 Start
autConn = connDriver.getConnectDB("Driver");
//conn = connDriver.getConnectDB( transDB );
//Change by Priyanka B on 25/Jan/19 end
for (int i = 0; i < columns.length; i++) {
String userSql = "select USER_LIC_TYPE" +
" from users where " +
columns[i] + " = ?";
pstmt = autConn.prepareStatement(userSql);
pstmt.setString(1, userId);
rs = pstmt.executeQuery();
if (rs.next()) {
userLicType = rs.getString("USER_LIC_TYPE");
BaseLogger.log("2",null,null,"<----userLicType ---- > ["+ userLicType +"]");
break;
}
if(rs != null)
{
rs.close();
rs = null;
}
if(pstmt != null)
{
pstmt.close();
pstmt = null;
}
}
}
catch ( Exception e )
{
throw new Exception(e);
}
finally
{
if (pstmt != null )
{
try
{
if(autConn != null)
autConn.close();
if(pstmt != null)
pstmt.close();
if(rs != null)
rs.close();
} catch (SQLException e) {
}
}
}
return userLicType;
}
// Added By Prajyot on 14-11-18 : Server Licence Validation - Start
public String generateLicenseKey(String url, String ip, String userLimit, String enterprise)
{
String response = "";
boolean isExist = false;
JSONObject existingServerLicenceEntry = null;
CommonDBAccessEJB commonDBAccessEJB = new CommonDBAccessEJB();
String licenseKey = url + enterprise + ip + enterprise;
String encryptedKey = commonDBAccessEJB.encrypt(licenseKey);
String licenseKeysFolderPath = CommonConstants.JBOSSHOME + File.separator + "setting" + File.separator + "licenses";
String licenseKeysFilePath = licenseKeysFolderPath + File.separator +"licenseKeys"+".json";
BaseLogger.log("2",null,null,"File Path ::["+licenseKeysFilePath+"]");
try
{
File existingFolder = new File(licenseKeysFolderPath);
if(!existingFolder.exists()) {
existingFolder.mkdir();
}
File existingFile = new File(licenseKeysFilePath);
if(!existingFile.exists()) {
existingFile.createNewFile();
}
String fileString = FileUtils.readFileToString(existingFile);
BaseLogger.log("2",null,null,"File String ::["+fileString+"]");
JSONArray licenseJsonArr = new JSONArray();
if(!fileString.trim().isEmpty()) {
licenseJsonArr = new JSONArray(fileString);
}
for (int i = 0; i < licenseJsonArr.length(); i++)
{
JSONObject serverLicenceEntry = licenseJsonArr.getJSONObject(i);
String serverLicence = serverLicenceEntry.optString("server_licence");
serverLicence = commonDBAccessEJB.decrypt(serverLicence);
if(serverLicence.indexOf(url) != -1 && serverLicence.indexOf(ip) != -1 ) {
isExist = true;
existingServerLicenceEntry = serverLicenceEntry;
break;
}
}
if( userLimit == null || userLimit.trim().isEmpty() || userLimit.equals("0") )
{
userLimit = "5";
}
if(!isExist)
{
JSONArray userLicences = new JSONArray();
JSONObject licenseJson = new JSONObject();
licenseJson.put("users_limit", userLimit);
licenseJson.put("server_licence", encryptedKey);
licenseJson.put("user_licences", userLicences);
licenseJsonArr.put(licenseJson);
try
{
FileUtils.writeStringToFile(existingFile, licenseJsonArr.toString());
response = "License Key Added Successfully";
}
catch (IOException e) {
e.printStackTrace();
}
}
else
{
response = "License Key Already Exists";
}
}
catch(Exception e)
{
BaseLogger.log("0",null,null,"Exception in generateLicenseKey ::["+e+"]");
}
return response;
}
public String checkLicenseValidation(String hostUrl, String userCode, String enterprise) throws ITMException {
BaseLogger.log("2",null,null,"key in checkUserValidation: ["+hostUrl+"] loginID :["+userCode+"] enterprise:["+enterprise+"]");
CommonDBAccessEJB commonDBAccessEJB = new CommonDBAccessEJB();
if(enterprise != null && !enterprise.trim().isEmpty()) {
hostUrl = hostUrl + enterprise.trim();
}
String response = "";
boolean isValidHost = false;
boolean isValidUser = false;
String licenseKeysFolderPath = CommonConstants.JBOSSHOME + File.separator + "setting" + File.separator + "licenses";
String licenseKeysFilePath = licenseKeysFolderPath + File.separator +"licenseKeys"+".json";
JSONObject existingServerLicenceEntry = null;
try
{
File existingFolder = new File(licenseKeysFolderPath);
File file = new File(licenseKeysFilePath);
if(existingFolder.exists() && file.exists()) {
String fileString = FileUtils.readFileToString(file);
JSONArray licenseJsonArr = new JSONArray(fileString);
for (int i = 0; i < licenseJsonArr.length(); i++)
{
JSONObject serverLicenceEntry = licenseJsonArr.getJSONObject(i);
BaseLogger.log("2",null,null,"serverLicenceEntry : ["+serverLicenceEntry+"]");
String serverLicence = serverLicenceEntry.optString("server_licence");
serverLicence = commonDBAccessEJB.decrypt(serverLicence);
if(serverLicence.indexOf(hostUrl) != -1 ) {
isValidHost = true;
existingServerLicenceEntry = serverLicenceEntry;
break;
}
}
if (isValidHost)
{
JSONArray userLicences = existingServerLicenceEntry.optJSONArray("user_licences");
String usersLimit = existingServerLicenceEntry.optString("users_limit");
BaseLogger.log("2",null,null,"existingServerLicence : ||" + existingServerLicenceEntry.toString() +"|| userLicences ::"+userLicences);
if(usersLimit.equals("-1"))
{
isValidUser = true;
}
else
{
for (int i = 0; i < userLicences.length(); i++)
{
String userLicense = userLicences.getString(i);
userLicense = commonDBAccessEJB.decrypt(userLicense);
BaseLogger.log("2",null,null,"userLicense ::["+userLicense+"]");
if(userLicense.equals(userCode))
{
isValidUser = true;
break;
}
}
}
}
}
if(isValidUser) {
response = "valid";
}else {
response = "invalid";
}
}
catch(Exception e)
{
BaseLogger.log("0",null,null,"Exception in checkLicenseValidation ::["+e+"]");
}
BaseLogger.log("2",null,null,"response in user invitation dao ::["+response+"]");
return response;
}
//Sample licencesKeys.json
/*
[
{
"server_licence": "domain + ip",
"users_limit" : "5",
"user_licences":[
{
"user_licence": "<>",
"licence_type": "E"
}
]
},
{
"domain_licence": "<>",
"users_limit" : "-1",
"user_licences":[
{
"user_licence": "<>",
"licence_type": "E"
}
]
}
]
*/
// Added By Prajyot on 14-11-18 : Server Licence Validation - End
// Added By Saitej D on 21 Nov 2018 [To generate user license on register or invite] START
public void setHostName(String hostName) {
this.hostName = hostName;
}
public String generateUserLicense(String userCode, String hostName, String enterprise) throws ITMException {
BaseLogger.log("2",null,null,"In generateUserLicense ::["+userCode+"] hostName:["+hostName+"]");
CommonDBAccessEJB commonDBAccessEJB = new CommonDBAccessEJB();
String response = "";
boolean licenseAdded = false;
String licenseKey = userCode;
String encryptedKey = commonDBAccessEJB.encrypt(licenseKey);
hostName = hostName + enterprise;
String licenseKeysFolderPath = CommonConstants.JBOSSHOME + File.separator + "setting" + File.separator + "licenses";
String licenseKeysFilePath = licenseKeysFolderPath + File.separator +"licenseKeys"+".json";
BaseLogger.log("2",null,null,"File Path ::["+licenseKeysFilePath+"]");
try
{
File existingFolder = new File(licenseKeysFolderPath);
if(!existingFolder.exists()) {
existingFolder.mkdir();
}
File existingFile = new File(licenseKeysFilePath);
if(!existingFile.exists()) {
existingFile.createNewFile();
}
String fileString = FileUtils.readFileToString(existingFile);
BaseLogger.log("2",null,null,"File String ::["+fileString+"]");
if(!fileString.trim().isEmpty()) {
JSONArray licenseJsonArr = new JSONArray(fileString);
for (int i = 0; i < licenseJsonArr.length(); i++)
{
JSONObject serverLicenceEntry = licenseJsonArr.getJSONObject(i);
BaseLogger.log("2",null,null,"serverLicenceEntry : ["+serverLicenceEntry+"]");
String serverLicence = serverLicenceEntry.optString("server_licence");
String usersLimit = serverLicenceEntry.optString("users_limit");
serverLicence = commonDBAccessEJB.decrypt(serverLicence);
if(serverLicence.indexOf(hostName) != -1 )
{
JSONArray userLicences = serverLicenceEntry.optJSONArray("user_licences");
int limit = Integer.parseInt(usersLimit);
if(limit > userLicences.length() || limit == -1)
{
boolean userLicenseExist = false;
for (int j = 0; j < userLicences.length(); j++)
{
String userLicense = userLicences.optString(j);
String decryptedUserId = commonDBAccessEJB.decrypt(userLicense);
if(decryptedUserId.equals(userCode))
{
userLicenseExist = true;
break;
}
}
if(!userLicenseExist) {
userLicences.put(encryptedKey);
licenseJsonArr.getJSONObject(i).put("user_licences", userLicences);
licenseAdded = true;
}
}
break;
}
}
try
{
FileUtils.writeStringToFile(existingFile, licenseJsonArr.toString());
}
catch (IOException e) {
e.printStackTrace();
}
}
if(licenseAdded) {
response = "License Generated";
}else {
response = "License Generation Failed";
}
}
catch(Exception e)
{
BaseLogger.log("0",null,null,"Exception in generateLicenseKey ::["+e+"]");
}
return response;
}
public String generateServerLicense(String url, String ip, String userLimit, String enterprise) throws ITMException
{
String response = "";
boolean isExist = false;
CommonDBAccessEJB commonDBAccessEJB = new CommonDBAccessEJB();
String licenseKey = url + enterprise;
String encryptedKey = commonDBAccessEJB.encrypt(licenseKey);
String licenseKeysFolderPath = CommonConstants.JBOSSHOME + File.separator + "setting" + File.separator + "licenses";
String licenseKeysFilePath = licenseKeysFolderPath + File.separator +"licenseKeys"+".json";
BaseLogger.log("2",null,null,"licenseKey ::["+licenseKey+"]");
try
{
File existingFolder = new File(licenseKeysFolderPath);
if(!existingFolder.exists()) {
existingFolder.mkdir();
}
File existingFile = new File(licenseKeysFilePath);
if(!existingFile.exists()) {
existingFile.createNewFile();
}
String fileString = FileUtils.readFileToString(existingFile);
BaseLogger.log("2",null,null,"File String ::["+fileString+"]");
JSONArray licenseJsonArr = new JSONArray();
if(!fileString.trim().isEmpty()) {
licenseJsonArr = new JSONArray(fileString);
}
for (int i = 0; i < licenseJsonArr.length(); i++)
{
JSONObject serverLicenceEntry = licenseJsonArr.getJSONObject(i);
String serverLicence = serverLicenceEntry.optString("server_licence");
serverLicence = commonDBAccessEJB.decrypt(serverLicence);
if( serverLicence.indexOf(licenseKey) != -1 ) {
isExist = true;
break;
}
}
if( userLimit == null || userLimit.trim().isEmpty() || userLimit.equals("0") )
{
userLimit = "5";
}
if(!isExist)
{
JSONArray userLicences = new JSONArray();
JSONObject licenseJson = new JSONObject();
licenseJson.put("users_limit", userLimit);
licenseJson.put("server_licence", encryptedKey);
licenseJson.put("user_licences", userLicences);
licenseJsonArr.put(licenseJson);
try
{
FileUtils.writeStringToFile(existingFile, licenseJsonArr.toString());
response = "License Key Added Successfully";
}
catch (IOException e) {
e.printStackTrace();
}
}
else
{
response = "License Key Already Exists";
}
}
catch(Exception e)
{
BaseLogger.log("0",null,null,"Exception in generateServerLicense ::["+e+"]");
}
return response;
}
// Added By Saitej D on 21 Nov 2018 [To generate user license on register or invite] END
public JSONObject getUsersData(String enterprise, String userLicType)
{
JSONObject usersData = new JSONObject();
try
{
BaseLogger.log("3", null, null,"Inside getUsersData... transDB["+transDB+"] enterprise["+enterprise+"]userLicType["+userLicType+"]");
StringBuffer sqlStrBuff = new StringBuffer();
sqlStrBuff.append(" SELECT CODE as \"User Code\", NAME as \"User Name\", EMAIL_ID as \"Email ID\", MOBILE_NO as \"Mobile No.\", PROFILE_ID as \"Profile ID\", ");
sqlStrBuff.append(" STATUS as \"Status\", USER_LIC_TYPE as \"User Licence Type\", ACTIVATION_CODE as \"Activation Code\" ");
sqlStrBuff.append(" FROM USERS ");
sqlStrBuff.append(" WHERE ENTERPRISE = '" + enterprise + "' ");
sqlStrBuff.append(" ORDER BY USER_LIC_TYPE, ACTIVATION_CODE ");
BaseLogger.log("3", null, null,"Inside UserInvitationDAO::getUsersData SQL Exection done ! SQL => \n " + sqlStrBuff.toString());
CommonDBAccessEJB commonDBAccessEJB = new CommonDBAccessEJB();
JSONArray usersDataArray = commonDBAccessEJB.getSQLResultJSONData(sqlStrBuff.toString(), "Driver");
UserActivationEJB userActivationEjb = new UserActivationEJB();
String licUsersCnt = userActivationEjb.getLicUserLimitFromAUT(userLicType, enterprise);
String activeUsersCnt = commonDBAccessEJB.getDBColumnValue(" USERS ", " COUNT(*) ", " WHERE STATUS='A' AND USER_LIC_TYPE='"+userLicType+"' AND ENTERPRISE = '"+enterprise+"' " , "Driver");
int licUsersLimit = 0;
try
{
licUsersLimit = Integer.parseInt(licUsersCnt);
}
catch (NumberFormatException e)
{
BaseLogger.log("2", null, null, "NumberFormatException in getUsersData : " + e.getMessage());
e.printStackTrace();
}
usersData.put("LIC_USER_LIMIT", licUsersLimit); // -1 : Unlimited
usersData.put("ACTIVE_USER_CNT", activeUsersCnt);
usersData.put("AUTH_USERS_DATA", usersDataArray);
usersData.put("STATUS", "SUCCESS");
}
catch(Exception e)
{
usersData = new JSONObject();
try
{
usersData.put("STATUS", "FAILURE");
}
catch (JSONException e1)
{
BaseLogger.log("0", null, null,"Inside UserInvitationDAO::getUsersData Exception Catch Block : " + e.getMessage());
e1.printStackTrace();
}
BaseLogger.log("0", null, null,"Inside UserInvitationDAO::getUsersData Exception : " + e.getMessage());
e.printStackTrace();
}
return usersData;
}
public void updateUserLicence(String transDB, String enterprise, String userLicType, String activeUserCnt, JSONArray userCodes)
{
boolean authUpdated = false;
boolean userUpdated = false;
Connection authConn = null;
Connection userConn = null;
try
{
BaseLogger.log("3", null, null,"Inside updateUserLicence... transDB["+transDB+"] enterprise["+enterprise+"]userLicType["+userLicType+"]activeUserCnt["+activeUserCnt+"] \n userCodes>>" + userCodes );
List<String> updateStatements = new ArrayList<String>();
UserActivationEJB userActivationEjb = new UserActivationEJB();
for( int idx = 0; idx < userCodes.length(); idx++ )
{
String userCode = userCodes.optString(idx);
String hashData = userCode+userLicType+activeUserCnt;
String activationCode = userActivationEjb.createHashCode( hashData );
String updateStatement = " UPDATE USERS SET ACTIVATION_CODE = '" + activationCode + "' USER_LIC_TYPE = '" + userLicType + "' WHERE CODE = '" + userCode + "' ";
updateStatements.add(updateStatement);
}
writeToFile(updateStatements, "UserInviteUpdate.sql");
/*
ConnDriver connDriver = new ConnDriver();
authConn = connDriver.getConnectDB("Driver"); //Auth Schema
userConn = connDriver.getConnectDB(transDB); //User Schema
authUpdated = updateBatchStatements(authConn, updateStatements);
System.out.println("updateUserLicence... in USER SCHEMA Done");
userUpdated = updateBatchStatements(userConn, updateStatements);
System.out.println("updateUserLicence... in AUTH SCHEMA Done");
*/
}
catch (Exception ae)
{
BaseLogger.log("0", null, null,"Exception in updateUserLicence... " + ae.getMessage() );
ae.printStackTrace();
}
finally
{
try
{
if( userConn != null )
{
if(!userUpdated)
{
userConn.rollback();
}
else
{
userConn.commit();
}
userConn.close();
userConn = null;
}
if( authConn != null )
{
if(!authUpdated)
{
authConn.rollback();
}
else
{
authConn.commit();
}
authConn.close();
authConn = null;
}
}
catch (Exception e)
{
BaseLogger.log("0", null, null,"Exception in updateBatchStatements connection or resultset closing::[ " + e.getMessage() + " ]");
e.printStackTrace();
}
}
}
private boolean updateBatchStatements(Connection schemaConn, List<String> updateStatements)
{
boolean status = false;
Statement stmt = null;
String updateSql = "";
try
{
stmt = schemaConn.createStatement();
for( String updateStatement : updateStatements )
{
stmt.addBatch( updateStatement );
updateSql = updateStatement;
}
// submit a batch of update commands for execution
int[] updateCounts = stmt.executeBatch();
System.out.println("Update Statements execution [" + updateCounts.length + "]");
stmt.close();
stmt = null;
status = true;
}
catch (SQLException se)
{
status = false;
System.out.println("SQLException in updateBatchStatements... [" + updateSql + " ]" + se.getMessage() );
se.printStackTrace();
}
catch (Exception ae)
{
status = false;
System.out.println("Exception in updateBatchStatements... [" + updateSql + " ]" + ae.getMessage() );
ae.printStackTrace();
}
finally
{
try
{
if (stmt != null)
{
stmt.close();
stmt = null;
}
}
catch (Exception e)
{
System.out.println("Exception in updateBatchStatements connection or resultset closing::[ " + e.getMessage() + " ]");
e.printStackTrace();
}
}
return status;
}
private void writeToFile(List<String> updateStatements, String fileName)
{
try
{
File file = new File( createFolder() + File.separator + fileName );
System.out.println("File path "+fileName+" : " + file.getPath());
FileWriter fw = new FileWriter(file);
fw.write("\n-- No of Rows = " + updateStatements.size() + "\n" );
for(String updateStatement : updateStatements)
{
fw.write( updateStatement + " \n");
}
fw.flush();
fw.close();
}
catch ( Exception e )
{
System.out.println("Exception in writeToFile" + e.getMessage());
e.printStackTrace();
}
}
private String createFolder() throws Exception
{
if( CommonConstants.JBOSSHOME == null )
{
CommonConstants.setIBASEHOME();
}
String jbossHome = CommonConstants.JBOSSHOME;
String dbCompareLogFolderName = jbossHome + File.separator + "UserInvitation";
File dbCompareLogFolder = new File(dbCompareLogFolderName);
if (! dbCompareLogFolder.exists())
{
dbCompareLogFolder.mkdir();
}
return dbCompareLogFolderName;
}
//Changes by Prajyot R. on 12-DEC-2019 - Starts
//To use USER_INVITE_SEQ directly without referring from Transetup and Refser table.
//_seq i.e. locally generated sequence by the user using sequnce generator not from the table
private String generateSeq(String ls_seq_name , String kval, Connection con) throws ITMException
{
String retstr = "";
try
{
long lastSeq = 0 ;
int SeqLen = Integer.parseInt( kval.substring(4,6) ) ;
String qry1 ="" ;
BaseLogger.log("3",null,null,"ls_seq_name ="+ls_seq_name);
if(!"mysql".equalsIgnoreCase( CommonConstants.DB_NAME ) )
{
if (ls_seq_name != null && ls_seq_name.trim().length() > 0 )
{
if ( "db2".equalsIgnoreCase( CommonConstants.DB_NAME ) )
{
qry1 = "SELECT NEXTVAL FOR "+ls_seq_name.trim()+" FROM DUAL" ;
}
else
{
qry1 = "SELECT "+ls_seq_name.trim()+".NEXTVAL FROM DUAL" ;
}
}
else
{
//Added check for DB2
if ( "db2".equalsIgnoreCase( CommonConstants.DB_NAME ) )
{
qry1 = "SELECT NEXTVAL FOR BATCHSEQ FROM DUAL" ;
}
else
{
qry1 = "SELECT BATCHSEQ.NEXTVAL FROM DUAL" ;
}
}
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(qry1);
while(rs.next())
{
lastSeq = rs.getLong(1);
}
if(rs != null)
{
rs.close(); rs = null;
}
if(stmt!=null)
{
stmt.close(); stmt = null;
}
}
else
{
String maxValueStr = "";
String getMaxValue = "";
Statement st = null;
ResultSet rst = null;
PreparedStatement pstm = null;
if(ls_seq_name != null && ls_seq_name.trim().length() >0)
{
getMaxValue = "SELECT MAX(MAX_VALUE) FROM SEQUENCES WHERE SEQ_NAME = "+ls_seq_name.trim()+" ";
st = con.createStatement();
rst = st.executeQuery(getMaxValue);
if(rst.next())
{
lastSeq = rst.getInt(1);
if(lastSeq != 0)
{
maxValueStr = "UPDATE SEQUENCES SET MAX_VALUE = ? WHERE SEQ_NAME = ?";
pstm = con.prepareStatement(maxValueStr);
pstm.setLong(1,lastSeq+1);
pstm.setString(2,ls_seq_name.trim());
}
else
{
lastSeq = 1;
maxValueStr = "INSERT INTO SEQUENCES ( MAX_VALUE ,SEQ_NAME) VALUES (?, ?) ";
pstm = con.prepareStatement(maxValueStr);
pstm.setLong(1,lastSeq);
pstm.setString(2,ls_seq_name.trim());
}
}
}
else
{
getMaxValue = "SELECT MAX(MAX_VALUE) FROM SEQUENCES WHERE SEQ_NAME = 'BATCH_SEQ' ";
st = con.createStatement();
rst = st.executeQuery(getMaxValue);
if(rst.next())
{
lastSeq = rst.getInt(1);
if(lastSeq != 0)
{
maxValueStr = "UPDATE SEQUENCES SET MAX_VALUE = ? WHERE SEQ_NAME = 'BATCH_SEQ' ";
pstm = con.prepareStatement(maxValueStr);
pstm.setLong(1,lastSeq+1);
}
else
{
lastSeq = 1;
maxValueStr = "INSERT INTO SEQUENCES ( MAX_VALUE ,SEQ_NAME) VALUES (?, ?) ";
pstm = con.prepareStatement(maxValueStr);
pstm.setLong(1,lastSeq);
pstm.setString(2,"BATCH_SEQ");
}
}
pstm.executeUpdate();
}
if(rst != null)
{
rst.close(); rst = null;
}
if(st!=null)
{
st.close(); st = null;
}
if(pstm!=null)
{
pstm.close(); pstm = null;
}
}
String tmp1 = "000000000000000000000000"+lastSeq;
int tm_len = tmp1.length()-SeqLen ;
retstr = tmp1.substring(tm_len ) ;
BaseLogger.log("3",null,null,"Return from generateSeq retstr = "+retstr);
}
catch(Exception e)
{
throw new ITMException(e );
}
return retstr ;
}
//Changes by Prajyot R. on 12-DEC-2019 - Ends
// Added by mayuri on 27-aug-2023 for user type is employee and entity type avialable in employee table then get data [start]
public String getEmpDetail(String empCode,UserInfoBean userInfo) throws Exception
{
BaseLogger.log("1",null,null,"empCode 2581 in getEmpDetail method == >" +empCode);
BaseLogger.log("1",null,null,"userInfo 2581 in getEmpDetail method == >" +userInfo);
Connection con = null;
PreparedStatement stmt = null;
ResultSet mResultSet = null;
String deptCode ="";
String grade = "";
String cadre = "";
//Changes added to get values for designation,reportTo,headquarter on 27-MAR-24[START]
String reportTo = "";
String stanCodeHq = "";
String designCode = "";
//Changes added to get values for designation,reportTo,headquarter on 27-MAR-24[END]
JSONArray createRepoIdArray = new JSONArray();
try
{
ConnDriver mConnDriver = new ConnDriver();
BaseLogger.log("1",null,null,"userInfo 2581 in userInvitation dao == >" +userInfo);
con = mConnDriver.getConnectDB(userInfo.getTransDB());
String sql = "SELECT DEPT_CODE,GRADE,CADRE,DESIGN_CODE,REPORT_TO,STAN_CODE__HQ FROM EMPLOYEE WHERE EMP_CODE= ?";
//Changes added to get values for designation,reportTo,headquarter on 27-MAR-24
stmt = con.prepareStatement(sql);
stmt.setString(1, empCode);
mResultSet = stmt.executeQuery();
while (mResultSet.next())
{
JSONObject createUserJson = new JSONObject();
deptCode = mResultSet.getString("DEPT_CODE");
grade = mResultSet.getString("GRADE");
cadre = mResultSet.getString("CADRE");
//Changes added to get values for designation,reportTo,headquarter on 27-MAR-24[START]
designCode = mResultSet.getString("DESIGN_CODE");
reportTo = mResultSet.getString("REPORT_TO");
stanCodeHq = mResultSet.getString("STAN_CODE__HQ");
//Changes added to get values for designation,reportTo,headquarter on 27-MAR-24[END]
createUserJson.put("DEPT_CODE",deptCode);
createUserJson.put("GRADE",grade);
createUserJson.put("CADRE",cadre);
//Changes added to get values for designation,reportTo,headquarter on 27-MAR-24[START]
createUserJson.put("DESIGN_CODE",designCode);
createUserJson.put("REPORT_TO",reportTo);
createUserJson.put("STAN_CODE__HQ",stanCodeHq);
//Changes added to get values for designation,reportTo,headquarter on 27-MAR-24[END]
BaseLogger.log("3", null,null, "print createUserJson...5605" + createUserJson);
createRepoIdArray.put(createUserJson);
}
mResultSet.close();
mResultSet = null;
stmt.close();
stmt = null;
con.close();
con = null;
}
catch (Exception e)
{
try {
if (con != null) {
con.rollback();
con.close();
con = null;
}
}
catch (Exception catche) {
e.printStackTrace();
BaseLogger.log("0", null, (String)null, (Object)("Exception inside updateLoginTrace[" + catche.getMessage() + "]"));
}
throw new Exception( e );
}
finally {
if (con != null) {
if (stmt != null)
{
stmt.close();
stmt = null;
}
if (mResultSet != null) {
mResultSet.close();
mResultSet = null;
}
if (con != null) {
con.close();
con = null;
}
}
}
BaseLogger.log("0", null, (String)null, (Object)("Print createRepoIdArray::::::::::" + createRepoIdArray));
return createRepoIdArray.toString();
}
// Added by mayuri on 27-aug-2023 for user type is employee and entity type avialable in employee table then get data [end]
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment