Commit d9329cab authored by pborate's avatar pborate

Account activity server.

git-svn-id: http://15.206.35.175/svn/proteus/business-java/trunk@178814 ce508802-f39f-4f6c-b175-0d175dae99d5
parent 65522c4a
package ibase.dashboard.common.hibernate.bean;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Transient;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import org.hibernate.search.annotations.Analyze;
import org.hibernate.search.annotations.Field;
import org.hibernate.search.annotations.Indexed;
import org.hibernate.search.annotations.Store;
import org.json.JSONException;
import org.json.JSONObject;
import ibase.dashboard.common.hibernate.utility.HibernateUtil;
@Indexed
@Entity
@Table(name = "Employee")
@XmlRootElement(name = "employee")
public class Employee implements java.io.Serializable
{
private static final long serialVersionUID = 1L;
@Id
@Column(name="EMP_CODE")
@Field(store = Store.YES, analyze = Analyze.NO)
private String empCode;
@Column(name="EMP_FNAME")
private String empFname;
@Column(name="EMP_LNAME")
private String empLname;
@Column(name="DESIGNATION")
private String designation;
@Column(name="REPORT_TO")
private String reportTo;
public Employee() {
}
public Employee(String empCode, String empFname, String empLname, String designation, String reportTo
) {
this.empCode = empCode;
this.empFname = empFname;
this.empLname = empLname;
this.designation = designation;
this.reportTo = reportTo;
}
public String getEmpCode() {
return empCode;
}
public void setEmpCode(String empCode) {
this.empCode = empCode;
}
public String getEmpFname() {
return empFname;
}
public void setEmpFname(String empFname) {
this.empFname = empFname;
}
public String getEmpLname() {
return empLname;
}
public void setEmpLname(String empLname) {
this.empLname = empLname;
}
public String getDesignation() {
return designation;
}
public void setDesignation(String designation) {
this.designation = designation;
}
public String getReportTo() {
return reportTo;
}
public void setReportTo(String reportTo) {
this.reportTo = reportTo;
}
@Override
public String toString(){
return "\n Employee.toString >> [" + new JSONObject(this).toString() + "]";
}
}
package ibase.dashboard.common.hibernate.bean;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.xml.bind.annotation.XmlRootElement;
import org.hibernate.search.annotations.Analyze;
import org.hibernate.search.annotations.Field;
import org.hibernate.search.annotations.Indexed;
import org.hibernate.search.annotations.Store;
import org.json.JSONObject;
@Indexed
@Entity
@Table(name = "LOGINTRACE")
@XmlRootElement(name = "LoginTrace")
public class LoginTrace implements java.io.Serializable
{
private static final long serialVersionUID = 1L;
@Id
@Field(store = Store.YES, analyze = Analyze.NO)
@Column(name="USERID")
private String userId;
@Column(name="LOGINTIME")
private Date loginTime;
@Column(name="LOGOUTTIME")
private Date logoutTime;
@Id
@Field(store = Store.YES, analyze = Analyze.NO)
@Column(name="SESSIONID")
private String sessionId;
@Column(name="LOGIN_STATUS")
private String loginStatus;
@Column(name="SESSION_DESTROY")
private String sessionDestroy;
@Column(name="DEVICE_TYPE")
private String deviceType;
@Column(name="HOST_IP")
private String hostIp;
@Column(name="CURRENT_GEO_POS")
private String currentGeoPos;
@Column(name="LOGIN_BATTERY_STAT")
private Integer loginBatteryStat;
@Column(name="LOGOUT_BATTERY_STAT")
private Integer logoutBatteryStat;
@Column(name="OS_NAME")
private String osName;
@Column(name="OS_VERSION")
private String osVersion;
@Column(name="CLIENT_APP")
private String clientApp;
@Column(name="CLIENT_APP_VER")
private String clientAppVer;
public LoginTrace() {
}
public LoginTrace(String userId, Date loginTime, Date logoutTime, String sessionId, String loginStatus,
String sessionDestroy,String deviceType,String hostIp,String currentGeoPos,Integer loginBatteryStat,
Integer logoutBatteryStat,String osName,String osVersion,String clientApp,String clientAppVer
) {
this.userId = userId;
this.loginTime = loginTime;
this.logoutTime = logoutTime;
this.sessionId = sessionId;
this.loginStatus = loginStatus;
this.sessionDestroy = sessionDestroy;
this.deviceType = deviceType;
this.hostIp = hostIp;
this.currentGeoPos = currentGeoPos;
this.loginBatteryStat = loginBatteryStat;
this.logoutBatteryStat=logoutBatteryStat;
this.osName = osName;
this.osVersion=osVersion;
this.clientApp = clientApp;
this.clientAppVer=clientAppVer;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public Date getLoginTime() {
return loginTime;
}
public void setLoginTime(Date loginTime) {
this.loginTime = loginTime;
}
public Date getLogoutTime() {
return logoutTime;
}
public void setLogoutTime(Date logoutTime) {
this.logoutTime = logoutTime;
}
public String getSessionId() {
return sessionId;
}
public void setSessionId(String sessionId) {
this.sessionId = sessionId;
}
public String getLoginStatus() {
return loginStatus;
}
public void setLoginStatus(String loginStatus) {
this.loginStatus = loginStatus;
}
public String getSessionDestroy() {
return sessionDestroy;
}
public void setSessionDestroy(String sessionDestroy) {
this.sessionDestroy = sessionDestroy;
}
public String getDeviceType() {
return deviceType;
}
public void setDeviceType(String deviceType) {
this.deviceType = deviceType;
}
public String getHostIp() {
return hostIp;
}
public void setHostIp(String hostIp) {
this.hostIp = hostIp;
}
public String getCurrentGeoPos() {
return currentGeoPos;
}
public void setCurrentGeoPos(String currentGeoPos) {
this.currentGeoPos = currentGeoPos;
}
public Integer getLoginBatteryStat() {
return loginBatteryStat;
}
public void setLoginBatteryStat(Integer loginBatteryStat) {
this.loginBatteryStat = loginBatteryStat;
}
public Integer getLogoutBatteryStat() {
return logoutBatteryStat;
}
public void setLogoutBatteryStat(Integer logoutBatteryStat) {
this.logoutBatteryStat = logoutBatteryStat;
}
public String getOsName() {
return osName;
}
public void setOsName(String osName) {
this.osName = osName;
}
public String getOsVersion() {
return osVersion;
}
public void setOsVersion(String osVersion) {
this.osVersion = osVersion;
}
public String getClientApp() {
return clientApp;
}
public void setClientApp(String clientApp) {
this.clientApp = clientApp;
}
public String getClientAppVer() {
return clientAppVer;
}
public void setClientAppVer(String clientAppVer) {
this.clientAppVer = clientAppVer;
}
@Override
public String toString(){
return "\n LoginTrace.toString >> [" + new JSONObject(this).toString() + "]";
}
}
/*
{
"userId": "",
"userName": "",
"designation": "",
"batteryStatus": {
"dayStart": "",
"dayEnd": "",
"loginTime": "",
"logoutTime": ""
},
"activityDetail": [
{
"browserName": "",
"totalTime": "",
"hostIp": "",
"currentGeoPos": "",
"activityData": [
{
"actObjName": "",
"actObjDescr": "",
"accessStartTime": "",
"accessEndTime": ""
},
{
"actObjName": "",
"actObjDescr": "",
"accessStartTime": "",
"accessEndTime": ""
}
]
},
{
"browserName": "",
"totalTime": "",
"hostIp": "",
"currentGeoPos": "",
"activityData": [
{
"actObjName": "",
"actObjDescr": "",
"accessStartTime": "",
"accessEndTime": ""
},
{
"actObjName": "",
"actObjDescr": "",
"accessStartTime": "",
"accessEndTime": ""
}
]
}
]
}
*/
\ No newline at end of file
package ibase.dashboard.common.hibernate.bean;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.xml.bind.annotation.XmlRootElement;
import org.hibernate.search.annotations.Analyze;
import org.hibernate.search.annotations.Field;
import org.hibernate.search.annotations.Indexed;
import org.hibernate.search.annotations.Store;
import org.json.JSONObject;
import oracle.sql.DATE;
@Indexed
@Entity
@Table(name = "USER_DEVICE")
@XmlRootElement(name = "UserDevice")
public class UserDevice implements java.io.Serializable
{
private static final long serialVersionUID = 1L;
@Id
@Field(store = Store.YES, analyze = Analyze.NO)
@Column(name="USER_ID")
private String userId;
@Column(name="DEVICE_ID__PUSH")
private String deviceIdPush;
@Column(name="DEVICE_OS")
private String deviceOs;
@Column(name="DEVICE_TYPE")
private String deviceType;
@Column(name="EFF_FROM")
private Date effFrom;
@Column(name="VALID_UPTO")
private Date validUpto;
@Column(name="ACTIVE")
private String active;
@Column(name="DEVICE_MAKE")
private String deviceMake;
@Column(name="DEVICE_MAC_ADDR")
private String deviceMacAddr;
public UserDevice() {
}
public UserDevice(String userId,String deviceIdPush,String deviceOs,String deviceType,
Date effFrom, Date validUpto, String active, String deviceMake, String deviceMacAddr
) {
this.userId = userId;
this.deviceIdPush = deviceIdPush;
this.deviceOs = deviceOs;
this.deviceType = deviceType;
this.effFrom = effFrom;
this.validUpto = validUpto;
this.active = active;
this.deviceMake = deviceMake;
this.deviceMacAddr = deviceMacAddr;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getDeviceIdPush() {
return deviceIdPush;
}
public void setDeviceIdPush(String deviceIdPush) {
this.deviceIdPush = deviceIdPush;
}
public String getDeviceOs() {
return deviceOs;
}
public void setDeviceOs(String deviceOs) {
this.deviceOs = deviceOs;
}
public String getDeviceType() {
return deviceType;
}
public void setDeviceType(String deviceType) {
this.deviceType = deviceType;
}
public Date getEffFrom() {
return effFrom;
}
public void setEffFrom(Date effFrom) {
this.effFrom = effFrom;
}
public Date getValidUpto() {
return validUpto;
}
public void setValidUpto(Date validUpto) {
this.validUpto = validUpto;
}
public String getActive() {
return active;
}
public void setActive(String active) {
this.active = active;
}
public String getDeviceMake() {
return deviceMake;
}
public void setDeviceMake(String deviceMake) {
this.deviceMake = deviceMake;
}
public String getDeviceMacAddr() {
return deviceMacAddr;
}
public void setDeviceMacAddr(String deviceMacAddr) {
this.deviceMacAddr = deviceMacAddr;
}
@Override
public String toString(){
return "\n UserDevice.toString >> [" + new JSONObject(this).toString() + "]";
}
}
package ibase.dashboard.common.hibernate.bean;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Transient;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import org.hibernate.search.annotations.Analyze;
import org.hibernate.search.annotations.Field;
import org.hibernate.search.annotations.Indexed;
import org.hibernate.search.annotations.Store;
import org.json.JSONException;
import org.json.JSONObject;
import ibase.dashboard.common.hibernate.utility.HibernateUtil;
@Indexed
@Entity
@Table(name = "USERS")
@XmlRootElement(name = "UserProfile")
public class UserProfile implements java.io.Serializable
{
private static final long serialVersionUID = 1L;
@Id
@Column(name="CODE")
@Field(store = Store.YES, analyze = Analyze.NO)
private String userCode;
@Column(name="BIRTH_DATE")
private Date birthDate;
@Column(name="GENDER")
private String gender;
@Column(name="NAME")
private String userName;
@Transient
private String firstName;
@Transient
private String lastName;
@Column(name="EMAIL_ID")
private String emailId;
@Column(name="MOBILE_NO")
private String contactNo;
@Column(name="EMP_CODE")
private String empCode;
public UserProfile() {
}
public UserProfile(String userCode, Date birthDate, String gender, String userName, String emailId,
String contactNo,String empCode) {
this.userCode = userCode;
this.birthDate = birthDate;
this.gender = gender;
this.userName = userName;
this.emailId = emailId;
this.contactNo = contactNo;
this.empCode=empCode;
}
public String getEmpCode() {
return empCode;
}
public void setEmpCode(String empCode) {
this.empCode = empCode;
}
public String getUserCode() {
return userCode;
}
@XmlElement
public void setUserCode(String userCode) {
this.userCode = userCode;
}
public Date getBirthDate() {
return birthDate;
}
@XmlElement
public void setBirthDate(Date birthDate) {
this.birthDate = birthDate;
}
public String getGender() {
return gender;
}
@XmlElement
public void setGender(String gender) {
this.gender = gender;
}
public String getUserName() {
return userName;
}
@XmlElement
public void setUserName(String userName) {
this.userName = userName;
}
public String getFirstName() {
return firstName;
}
@XmlElement
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
@XmlElement
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmailId() {
return emailId;
}
@XmlElement
public void setEmailId(String emailId) {
this.emailId = emailId;
}
public String getContactNo() {
return contactNo;
}
@XmlElement
public void setContactNo(String contactNo) {
this.contactNo = contactNo;
}
@Override
public String toString(){
return "\n UserProfile.toString >> [" + new JSONObject(this).toString() + "]";
}
}
package ibase.dashboard.common.hibernate.dao;
import java.io.File;
import java.lang.reflect.Array;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import org.apache.commons.io.FileUtils;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.query.Query;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.omg.CORBA.CODESET_INCOMPATIBLE;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import ibase.dashboard.common.hibernate.bean.Employee;
import ibase.dashboard.common.hibernate.bean.LoginTrace;
import ibase.dashboard.common.hibernate.bean.UserProfile;
import ibase.dashboard.common.hibernate.utility.HibernateUtil;
import ibase.utility.E12GenericUtility;
//6DBC5A495F0F2C5371D59DC89EB06F41
public class AccountActivityDao
{
private static String siteTranDB = "DEFAULT";
public String getUserActivityData(String loginCode, String profileId)throws Exception
{
JSONArray activityDataFinal = new JSONArray();
System.out.println("getUserActivityData>>>");
profileId=profileId.trim();
if( "ADMIN".equalsIgnoreCase(profileId) || "ADM".equalsIgnoreCase(profileId) )
{
List<JSONObject> fileDataList= getUserActivityFileData(null, "", "");
for(JSONObject fileDataObj : fileDataList )
{
String userId = fileDataObj.optString("userId");
String activityDate = fileDataObj.optString("activityDate");
String fileContents = fileDataObj.optString("fileContents");
System.out.println("fileName::::::::: ["+userId+"]["+activityDate+"]");
JSONObject activityData = createActivityData(userId, fileContents);
activityDataFinal.put(activityData);
}
}
else
{
List<String> userDataList = getUserDetails(loginCode,profileId);
List<JSONObject> fileDataList= getUserActivityFileData(userDataList, "", "");
JSONObject selfActivityData = new JSONObject();
JSONArray teamActivityData = new JSONArray();
System.out.println("userDataList AFTER>>>"+userDataList);
for(JSONObject fileDataObj : fileDataList )
{
String userId = fileDataObj.optString("userId");
String activityDate = fileDataObj.optString("activityDate");
String fileContents = fileDataObj.optString("fileContents");
System.out.println("fileName::::::::: ["+userId+"]["+activityDate+"]");
if( userId.equalsIgnoreCase(loginCode) )
{
selfActivityData = createActivityData(userId, fileContents);
}
else
{
JSONObject teamMemberActivityData = createActivityData(userId, fileContents);
teamActivityData.put(teamMemberActivityData);
}
}
selfActivityData.put("TEAM", teamActivityData);
activityDataFinal.put(selfActivityData);
}
System.out.println("activityDataFinal data " + activityDataFinal.toString());
return activityDataFinal.toString();
}
private JSONObject createActivityData(String userCode, String activityLogXml)
{
E12GenericUtility e12GenericUtility = new E12GenericUtility();
ArrayList<String> objNameList = new ArrayList<String>();
JSONObject activityData = new JSONObject();
try
{
System.out.println("Inside create activity data");
Document activityDoc = e12GenericUtility.parseString(activityLogXml);
NodeList activitySessIdNL = activityDoc.getElementsByTagName("ACTIVITY_SESSION_ID");
activityData = processSessionIds( userCode, activitySessIdNL );
JSONArray sessionArray = activityData.optJSONArray("ALL_SESSIONS");
System.out.println("sessionArrayList"+sessionArray);
activityData.remove("ALL_SESSIONS");
NodeList activityNL = activityDoc.getElementsByTagName("ACTIVITY");
//System.out.println("Inside getUserActivityData" + activityNL +" >> "+ activityNL.getLength() );
if( activityNL != null && activityNL.getLength() > 0 )
{
int len = activityNL.getLength();
for( int j = 0; j < len; j++)
{
String activityObj = "";
String activityTitle = "";
String activitySeesionId = "";
String activityIcon="";
NodeList activityChildNL = activityNL.item(j).getChildNodes();
//System.out.println("processActivityAction i" + i);
System.out.println("==");
int actChLen = activityChildNL.getLength();
//System.out.println("processActivityAction actChLen" + actChLen);
for( int actCh = 0; actCh < actChLen; actCh++)
{
Node activityChildNode = activityChildNL.item(actCh);
if( activityChildNode.getNodeType() == Node.ELEMENT_NODE)
{
String activityChName = activityChildNode.getNodeName();
System.out.println("Inside getUserActivityData >> "+ activityChName );
if( "ACTIVITY_OBJECT".equalsIgnoreCase( activityChName ) )
{
activityObj = activityChildNode.getFirstChild().getNodeValue();
//System.out.println( activityChName + "[" + activityObj + "]");
if(activityObj != null && objNameList.indexOf(activityObj) == -1 )
{
objNameList.add(activityObj);
}
}
else if("ACTIVITY_ICON".equalsIgnoreCase( activityChName ))
{
System.out.println("inside activity icon");
activityIcon = activityChildNode.getFirstChild() != null ? activityChildNode.getFirstChild().getNodeValue() : "e12Menu.png";
System.out.println( "activityIcon [" + activityIcon +"]");
}
else if("ACTIVITY_TITLE".equalsIgnoreCase( activityChName ))
{
System.out.println("activity title"+actCh+"--"+activityChildNode.getFirstChild().getNodeValue());
activityTitle = activityChildNode.getFirstChild().getNodeValue();
System.out.println( "activityTitle [" + activityTitle +"]");
}
else if( "ACTIVITY_SESSION_ID".equalsIgnoreCase( activityChName ) )
{
activitySeesionId = activityChildNode.getFirstChild().getNodeValue();
//System.out.println(activityChName + "[" + activitySeesionId + "]");
}
else if( "ACTIVITY_ACTION".equalsIgnoreCase( activityChName ) )
{
System.out.println( "ACTIVITY_OBJECT[" + activityObj + "]");
System.out.println( "activityTitle[" + activityTitle + "]");
System.out.println( "ACTIVITY_SESSION_ID[" + activitySeesionId + "]");
//System.out.println("[" + activityChildNode.getChildNodes() + "]");
//System.out.println( processActivityAction(activityChildNode) );
JSONObject activityObjData = activityData.optJSONObject(activitySeesionId);
if( activityObjData == null )
{
activityObjData = new JSONObject();
}
JSONObject prevActivityObj = activityObjData.optJSONObject(activityObj);
if( prevActivityObj == null )
{
prevActivityObj = new JSONObject();
}
JSONArray prevArray = prevActivityObj.optJSONArray("DATA");
if( prevArray == null )
{
prevArray = new JSONArray();
}
//System.out.println(prevArray);
prevActivityObj.put("DESCR", activityTitle);
prevActivityObj.put("ICON", activityIcon);
prevActivityObj.put("DATA", processActivityAction(activityChildNode, prevArray) );
activityObjData.put(activityObj, prevActivityObj);
activityData.put(activitySeesionId, activityObjData);
}
}
}
}
}
//System.out.println( activityData );
JSONArray allSeesionArray = new JSONArray();
int arrayLen = sessionArray.length();
System.out.println("Object data "+arrayLen);
for( int sessIdx = 0; sessIdx < arrayLen; sessIdx ++ )
{
String sessionId = sessionArray.optString(sessIdx);
System.out.println("inside sessionid>>"+sessionId);
JSONObject activityObjData = activityData.optJSONObject(sessionId);
if( activityObjData == null )
{
activityObjData = new JSONObject();
}
JSONArray allObjectArray = new JSONArray();
ArrayList<ActivityTime> objTimeArray = new ArrayList<ActivityTime>();
for( String objName : objNameList )
{
JSONObject prevActivityObj = activityObjData.optJSONObject(objName);
if( prevActivityObj != null )
{
JSONArray prevArray = prevActivityObj.optJSONArray("DATA");
if( prevArray.length() > 0 )
{
ActivityTime totalTime = calcTotalTime(prevArray);
prevActivityObj.remove("DATA");
prevActivityObj.put("ACCESS_TIME", totalTime.toJSON());
objTimeArray.add(totalTime);
}
prevActivityObj.put("OBJ_NAME", objName);
activityObjData.remove(objName);
allObjectArray.put(prevActivityObj);
}
}
int len = objTimeArray.size();
if( len > 0 )
{
ActivityTime objTotalTime = objTimeArray.get(0);
System.out.println(" objTotalTime >>" + objTotalTime);
for(int idx = 1; idx < len; idx++)
{
ActivityTime actTime = objTimeArray.get(idx);
objTotalTime.addTime(actTime);
System.out.println(" totalTime >" + idx + ">" + objTotalTime);
}
activityObjData.put("ACCESS_TIME", objTotalTime.toJSON());
}
activityObjData.put("OBJECTS", allObjectArray);
activityData.remove(sessionId);
allSeesionArray.put( activityObjData );
}
activityData.put("SESSIONS", allSeesionArray);
activityData.put("TEAM", new JSONArray());
List<Employee> employeeDataList = getUserDesignation(userCode);
for( Employee employee : employeeDataList )
{
activityData.put("NAME", employee.getEmpFname());
activityData.put("DESIGNATION", employee.getDesignation());
activityData.put("USER_ID", userCode);
}
System.out.println("activity data " + activityData.toString());
}
catch (Exception e)
{
e.printStackTrace();
}
return activityData;
}
private ActivityTime calcTotalTime(JSONArray prevArray) throws JSONException
{
ActivityTime firstTime = null;
ArrayList<ActivityTime> timeArray = new ArrayList<ActivityTime>();
System.out.println("DATA>>>"+prevArray);
for( int i = 0; i < prevArray.length(); i++ )
{
System.out.println(i);
JSONObject jsonObject1 = prevArray.getJSONObject(i);
String startTime = jsonObject1.getString("ACCESS_START_TIME");
String endTime = jsonObject1.optString("ACCESS_END_TIME");
System.out.println("ACCESS_END_TIME>>"+endTime);
System.out.println("ACCESS_START_TIME>>"+startTime);
ActivityTime actTime = new ActivityTime(startTime, endTime);
timeArray.add(actTime);
System.out.println( "ActivityTime >> " + actTime );
}
int len = timeArray.size();
if( len > 0 )
{
firstTime = timeArray.get(0);
System.out.println(" firstTime >>" + firstTime);
for(int idx = 1; idx < len; idx++)
{
ActivityTime actTime = timeArray.get(idx);
firstTime.addTime(actTime);
System.out.println(" firstTime >" + idx + ">" + firstTime);
}
}
return firstTime;
}
public JSONObject processSessionIds(String userCode, NodeList activitySessIdNL) throws JSONException
{
JSONObject activityData = new JSONObject();
StringBuffer sessionIds = new StringBuffer();
JSONArray sessionArray = new JSONArray ();
if( activitySessIdNL != null && activitySessIdNL.getLength() > 0 )
{
int len = activitySessIdNL.getLength();
for( int i = 0; i < len; i++)
{
String activitySeesionId = null;
Node activityChildNode = activitySessIdNL.item(i);
if( activityChildNode.getNodeType() == Node.ELEMENT_NODE)
{
String activityChName = activityChildNode.getNodeName();
activitySeesionId = activityChildNode.getFirstChild().getNodeValue();
System.out.println("Inside processSessionIds >> "+ activityChName );
}
if(activitySeesionId != null && sessionIds.indexOf(activitySeesionId) == -1 )
{
sessionIds.append("'").append(activitySeesionId).append("',");
sessionArray.put(activitySeesionId);
}
}
sessionIds.append(" '' ");
System.out.println("SessionIds::::"+sessionIds);
}
//Get Data from Logintrace
List<LoginTrace> loginTraceList = getLogDetails(userCode, sessionIds.toString() );
System.out.println("loginTraceList::::"+loginTraceList);
for( LoginTrace loginTrace : loginTraceList )
{
JSONObject activityObjData = new JSONObject();
System.out.println("loginTrace.getClass()>>>>"+loginTrace.getClass());
String activitySeesionId = loginTrace.getSessionId();
activityObjData.put("SESSION_ID", activitySeesionId);
activityObjData.put("DEVICE_TYPE", checkNull(loginTrace.getDeviceType()));
activityObjData.put("OS_NAME", checkNull(loginTrace.getOsName()));
activityObjData.put("HOST_IP", checkNull(loginTrace.getHostIp()));
activityObjData.put("CURRENT_GEO_POS", checkNull(loginTrace.getCurrentGeoPos()));
activityObjData.put("OS_VERSION", checkNull(loginTrace.getOsVersion()));
activityObjData.put("CLIENT_APP", checkNull(loginTrace.getClientApp()));
activityObjData.put("CLIENT_APP_VER",checkNull(loginTrace.getClientAppVer()));
activityObjData.put("LOGIN_TIME", checkNullDate(loginTrace.getLoginTime()));
activityObjData.put("LOGOUT_TIME", checkNullDate(loginTrace.getLogoutTime()));
activityObjData.put("LOGIN_BATTERY_STAT", checkNull(loginTrace.getLoginBatteryStat()));
activityObjData.put("LOGOUT_BATTERY_STAT",checkNull(loginTrace.getLogoutBatteryStat()));
ActivityTime loginTime = new ActivityTime(loginTrace.getLoginTime(), loginTrace.getLogoutTime());
// int batteryStatus =loginTrace.getLoginBatteryStat()- loginTrace.getLogoutBatteryStat();
activityObjData.put("TOTAL_TIME", loginTime.toJSON());
System.out.println("TOTAL_TIME loginTime ["+ loginTime + "]");
System.out.println("activityData processSessionIds"+activityData);
activityData.put(activitySeesionId, activityObjData);
}
activityData.put("ALL_SESSIONS", sessionArray);
System.out.println("activityData processSessionIds"+activityData);
return activityData;
}
private Object checkNull(Object data) {
if(data==null){
return "NA";
}
else
{
return data;
}
}
private Object checkNullDate(Object data) {
if(data==null){
return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
}
else
{
return data;
}
}
public List<LoginTrace> getLogDetails(String userCode, String sessionIds)
{
List<LoginTrace> loginTraceList = null;
try
{
// 1. Get Session object
Session session = HibernateUtil.getSessionFactory(siteTranDB).openSession();
// 2. Create Query
System.out.println("Inside getLogDetails sessionId: [" + sessionIds + "] USER CODE ["+userCode+"]");
Query query = session.createQuery("FROM LoginTrace where userId='" + userCode + "' AND sessionId IN ( " + sessionIds + " ) ");
System.out.println("Inside getLogDetails query: [" + query + "]");
loginTraceList = query.getResultList();
System.out.println("getLogDetails: loginTraceList [" + loginTraceList + "]");
session.close();
}
catch (HibernateException e)
{
System.out.println("HibernateException :");
System.out.println(e.getMessage());
}
return loginTraceList;
}
private List<Employee> getUserDesignation(String userCode)
{
System.out.println("Inside getUserDesignation");
List<Employee> employeeDataList = null;
Employee result = new Employee();
try {
// 1. Get Session object
Session session = HibernateUtil.getSessionFactory(siteTranDB).openSession();
// 2. Create Query
// Query query = session.createQuery("FROM Employee WHERE empCode IN ( "
// + " SELECT empCode FROM UserProfile WHERE userCode='BASE'");
Query query = session.createQuery("FROM Employee e WHERE e.empCode IN ( "
+ " SELECT u.empCode "
+ " FROM UserProfile u "
+ " WHERE u.userCode ='"+userCode+"'"
+ " )");
System.out.println("Inside getLogDetails query: [" + query + "]");
employeeDataList = query.getResultList();
System.out.println("getLogDetails: loginTraceList [" + employeeDataList + "]");
session.close();
} catch (HibernateException e) {
System.out.println("HibernateException :");
System.out.println(e.getMessage());
}
return employeeDataList;
}
public List<String> getUserDetails(String userId, String profileId)
{
List<String> userDetailList = null;
try
{
// 1. Get Session object
System.out.println("Inside getUserDetails userId: [" + userId + "]");
Session session = HibernateUtil.getSessionFactory(siteTranDB).openSession();
// 2. Create Query
Query query = session.createSQLQuery("select trim(CODE) from users where EMP_CODE in (SELECT emp_code FROM employee START WITH emp_code = (SELECT emp_code FROM users WHERE code = '"+userId+"') CONNECT BY prior emp_code = report_to)");
System.out.println("query result>>>>>"+query);
userDetailList = query.getResultList();
System.out.println("query result:::::::"+userDetailList);
System.out.println("query result:::::::"+userDetailList.size());
/* Query query = session.createQuery("FROM UserProfile WHERE empCode IN ( "
+ " SELECT empCode"
+ " FROM Employee START WITH empCode = "
+ " ( SELECT empCode FROM UserProfile "
+ " WHERE userCode='"+userId+"'"
+ " )"
+ " CONNECT BY prior empCode = reportTo ) ");
System.out.println("Inside getUserDetails query: [" + query + "]");
userDetailList = query.getResultList();
System.out.println("getLogDetails: getUserDetails [" + userDetailList + "]"); */
session.close();
}
catch (HibernateException e)
{
System.out.println("HibernateException :");
System.out.println(e.getMessage());
}
System.out.println("userDetailList >>>>>>>>>"+userDetailList);
return userDetailList;
}
public JSONArray processActivityAction(Node activityChildNode, JSONArray eventArray) throws JSONException
{
if( activityChildNode != null )
{
NodeList activityActionNL = activityChildNode.getChildNodes();
int actActionLen = activityActionNL.getLength();
for( int actActionCh = 0; actActionCh < actActionLen; actActionCh++)
{
Node activityActionNode = activityActionNL.item(actActionCh);
if( activityActionNode.getNodeType() == Node.ELEMENT_NODE)
{
String activityActionName = activityActionNode.getNodeName();
//System.out.println("Inside processActivityAction >> "+ activityActionName );
if( "EVENT_ID".equalsIgnoreCase( activityActionName ) )
{
eventArray.put( processEvent(activityActionNode) );
}
}
}
}
return eventArray;
}
public JSONObject processEvent(Node activityActionNode) throws JSONException
{
JSONObject eventObj = new JSONObject();
if( activityActionNode != null )
{
NodeList eventNL = activityActionNode.getChildNodes();
int eventLen = eventNL.getLength();
for( int eventId = 0; eventId < eventLen; eventId++)
{
Node eventChNode = eventNL.item(eventId);
if( eventChNode.getNodeType() == Node.ELEMENT_NODE)
{
String eventChName = eventChNode.getNodeName();
String eventChValue = eventChNode.getFirstChild() != null ? eventChNode.getFirstChild().getNodeValue() : eventChNode.getNodeValue();
//System.out.println("Inside getUserActivityData >1212> "+ eventChNode.getNodeName() );
if( "ACCESS_START_TIME".equalsIgnoreCase( eventChName ) )
{
//System.out.println( new Date (eventChValue));
//System.out.println( eventChName + "[" + eventChValue + "]");
eventObj.put(eventChName, eventChValue);
}
else if( "ACCESS_END_TIME".equalsIgnoreCase( eventChName ) )
{
//System.out.println(eventChName + "[" + eventChValue + "]");
eventObj.put(eventChName, eventChValue);
}
}
}
}
return eventObj;
}
public List<JSONObject> getUserActivityFileData(List<String> users, String fromDate, String toDate) throws IOException, JSONException
{
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("YYYYMMdd");
String today = LocalDate.now().format(formatter);
List<JSONObject> filesArrayList = new ArrayList<JSONObject>();
File userActivityFolder = new File("/home/base/wildfly-10.1.0.Final/server/default/UserActivity");
if( userActivityFolder.isDirectory() )
{
File[] userActivityFiles = userActivityFolder.listFiles(new FileFilter() {
@Override
public boolean accept(File pathname) {
return pathname.getName().endsWith(".txt");
}
});
for(File userActivityFile: userActivityFiles )
{
String fileName = userActivityFile.getName();
//System.out.println("userActivityFile[" + fileName + "]");
fileName = fileName.replace(".txt", "");
//System.out.println("userActivityFile[" + fileName + "]");
String[] fileArr = fileName.split("_");
String userId = ( fileArr.length > 0 ) ? fileArr[0] : "SYSTEM";
String activityDate = ( fileArr.length > 1 ) ? fileArr[1] : today;
System.out.println("userActivityFile[" + userId + "]["+activityDate+"]");
JSONObject fileData = new JSONObject();
fileData.put("userId", userId);
fileData.put("activityDate", activityDate);
if( users == null || ( users != null && users.contains(userId) ) )
{
String fileContents = FileUtils.readFileToString(userActivityFile);
StringBuffer fileContentsBuff = new StringBuffer();
fileContentsBuff.append("<ROOT>");
fileContentsBuff.append(fileContents);
fileContentsBuff.append("</ROOT>");
fileData.put("fileContents", fileContentsBuff.toString());
filesArrayList.add(fileData);
}
System.out.println(fileData.toString().length() + "\n");
}
}
return filesArrayList;
}
}
class ActivityTime implements java.io.Serializable
{
private static final long serialVersionUID = 1L;
long seconds = 0;
long minutes = 0;
long hours = 0;
public ActivityTime()
{
}
public ActivityTime(String startTime, String endTime)
{
SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss.");
Date d1 = null;
Date d2 = null;
try
{
d1 = format.parse(startTime);
d2 = format.parse(endTime);
long diff = d2.getTime() - d1.getTime();
this.seconds = diff / 1000 % 60;
this.minutes = diff / (60 * 1000) % 60;
this.hours = diff / (60 * 60 * 1000);
//System.out.println("diff: " + diff );
}
catch (ParseException e)
{
e.printStackTrace();
}
//System.out.println("Time in : " + this.seconds + " seconds.");
//System.out.println("Time in : " + this.minutes + " minutes.");
//System.out.println("Time in : " + this.hours + " hours.");
}
public ActivityTime(Date startTime, Date endTime)
{
try
{
long diff = endTime.getTime() - startTime.getTime();
this.seconds = diff / 1000 % 60;
this.minutes = diff / (60 * 1000) % 60;
this.hours = diff / (60 * 60 * 1000);
//System.out.println("diff: " + diff );
}
catch (Exception e)
{
e.printStackTrace();
}
//System.out.println("Time in : " + this.seconds + " seconds.");
//System.out.println("Time in : " + this.minutes + " minutes.");
//System.out.println("Time in : " + this.hours + " hours.");
}
public void addTime(ActivityTime time)
{
System.out.println("addTime :1:time[" + time + "]this[" + this + "]" );
this.seconds = this.seconds + time.seconds;
if(this.seconds > 59)
{
this.seconds = this.seconds % 60;
long mins = this.seconds / 60;
this.minutes = this.minutes + mins;
System.out.println("this.seconds > 59 ::" + this.seconds );
}
this.minutes = this.minutes + time.minutes;
if(this.minutes > 59)
{
this.minutes = this.minutes % 60;
long hrs = this.minutes / 60;
this.hours = this.hours + hrs;
System.out.println("this.minutes > 59 ::" + this.minutes );
}
this.hours = this.hours + time.hours;
if(this.hours >= 23) //Should not come here
{
System.out.println("this.hours >= 23 ::" + this.hours );
}
System.out.println("addTime :2:time[" + time + "]this[" + this + "]" );
}
public JSONObject toJSON()
{
JSONObject jObj = new JSONObject();
try
{
jObj.put("hours", this.hours);
jObj.put("minutes", this.minutes);
jObj.put("seconds", this.seconds);
}
catch (JSONException e)
{
e.printStackTrace();
}
return jObj;
}
public String toString()
{
return this.toJSON().toString();
}
}
// select designation from employee where emp_code in(SELECT emp_code FROM USERS
// WHERE CODE='BASE');
// http://192.168.0.220:9090/ibase/plugin/api/logintrace/6DBC5A495F0F2C5371D59DC89EB06F41
package ibase.dashboard.common.hibernate.utility;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import org.hibernate.HibernateException;
import org.hibernate.SessionFactory;
import org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
//import org.hibernate.cfg.Configuration;
//import org.hibernate.service.ServiceRegistry;
public class HibernateUtil {
//private static final SessionFactory sessionFactory = buildSessionFactory();
private static final SessionFactory sessionFactory;
//private static SessionFactory buildSessionFactory()
static
{
try
{
/*
// For Hibernate 4.x
// 1. configuring hibernate
Configuration configuration = new Configuration().configure("resource/hibernate.cfg.xml");
// 2. create sessionfactory
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry);
// Create the SessionFactory from hibernate.cfg.xml
return sessionFactory;
*/
// For Hibernate 5.x
// 1. configuring hibernate
StandardServiceRegistry standardRegistry = new StandardServiceRegistryBuilder().configure("resource/hibernate.cfg.xml").build();
// 2. create sessionfactory
Metadata metaData = new MetadataSources(standardRegistry).getMetadataBuilder().build();
sessionFactory = metaData.getSessionFactoryBuilder().build();
}
catch (Throwable ex)
{
// Make sure you log the exception, as it might be swallowed
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory()
{
return sessionFactory;
}
public static void shutdown()
{
// Close caches and connection pools
getSessionFactory().close();
}
private static final Map<String, SessionFactory> sessionFactories = new HashMap<String, SessionFactory>();
private static SessionFactory buildSessionFactory(String dbName)
{
try
{
/*
// For Hibernate 4.x
// 1. configuring hibernate
Configuration configuration = new Configuration().configure("hibernate.cfg.xml");
// 2. create sessionfactory
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry);
*/
// For Hibernate 5.x
// 1. configuring hibernate
StandardServiceRegistry standardRegistry = new StandardServiceRegistryBuilder().configure("resource/hibernate.cfg.xml").build();
// 2. create sessionfactory
Metadata metaData = new MetadataSources(standardRegistry).getMetadataBuilder().build();
SessionFactory sessionFactory = metaData.getSessionFactoryBuilder().build();
sessionFactories.put(dbName,sessionFactory);
// Create the SessionFactory from hibernate.cfg.xml
return sessionFactory;
}
catch (final HibernateException e)
{
// Make sure you log the exception, as it might be swallowed
System.err.println("Initial SessionFactory creation failed." + e);
e.printStackTrace();
throw new ExceptionInInitializerError(e);
}
catch (Throwable ex)
{
// Make sure you log the exception, as it might be swallowed
System.err.println("Initial SessionFactory creation failed." + ex);
ex.printStackTrace();
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory(String dbName)
{
if( "DEFAULT".equalsIgnoreCase(dbName) )
{
return getSessionFactory();
}
else
{
SessionFactory _sessionFactory = sessionFactories.get(dbName);
if( _sessionFactory == null )
{
_sessionFactory = buildSessionFactory(dbName);
}
return _sessionFactory;
}
}
public static void shutdown(String dbName)
{
// Close caches and connection pools
getSessionFactory(dbName).close();
}
public static String DB_DATE_FORMAT = "yyyy-MM-dd";
public static String APPL_DATE_FORMAT = "dd/MM/yyyy";
//Get Date object in Provided Format
public static Date getDateObject(String dateStr, String dateFormat)
{
Date dateObj = null;
SimpleDateFormat simpleDateFormat = null;
try
{
simpleDateFormat = new SimpleDateFormat(dateFormat);
dateObj = simpleDateFormat.parse(dateStr);
}
catch(Exception e)
{
System.out.println("Exception :GenericUtility :getDateObject :==>\n"+e.getMessage());
e.printStackTrace();
}
return dateObj;
}
//While Sending date to Client End
//Get formatted Date String DB to APPL format
public static String getValidDB2APPLDate(String dateStr)
{
return getValidDateString(dateStr, DB_DATE_FORMAT, APPL_DATE_FORMAT);
}
//While inserting / updating date to Database
//Get formatted Date String APPL to DB format
public static String getValidAPPL2DBDate(String dateStr)
{
return getValidDateString(dateStr, APPL_DATE_FORMAT, DB_DATE_FORMAT);
}
private static String getValidDateString(String dateStr, String sourceDateFormat, String targetDateFormat)
{
Object date = null;
SimpleDateFormat sdfOutput = null;
String retDateStr = "";
try
{
if (!(sourceDateFormat.equalsIgnoreCase(targetDateFormat)))
{
if (sourceDateFormat.indexOf("/") != -1)
{
dateStr.replace('/', '-');
}
else if (sourceDateFormat.indexOf(".") != -1)
{
dateStr.replace('.', '-');
}
date = new SimpleDateFormat(sourceDateFormat).parse(dateStr);
sdfOutput = new SimpleDateFormat(targetDateFormat);
retDateStr = sdfOutput.format(date);
}
else
{
retDateStr = dateStr;
}
}
catch (Exception e)
{
System.out.println("Exception :GenericUtility :getValidDateString :==>"+e.getMessage());
e.printStackTrace();
}
return retDateStr;
}
}
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd" >
<hibernate-configuration>
<session-factory>
<!-- Database connection settings -->
<property name="hibernate.connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<!-- Datasource for Hibernate Connection -->
<property name="hibernate.connection.datasource">java:/OracleDS</property>
<property name="hibernate.cache.use_query_cache">false</property>
<!-- Echo all executed SQL to sysout -->
<property name="show_sql">true</property>
<!-- Drop and re-create the database schema on startup -->
<!-- <property name="hibernate.hbm2ddl.auto">update</property> -->
<!-- Map Entity Class -->
<mapping class="ibase.dashboard.hibernate.bean.DocContents"></mapping>
<mapping class="ibase.dashboard.hibernate.bean.DocTransLink"></mapping>
<mapping class="ibase.dashboard.hibernate.bean.RefSer"></mapping>
<mapping class="ibase.dashboard.hibernate.bean.UserDocContent"></mapping>
<mapping class="ibase.dashboard.hibernate.bean.Task"></mapping>
<mapping class="ibase.dashboard.hibernate.bean.LoginTrace"></mapping>
<mapping class="ibase.dashboard.hibernate.bean.Employee"></mapping>
<mapping class="ibase.dashboard.hibernate.bean.UserProfile"></mapping>
</session-factory>
</hibernate-configuration>
package ibase.dashboard.common.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.json.JSONException;
import org.json.JSONObject;
public class BBAccountActivityPluginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
{
try
{
JSONObject jsonObject = new JSONObject();
jsonObject.put("bbAccountActivityPluginTag", "<bb-account-activity-plugin></bb-account-activity-plugin>");
resp.setContentType( "application/json" );
PrintWriter pw = resp.getWriter();
pw.write(jsonObject.toString());
pw.flush();
}
catch (JSONException e)
{
System.out.println("BBAccountActivityPluginServlet JSONException [" + e.getMessage() + "]");
e.printStackTrace();
}
catch (Exception e)
{
System.out.println("BBAccountActivityPluginServlet Exception [" + e.getMessage() + "]");
e.printStackTrace();
}
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
{
doPost(req, resp);
}
}
package ibase.dashboard.common.webService;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import ibase.dashboard.common.hibernate.dao.AccountActivityDao;
import ibase.utility.BaseException;
import ibase.utility.UserInfoBean;
@Path("/accountActivity")
public class AccountActivityService {
@Context
HttpServletRequest request; // The proxy of Request will be injected into this singleton
private AccountActivityDao accountActivityDao = new AccountActivityDao();
@GET
@Path("/")
@Produces(MediaType.APPLICATION_JSON)
public String getLog() throws Exception {
HttpSession session = request.getSession();
Object userObj = session.getAttribute( "USER_INFO" );
String userId = "" ;
String profileId="";
System.out.println(" userObj >>[" + userObj + "]" );
if(userObj != null)
{
UserInfoBean userInfo;
try {
userInfo = new UserInfoBean( userObj.toString() );
userId = userInfo.getLoginCode();
profileId = userInfo.getProfileId();
System.out.println(" userInfo >>[" + userId + "] profile Id ["+profileId+"]" );
} catch (BaseException e) {
e.printStackTrace();
}
}
String logDetails = accountActivityDao. getUserActivityData(userId,profileId);
return logDetails;
}
}
\ No newline at end of file
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