ranger-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From omal...@apache.org
Subject [23/44] ARGUS-1. Initial code commit (Selvamohan Neethiraj via omalley)
Date Thu, 14 Aug 2014 20:50:34 GMT
http://git-wip-us.apache.org/repos/asf/incubator-argus/blob/7defc061/security-admin/src/main/java/com/xasecure/security/web/authentication/XAAuthenticationEntryPoint.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/security/web/authentication/XAAuthenticationEntryPoint.java b/security-admin/src/main/java/com/xasecure/security/web/authentication/XAAuthenticationEntryPoint.java
new file mode 100644
index 0000000..beab7ee
--- /dev/null
+++ b/security-admin/src/main/java/com/xasecure/security/web/authentication/XAAuthenticationEntryPoint.java
@@ -0,0 +1,88 @@
+/**
+ *
+ */
+package com.xasecure.security.web.authentication;
+
+import java.io.IOException;
+
+import javax.servlet.ServletException;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import com.xasecure.common.JSONUtil;
+import com.xasecure.common.PropertiesUtil;
+import com.xasecure.common.XAConfigUtil;
+import com.xasecure.view.VXResponse;
+
+import org.apache.log4j.Logger;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.security.core.AuthenticationException;
+import org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint;
+
+
+/**
+ * 
+ *
+ */
+public class XAAuthenticationEntryPoint extends
+LoginUrlAuthenticationEntryPoint {
+    static Logger logger = Logger.getLogger(XAAuthenticationEntryPoint.class);
+    static int ajaxReturnCode = -1;
+    
+    @Autowired
+    XAConfigUtil configUtil;
+    
+    @Autowired
+    JSONUtil jsonUtil;
+
+    public XAAuthenticationEntryPoint() {
+	super();
+	if (logger.isDebugEnabled()) {
+	    logger.debug("AjaxAwareAuthenticationEntryPoint(): constructor");
+	}
+
+	if (ajaxReturnCode < 0) {
+	    ajaxReturnCode = PropertiesUtil.getIntProperty(
+		    "xa.ajax.auth.required.code", 401);
+	}
+    }
+
+    @Override
+    public void commence(HttpServletRequest request,
+	    HttpServletResponse response, AuthenticationException authException)
+    throws IOException, ServletException {
+	String ajaxRequestHeader = request.getHeader("X-Requested-With");
+	if (logger.isDebugEnabled()) {
+	    logger.debug("commence() X-Requested-With=" + ajaxRequestHeader);
+	}
+
+	String requestURL = (request.getRequestURL() != null) ? request.getRequestURL().toString() : "";
+	String servletPath = PropertiesUtil.getProperty("xa.servlet.mapping.url.pattern", "service");
+	String reqServletPath = configUtil.getWebAppRootURL() + "/" + servletPath;
+
+	response.setContentType("application/json;charset=UTF-8");
+	response.setHeader("Cache-Control", "no-cache");
+	try {
+
+		VXResponse vXResponse = new VXResponse();
+
+		vXResponse.setStatusCode(HttpServletResponse.SC_UNAUTHORIZED);
+		vXResponse.setMsgDesc("Authentication Failed");
+
+		response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
+		response.getWriter().write(jsonUtil.writeObjectAsString(vXResponse));
+	} catch (IOException e) {
+		logger.info("Error while writing JSON in HttpServletResponse");
+	}
+	
+	if (ajaxRequestHeader != null && ajaxRequestHeader.equalsIgnoreCase("XMLHttpRequest")) {
+	    if (logger.isDebugEnabled()) {
+		logger.debug("commence() AJAX request. Authentication required. Returning "
+			+ ajaxReturnCode + ". URL=" + request.getRequestURI());
+	    }
+    	response.sendError(ajaxReturnCode, "");
+	} else if(!(requestURL.startsWith(reqServletPath))) {
+		super.commence(request, response, authException);
+	}
+    }
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-argus/blob/7defc061/security-admin/src/main/java/com/xasecure/security/web/filter/MyRememberMeFilter.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/security/web/filter/MyRememberMeFilter.java b/security-admin/src/main/java/com/xasecure/security/web/filter/MyRememberMeFilter.java
new file mode 100644
index 0000000..db6a68e
--- /dev/null
+++ b/security-admin/src/main/java/com/xasecure/security/web/filter/MyRememberMeFilter.java
@@ -0,0 +1,165 @@
+/**
+ *
+ */
+package com.xasecure.security.web.filter;
+
+import java.io.IOException;
+
+import javax.servlet.FilterChain;
+import javax.servlet.ServletException;
+import javax.servlet.ServletRequest;
+import javax.servlet.ServletResponse;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import org.apache.log4j.Logger;
+import org.springframework.context.ApplicationEventPublisher;
+import org.springframework.security.authentication.AuthenticationManager;
+import org.springframework.security.core.Authentication;
+import org.springframework.security.core.AuthenticationException;
+import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
+import org.springframework.security.web.authentication.RememberMeServices;
+import org.springframework.security.web.authentication.rememberme.RememberMeAuthenticationFilter;
+
+/**
+ * 
+ *
+ */
+@SuppressWarnings("deprecation")
+public class MyRememberMeFilter extends RememberMeAuthenticationFilter {
+
+    static Logger logger = Logger.getLogger(MyRememberMeFilter.class);
+
+    /*
+     * (non-Javadoc)
+     *
+     * @see org.springframework.security.web.authentication.rememberme.
+     * RememberMeAuthenticationFilter#afterPropertiesSet()
+     */
+    @Override
+    public void afterPropertiesSet() {
+	// TODO Auto-generated method stub
+	super.afterPropertiesSet();
+    }
+
+    /*
+     * (non-Javadoc)
+     *
+     * @see org.springframework.security.web.authentication.rememberme.
+     * RememberMeAuthenticationFilter#doFilter(javax.servlet.ServletRequest,
+     * javax.servlet.ServletResponse, javax.servlet.FilterChain)
+     */
+    @Override
+    public void doFilter(ServletRequest arg0, ServletResponse arg1,
+	    FilterChain arg2) throws IOException, ServletException {
+	// TODO Auto-generated method stub
+	super.doFilter(arg0, arg1, arg2);
+    }
+
+    /*
+     * (non-Javadoc)
+     *
+     * @see org.springframework.security.web.authentication.rememberme.
+     * RememberMeAuthenticationFilter#getRememberMeServices()
+     */
+    @Override
+    public RememberMeServices getRememberMeServices() {
+	// TODO Auto-generated method stub
+	return super.getRememberMeServices();
+    }
+
+    /*
+     * (non-Javadoc)
+     *
+     * @see org.springframework.security.web.authentication.rememberme.
+     * RememberMeAuthenticationFilter
+     * #onSuccessfulAuthentication(javax.servlet.http.HttpServletRequest,
+     * javax.servlet.http.HttpServletResponse,
+     * org.springframework.security.core.Authentication)
+     */
+    @Override
+    protected void onSuccessfulAuthentication(HttpServletRequest request,
+	    HttpServletResponse response, Authentication authResult) {
+	super.onSuccessfulAuthentication(request, response, authResult);
+	// if (logger.isDebugEnabled()) {
+	logger.info("onSuccessfulAuthentication() authResult=" + authResult);
+	// }
+    }
+
+    /*
+     * (non-Javadoc)
+     *
+     * @see org.springframework.security.web.authentication.rememberme.
+     * RememberMeAuthenticationFilter
+     * #onUnsuccessfulAuthentication(javax.servlet.http.HttpServletRequest,
+     * javax.servlet.http.HttpServletResponse,
+     * org.springframework.security.core.AuthenticationException)
+     */
+    @Override
+    protected void onUnsuccessfulAuthentication(HttpServletRequest request,
+	    HttpServletResponse response, AuthenticationException failed) {
+	logger.error("Authentication failure. failed=" + failed,
+		new Throwable());
+	super.onUnsuccessfulAuthentication(request, response, failed);
+    }
+
+    /*
+     * (non-Javadoc)
+     *
+     * @see org.springframework.security.web.authentication.rememberme.
+     * RememberMeAuthenticationFilter
+     * #setApplicationEventPublisher(org.springframework
+     * .context.ApplicationEventPublisher)
+     */
+    @Override
+    public void setApplicationEventPublisher(
+	    ApplicationEventPublisher eventPublisher) {
+	// TODO Auto-generated method stub
+	super.setApplicationEventPublisher(eventPublisher);
+    }
+
+    /*
+     * (non-Javadoc)
+     *
+     * @see org.springframework.security.web.authentication.rememberme.
+     * RememberMeAuthenticationFilter
+     * #setAuthenticationManager(org.springframework
+     * .security.authentication.AuthenticationManager)
+     */
+    @Override
+    public void setAuthenticationManager(
+	    AuthenticationManager authenticationManager) {
+	// TODO Auto-generated method stub
+	super.setAuthenticationManager(authenticationManager);
+    }
+
+    /*
+     * (non-Javadoc)
+     *
+     * @see org.springframework.security.web.authentication.rememberme.
+     * RememberMeAuthenticationFilter
+     * #setAuthenticationSuccessHandler(org.springframework
+     * .security.web.authentication.AuthenticationSuccessHandler)
+     */
+    @Override
+    public void setAuthenticationSuccessHandler(
+	    AuthenticationSuccessHandler successHandler) {
+	// TODO Auto-generated method stub
+	super.setAuthenticationSuccessHandler(successHandler);
+    }
+
+    /*
+     * (non-Javadoc)
+     *
+     * @see org.springframework.security.web.authentication.rememberme.
+     * RememberMeAuthenticationFilter
+     * #setRememberMeServices(org.springframework.security
+     * .web.authentication.RememberMeServices)
+     */
+    @Override
+    public void setRememberMeServices(RememberMeServices rememberMeServices) {
+	// TODO Auto-generated method stub
+	super.setRememberMeServices(rememberMeServices);
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-argus/blob/7defc061/security-admin/src/main/java/com/xasecure/security/web/filter/XASecurityContextFormationFilter.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/security/web/filter/XASecurityContextFormationFilter.java b/security-admin/src/main/java/com/xasecure/security/web/filter/XASecurityContextFormationFilter.java
new file mode 100644
index 0000000..1e40b0f
--- /dev/null
+++ b/security-admin/src/main/java/com/xasecure/security/web/filter/XASecurityContextFormationFilter.java
@@ -0,0 +1,122 @@
+/**
+ *
+ */
+package com.xasecure.security.web.filter;
+
+import java.io.IOException;
+
+import javax.servlet.FilterChain;
+import javax.servlet.ServletException;
+import javax.servlet.ServletRequest;
+import javax.servlet.ServletResponse;
+import javax.servlet.http.Cookie;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import javax.servlet.http.HttpSession;
+
+import com.xasecure.biz.SessionMgr;
+import com.xasecure.common.GUIDUtil;
+import com.xasecure.common.HTTPUtil;
+import com.xasecure.common.PropertiesUtil;
+import com.xasecure.common.RequestContext;
+import com.xasecure.common.UserSessionBase;
+import com.xasecure.entity.XXAuthSession;
+import com.xasecure.util.RestUtil;
+
+import org.apache.log4j.Logger;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.security.authentication.AnonymousAuthenticationToken;
+import org.springframework.security.core.Authentication;
+import org.springframework.security.core.context.SecurityContextHolder;
+import org.springframework.web.filter.GenericFilterBean;
+
+import com.xasecure.security.context.XAContextHolder;
+import com.xasecure.security.context.XASecurityContext;
+
+public class XASecurityContextFormationFilter extends GenericFilterBean {
+
+	static Logger logger = Logger
+			.getLogger(XASecurityContextFormationFilter.class);
+
+	public static final String AKA_SC_SESSION_KEY = "AKA_SECURITY_CONTEXT";
+	public static final String USER_AGENT = "User-Agent";
+
+	@Autowired
+	SessionMgr sessionMgr;
+
+	@Autowired
+	HTTPUtil httpUtil;
+
+	String testIP = null;
+
+	public XASecurityContextFormationFilter() {
+		testIP = PropertiesUtil.getProperty("xa.env.ip");
+	}
+
+	/*
+	 * (non-Javadoc)
+	 * 
+	 * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest,
+	 * javax.servlet.ServletResponse, javax.servlet.FilterChain)
+	 */
+	@Override
+	public void doFilter(ServletRequest request, ServletResponse response,
+			FilterChain chain) throws IOException, ServletException {
+		
+		try {
+			Authentication auth = SecurityContextHolder.getContext()
+					.getAuthentication();
+
+			if (auth instanceof AnonymousAuthenticationToken) {
+				// ignore
+			} else {
+				HttpServletRequest httpRequest = (HttpServletRequest) request;
+				HttpSession httpSession = httpRequest.getSession(false);
+
+				// [1]get the context from session
+				XASecurityContext context = (XASecurityContext) httpSession.getAttribute(AKA_SC_SESSION_KEY);
+				int clientTimeOffset = 0;
+				if (context == null) {
+					context = new XASecurityContext();
+					httpSession.setAttribute(AKA_SC_SESSION_KEY, context);					
+				}
+				String userAgent = httpRequest.getHeader(USER_AGENT);
+				if(httpRequest!=null){						
+					clientTimeOffset=RestUtil.getTimeOffset(httpRequest);	
+					
+				}
+				// Get the request specific info
+				RequestContext requestContext = new RequestContext();
+				String reqIP = testIP;
+				if (testIP == null) {
+					reqIP = httpRequest.getRemoteAddr();
+				}
+				requestContext.setIpAddress(reqIP);
+				requestContext.setUserAgent(userAgent);
+				requestContext.setDeviceType(httpUtil
+						.getDeviceType(httpRequest));
+				requestContext.setServerRequestId(GUIDUtil.genGUI());
+				requestContext.setRequestURL(httpRequest.getRequestURI());				
+										
+				requestContext.setClientTimeOffsetInMinute(clientTimeOffset);
+				context.setRequestContext(requestContext);			
+
+				XAContextHolder.setSecurityContext(context);
+
+				UserSessionBase userSession = sessionMgr.processSuccessLogin(
+						XXAuthSession.AUTH_TYPE_PASSWORD, userAgent);
+				
+				if(userSession!=null && userSession.getClientTimeOffsetInMinute()==0){
+					userSession.setClientTimeOffsetInMinute(clientTimeOffset);
+				}
+				
+				context.setUserSession(userSession);
+			}
+			chain.doFilter(request, response);
+
+		} finally {
+			// [4]remove context from thread-local
+			XAContextHolder.resetSecurityContext();
+		}
+	}
+}

http://git-wip-us.apache.org/repos/asf/incubator-argus/blob/7defc061/security-admin/src/main/java/com/xasecure/security/web/filter/XAUsernamePasswordAuthenticationFilter.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/security/web/filter/XAUsernamePasswordAuthenticationFilter.java b/security-admin/src/main/java/com/xasecure/security/web/filter/XAUsernamePasswordAuthenticationFilter.java
new file mode 100644
index 0000000..23a2c3c
--- /dev/null
+++ b/security-admin/src/main/java/com/xasecure/security/web/filter/XAUsernamePasswordAuthenticationFilter.java
@@ -0,0 +1,33 @@
+/**
+ *
+ */
+package com.xasecure.security.web.filter;
+
+import org.apache.log4j.Logger;
+import org.springframework.security.web.authentication.RememberMeServices;
+import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
+
+public class XAUsernamePasswordAuthenticationFilter extends
+	UsernamePasswordAuthenticationFilter {
+
+    static Logger logger = Logger
+	    .getLogger(XAUsernamePasswordAuthenticationFilter.class);
+
+    /*
+     * (non-Javadoc)
+     *
+     * @see org.springframework.security.web.authentication.
+     * AbstractAuthenticationProcessingFilter
+     * #setRememberMeServices(org.springframework
+     * .security.web.authentication.RememberMeServices)
+     */
+    @Override
+    public void setRememberMeServices(RememberMeServices rememberMeServices) {
+	if (logger.isDebugEnabled()) {
+	    logger.debug("setRememberMeServices() enter: rememberMeServices="
+		    + rememberMeServices.toString());
+	}
+	super.setRememberMeServices(rememberMeServices);
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-argus/blob/7defc061/security-admin/src/main/java/com/xasecure/service/AbstractBaseResourceService.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/service/AbstractBaseResourceService.java b/security-admin/src/main/java/com/xasecure/service/AbstractBaseResourceService.java
new file mode 100644
index 0000000..e0d1bd2
--- /dev/null
+++ b/security-admin/src/main/java/com/xasecure/service/AbstractBaseResourceService.java
@@ -0,0 +1,852 @@
+package com.xasecure.service;
+
+import java.lang.reflect.ParameterizedType;
+import java.lang.reflect.TypeVariable;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import javax.persistence.EntityManager;
+import javax.persistence.Query;
+import javax.persistence.TypedQuery;
+import javax.persistence.criteria.CriteriaBuilder;
+import javax.persistence.criteria.CriteriaQuery;
+import javax.persistence.criteria.Expression;
+import javax.persistence.criteria.Path;
+import javax.persistence.criteria.Predicate;
+import javax.persistence.criteria.Root;
+
+import com.xasecure.biz.XABizUtil;
+import com.xasecure.common.ContextUtil;
+import com.xasecure.common.DateUtil;
+import com.xasecure.common.UserSessionBase;
+import com.xasecure.common.XAConfigUtil;
+import com.xasecure.common.MessageEnums;
+import com.xasecure.common.RESTErrorUtil;
+import com.xasecure.common.SearchCriteria;
+import com.xasecure.common.SearchField;
+import com.xasecure.common.SearchUtil;
+import com.xasecure.common.SortField;
+import com.xasecure.common.StringUtil;
+import com.xasecure.common.db.BaseDao;
+import com.xasecure.common.view.VList;
+import com.xasecure.db.XADaoManager;
+import com.xasecure.entity.XXAuthSession;
+import com.xasecure.entity.XXDBBase;
+import com.xasecure.entity.XXPortalUser;
+import com.xasecure.view.VXDataObject;
+import com.xasecure.view.VXLong;
+
+import org.apache.log4j.Logger;
+import org.springframework.beans.factory.annotation.Autowired;
+
+import com.xasecure.security.handler.XADomainObjectSecurityHandler;
+import com.xasecure.security.handler.Permission;
+
+public abstract class AbstractBaseResourceService<T extends XXDBBase, V extends VXDataObject> {
+
+	public static final Logger logger = Logger
+			.getLogger(AbstractBaseResourceService.class);
+
+	public static final int OPERATION_CREATE_CONTEXT = 1;
+	public static final int OPERATION_UPDATE_CONTEXT = 2;
+
+	static HashMap<Integer, AbstractBaseResourceService<?, ?>> serviceList = new HashMap<Integer, AbstractBaseResourceService<?, ?>>();
+	static List<AbstractBaseResourceService<?, ?>> preServiceList = new ArrayList<AbstractBaseResourceService<?, ?>>();
+	protected Class<T> tEntityClass;
+	protected Class<V> tViewClass;
+
+	protected String className;
+	protected String viewClassName;
+	protected String countQueryStr;
+	protected String queryStr;
+	protected final String distinctCountQueryStr;
+	protected final String distinctQueryStr;
+
+	public List<SortField> sortFields = new ArrayList<SortField>();
+	public List<SearchField> searchFields = new ArrayList<SearchField>();
+
+	@Autowired
+	XADaoManager daoManager;
+
+	protected static final HashMap<Class<?>, String> tEntityValueMap = new HashMap<Class<?>, String>();
+	static {
+		tEntityValueMap.put(XXAuthSession.class, "Auth Session");
+		tEntityValueMap.put(XXDBBase.class, "Base");
+	}
+
+	BaseDao<T> entityDao;
+
+	@Autowired
+	StringUtil stringUtil;
+
+	@Autowired
+	protected XADaoManager daoMgr;
+
+	@Autowired
+	protected SearchUtil searchUtil;
+
+	@Autowired
+	protected RESTErrorUtil restErrorUtil;
+
+	@Autowired
+	XADomainObjectSecurityHandler objectSecurityHandler;
+
+	@Autowired
+	XABizUtil bizUtil;
+
+	@Autowired
+	XAConfigUtil msConfigUtil;
+
+	protected abstract void validateForCreate(V viewBaseBean);
+
+	protected abstract void validateForUpdate(V viewBaseBean, T t);
+
+	protected abstract T mapViewToEntityBean(V viewBean, T t,
+			int OPERATION_CONTEXT);
+
+	protected abstract V mapEntityToViewBean(V viewBean, T t);
+
+	public static void registerService(
+			AbstractBaseResourceService<?, ?> baseService) {
+		preServiceList.add(baseService);
+	}
+
+	static public AbstractBaseResourceService<?, ?> getService(int classType) {
+		AbstractBaseResourceService<?, ?> service = serviceList.get(classType);
+		if (service == null) {
+			for (AbstractBaseResourceService<?, ?> myService : preServiceList) {
+				if (myService.getClassType() == classType) {
+					serviceList.put(myService.getClassType(), myService);
+					service = myService;
+					break;
+				}
+			}
+		}
+
+		if (service == null) {
+			logger.error("Service not found for classType=" + classType,
+					new Throwable());
+		}
+		return service;
+	}
+
+	protected String getResourceName() {
+
+		String resourceName = tEntityValueMap.get(tEntityClass);
+		if (resourceName == null || resourceName.isEmpty()) {
+			resourceName = "Object";
+		}
+		return resourceName;
+
+		// if (className.startsWith("M")) {
+		// return className.substring(1);
+		// } else if (className.startsWith("com.xasecure.entity.M")){
+		// return className.substring(14);
+		// }
+		// return className;
+	}
+
+	@SuppressWarnings("unchecked")
+	protected BaseDao<T> getDao() {
+		if (entityDao == null) {
+			entityDao = (BaseDao<T>) daoMgr.getDaoForClassName(tEntityClass
+					.getSimpleName());
+
+		}
+		return entityDao;
+	}
+
+	protected T createEntityObject() {
+		try {
+			return tEntityClass.newInstance();
+		} catch (Throwable e) {
+			logger.error("Error instantiating entity class. tEntityClass="
+					+ tEntityClass.toString(), e);
+		}
+		return null;
+	}
+
+	protected V createViewObject() {
+		try {
+			return tViewClass.newInstance();
+		} catch (Throwable e) {
+			logger.error("Error instantiating view class. tViewClass="
+					+ tViewClass.toString(), e);
+		}
+		return null;
+	}
+
+	protected int getClassType() {
+		return bizUtil.getClassType(tEntityClass);
+	}
+
+	protected int ownerRatingWeight;
+
+	/**
+	 * constructor
+	 */
+	@SuppressWarnings("unchecked")
+	public AbstractBaseResourceService() {
+
+		Class klass = getClass();
+		ParameterizedType genericSuperclass = (ParameterizedType) klass
+				.getGenericSuperclass();
+		TypeVariable<Class<?>> var[] = klass.getTypeParameters();
+
+		if (genericSuperclass.getActualTypeArguments()[0] instanceof Class) {
+			tEntityClass = (Class<T>) genericSuperclass
+					.getActualTypeArguments()[0];
+			tViewClass = (Class<V>) genericSuperclass.getActualTypeArguments()[1];
+		} else if (var.length > 0) {
+			tEntityClass = (Class<T>) var[0].getBounds()[0];
+			tViewClass = (Class<V>) var[1].getBounds()[0];
+		} else {
+			logger.fatal("Cannot find class for template", new Throwable());
+		}
+		if (tEntityClass != null) {
+			className = tEntityClass.getName();
+		}
+		if (tViewClass != null) {
+			viewClassName = tViewClass.getName();
+		}
+
+		// Get total count of the rows which meet the search criteria
+		countQueryStr = "SELECT COUNT(obj) FROM " + tEntityClass.getName()
+				+ " obj ";
+		queryStr = "SELECT obj FROM " + className + " obj ";
+
+		distinctCountQueryStr = "SELECT COUNT(distinct obj.id) FROM "
+				+ tEntityClass.getName() + " obj ";
+		distinctQueryStr = "SELECT distinct obj FROM " + className + " obj ";
+
+		registerService(this);
+	}
+
+	// ----------------------------------------------------------------------------------
+	// Create Operation
+	// ----------------------------------------------------------------------------------
+	/**
+	 * Create Entity object and populate it from view object. Used in create
+	 * operation
+	 */
+
+	protected void mapBaseAttributesToEntityBean(T resource, V viewBean) {
+		if (resource.getCreateTime() == null) {
+			resource.setCreateTime(DateUtil.getUTCDate());
+		}
+
+		resource.setUpdateTime(DateUtil.getUTCDate());
+
+		if (resource.getAddedByUserId() == null) {
+			resource.setAddedByUserId(ContextUtil.getCurrentUserId());
+		}
+
+		resource.setUpdatedByUserId(ContextUtil.getCurrentUserId());
+	}
+
+	protected T populateEntityBeanForCreate(T t, V viewBaseBean) {
+		mapBaseAttributesToEntityBean(t, viewBaseBean);
+		return mapViewToEntityBean(viewBaseBean, t, OPERATION_CREATE_CONTEXT);
+	}
+
+	protected T preCreate(V viewBaseBean) {
+		validateGenericAttributes(viewBaseBean);
+		validateForCreate(viewBaseBean);
+
+		T t = createEntityObject();
+		t = populateEntityBeanForCreate(t, viewBaseBean);
+		return t;
+	}
+
+	public V createResource(V viewBaseBean) {
+		T resource = preCreate(viewBaseBean);
+
+		// object security
+		if (!objectSecurityHandler.hasAccess(resource,
+				Permission.permissionType.CREATE)) {
+			throw restErrorUtil.create403RESTException(getResourceName()
+					+ " access denied. classType=" + resource.getMyClassType()
+					+ ", className=" + resource.getClass().getName()
+					+ ", objectId=" + resource.getId());
+		}
+
+		bizUtil.updateCloneReferences(resource);
+
+		resource = getDao().create(resource);
+
+		V view = postCreate(resource);
+		return view;
+	}
+
+	protected V postCreate(T resource) {
+		V view = populateViewBean(resource);
+		return view;
+	}
+
+	// ----------------------------------------------------------------------------------
+	// Read Operation
+	// ----------------------------------------------------------------------------------
+
+	protected T preRead(Long id) {
+		return null;
+	}
+
+	public V readResource(Long id) {
+		// T resource = preRead(id);
+
+		T resource = getDao().getById(id);
+		if (resource == null) {
+			// Returns code 400 with DATA_NOT_FOUND as the error message
+			throw restErrorUtil.createRESTException(getResourceName()
+					+ " not found", MessageEnums.DATA_NOT_FOUND, id, null,
+					"preRead: " + id + " not found.");
+		}
+
+		V viewBean = readResource(resource);
+		return viewBean;
+	}
+
+	/**
+	 * @param resource
+	 * @return
+	 */
+	@SuppressWarnings("unchecked")
+	private V readResource(T resource) {
+		// object security
+		if (!objectSecurityHandler.hasAccess(resource,
+				Permission.permissionType.READ)) {
+
+			throw restErrorUtil.create403RESTException(getResourceName()
+					+ " access denied. classType=" + resource.getMyClassType()
+					+ ", className=" + resource.getClass().getName()
+					+ ", objectId=" + resource.getId() + ", object="
+					+ resource.toString());
+		}
+
+		V viewBean = postRead(resource);
+		return viewBean;
+	}
+
+	protected V postRead(T resource) {
+		V viewBean = populateViewBean(resource);
+		return viewBean;
+	}
+
+	// ----------------------------------------------------------------------------------
+	// Update Operation
+	// ----------------------------------------------------------------------------------
+
+	/**
+	 * Populate Entity object from view object. Used in update operation
+	 */
+	protected T populateEntityBeanForUpdate(T t, V viewBaseBean) {
+		mapBaseAttributesToEntityBean(t, viewBaseBean);
+		return mapViewToEntityBean(viewBaseBean, t, OPERATION_UPDATE_CONTEXT);
+	}
+
+	protected T preUpdate(V viewBaseBean) {
+		T resource = getDao().getById(viewBaseBean.getId());
+		if (resource == null) {
+			// Returns code 400 with DATA_NOT_FOUND as the error message
+			throw restErrorUtil.createRESTException(getResourceName()
+					+ " not found", MessageEnums.DATA_NOT_FOUND,
+					viewBaseBean.getId(), null, "preUpdate: id not found.");
+		}
+		validateForUpdate(viewBaseBean, resource);
+
+		return populateEntityBeanForUpdate(resource, viewBaseBean);
+	}
+
+	public V updateResource(V viewBaseBean) {
+		T resource = preUpdate(viewBaseBean);
+
+		// object security
+		if (!objectSecurityHandler.hasAccess(resource,
+				Permission.permissionType.UPDATE)) {
+			throw restErrorUtil.create403RESTException(getResourceName()
+					+ " access denied. classType=" + resource.getMyClassType()
+					+ ", className=" + resource.getClass().getName()
+					+ ", objectId=" + resource.getId());
+		}
+
+		resource = getDao().update(resource);
+		V viewBean = postUpdate(resource);
+		return viewBean;
+	}
+
+	protected V postUpdate(T resource) {
+		V view = populateViewBean(resource);
+		return view;
+	}
+
+	// ----------------------------------------------------------------------------------
+	// Delete Operation
+	// ----------------------------------------------------------------------------------
+	protected T preDelete(Long id) {
+		T resource = getDao().getById(id);
+		if (resource == null) {
+			// Return without error
+			logger.info("Delete ignored for non-existent " + getResourceName()
+					+ " id=" + id);
+		}
+		return resource;
+	}
+
+	public boolean deleteResource(Long id) {
+		boolean result = false;
+		T resource = preDelete(id);
+		if (resource == null) {
+			throw restErrorUtil.createRESTException(getResourceName()
+					+ " not found", MessageEnums.DATA_NOT_FOUND, id, null,
+					getResourceName() + ":" + id);
+		}
+
+		// object security
+		if (!objectSecurityHandler.hasAccess(resource,
+				Permission.permissionType.DELETE)) {
+			// throw 401
+			logger.debug("OBJECT SECURITY");
+		}
+		// Need to delete all dependent common objects like Notes and
+		// UserDataPref
+		bizUtil.deleteReferencedObjects(resource);
+		try {
+			result = getDao().remove(resource);
+		} catch (Exception e) {
+			logger.error("Error deleting " + getResourceName() + ". Id=" + id,
+					e);
+
+			throw restErrorUtil.createRESTException(getResourceName()
+					+ " can't be deleted",
+					MessageEnums.OPER_NOT_ALLOWED_FOR_STATE, id, null, "" + id
+							+ ", error=" + e.getMessage());
+		}
+
+		postDelete(resource);
+
+		return result;
+	}
+
+	protected void postDelete(T resource) {
+
+	}
+
+	// ----------------------------------------------------------------------------------
+	// Validation
+	// ----------------------------------------------------------------------------------
+	protected void validateGenericAttributes(V viewBaseBean) {
+	}
+
+	// ----------------------------------------------------------------------------------
+	// mapping view bean attributes
+	// ----------------------------------------------------------------------------------
+	public V populateViewBean(T resource) {
+		V viewBean = createViewObject();
+		populateViewBean(resource, viewBean);
+		mapEntityToViewBean(viewBean, resource);
+		return viewBean;
+	}
+
+	protected V populateViewBean(T resource, V viewBean) {
+		mapBaseAttributesToViewBean(resource, viewBean);
+		// TODO:Current:Open: Need to set original and updated
+		// content
+		return viewBean;
+	}
+
+	protected void mapBaseAttributesToViewBean(T resource, V viewBean) {
+		viewBean.setId(resource.getId());
+
+		// TBD: Need to review this change later
+		viewBean.setMObj(resource);
+		viewBean.setCreateDate(resource.getCreateTime());
+		viewBean.setUpdateDate(resource.getUpdateTime());
+
+		Long ownerId = resource.getAddedByUserId();
+		UserSessionBase currentUserSession = ContextUtil
+				.getCurrentUserSession();
+
+		if (currentUserSession == null) {
+			return;
+		}
+
+		if (ownerId != null) {
+			XXPortalUser tUser = daoManager.getXXPortalUser().getById(
+					resource.getAddedByUserId());
+			if (tUser != null) {
+				if (tUser.getPublicScreenName() != null
+						&& !tUser.getPublicScreenName().trim().isEmpty()
+						&& !tUser.getPublicScreenName().trim()
+								.equalsIgnoreCase("null")) {
+					viewBean.setOwner(tUser.getPublicScreenName());
+				} else {
+					if (tUser.getFirstName() != null
+							&& !tUser.getFirstName().trim().isEmpty()
+							&& !tUser.getFirstName().trim()
+									.equalsIgnoreCase("null")) {
+						if (tUser.getLastName() != null
+								&& !tUser.getLastName().trim().isEmpty()
+								&& !tUser.getLastName().trim()
+										.equalsIgnoreCase("null")) {
+							viewBean.setOwner(tUser.getFirstName() + " "
+									+ tUser.getLastName());
+						} else {
+							viewBean.setOwner(tUser.getFirstName());
+						}
+					} else {
+						viewBean.setOwner(tUser.getLoginId());
+					}
+				}
+			}
+		}
+		if (resource.getUpdatedByUserId() != null) {
+			XXPortalUser tUser = daoManager.getXXPortalUser().getById(
+					resource.getUpdatedByUserId());
+			if (tUser != null) {
+				if (tUser.getPublicScreenName() != null
+						&& !tUser.getPublicScreenName().trim().isEmpty()
+						&& !tUser.getPublicScreenName().trim()
+								.equalsIgnoreCase("null")) {
+					viewBean.setUpdatedBy(tUser.getPublicScreenName());
+				} else {
+					if (tUser.getFirstName() != null
+							&& !tUser.getFirstName().trim().isEmpty()
+							&& !tUser.getFirstName().trim()
+									.equalsIgnoreCase("null")) {
+						if (tUser.getLastName() != null
+								&& !tUser.getLastName().trim().isEmpty()
+								&& !tUser.getLastName().trim()
+										.equalsIgnoreCase("null")) {
+							viewBean.setUpdatedBy(tUser.getFirstName() + " "
+									+ tUser.getLastName());
+						} else {
+							viewBean.setUpdatedBy(tUser.getFirstName());
+						}
+					} else {
+						viewBean.setUpdatedBy(tUser.getLoginId());
+					}
+				}
+			}
+		}
+
+	}
+
+	// ----------------------------------------------------------------------------------
+	// Search Operation
+	// ----------------------------------------------------------------------------------
+
+	protected Query createQuery(String searchString, String sortString,
+			SearchCriteria searchCriteria, List<SearchField> searchFieldList,
+			boolean isCountQuery) {
+//		EntityManager em = entityDao != null ? entityDao.getEntityManager() : daoManager.getEntityManager();
+		EntityManager em = getDao().getEntityManager();
+		
+		Query query = searchUtil.createSearchQuery(em, searchString, sortString,
+				searchCriteria, searchFieldList, getClassType(), false,
+				isCountQuery);
+		return query;
+	}
+
+	protected long getCountForSearchQuery(SearchCriteria searchCriteria,
+			List<SearchField> searchFieldList) {
+
+		String q = countQueryStr;
+		// Get total count of the rows which meet the search criteria
+		if (searchCriteria.isDistinct()) {
+			q = distinctCountQueryStr;
+		}
+
+		// Get total count of the rows which meet the search criteria
+		Query query = createQuery(q, null, searchCriteria, searchFieldList,
+				true);
+
+		// Make the database call to get the total count
+		Long count = getDao().executeCountQueryInSecurityContext(tEntityClass,
+				query);
+		if (count == null) {
+			// If no data that meets the criteria, return 0
+			return 0;
+		}
+		return count.longValue();
+	}
+
+	public VXLong getSearchCount(SearchCriteria searchCriteria,
+			List<SearchField> searchFieldList) {
+		long count = getCountForSearchQuery(searchCriteria, searchFieldList);
+
+		VXLong vXLong = new VXLong();
+		vXLong.setValue(count);
+		return vXLong;
+	}
+
+	protected List<T> searchResources(SearchCriteria searchCriteria,
+			List<SearchField> searchFieldList, List<SortField> sortFieldList,
+			VList vList) {
+
+		// Get total count of the rows which meet the search criteria
+		long count = -1;
+		if (searchCriteria.isGetCount()) {
+			count = getCountForSearchQuery(searchCriteria, searchFieldList);
+			if (count == 0) {
+				return Collections.emptyList();
+			}
+		}
+		// construct the sort clause
+		String sortClause = searchUtil.constructSortClause(searchCriteria,
+				sortFieldList);
+
+		String q = queryStr;
+		if (searchCriteria.isDistinct()) {
+			q = distinctQueryStr;
+		}
+		// construct the query object for retrieving the data
+		Query query = createQuery(q, sortClause, searchCriteria,
+				searchFieldList, false);
+
+		List<T> resultList = getDao().executeQueryInSecurityContext(
+				tEntityClass, query);
+
+		if (vList != null) {
+			// Set the meta values for the query result
+			vList.setPageSize(query.getMaxResults());
+			vList.setSortBy(searchCriteria.getSortBy());
+			vList.setSortType(searchCriteria.getSortType());
+			vList.setStartIndex(query.getFirstResult());
+			vList.setTotalCount(count);
+			vList.setResultSize(resultList.size());
+		}
+		return resultList;
+	}
+
+	// -------------Criteria Usage--------------------
+	// -----------------------------------------------
+	public VXLong getSearchCountUsingCriteria(SearchCriteria searchCriteria,
+			List<SearchField> searchFieldList) {
+		EntityManager em = getDao().getEntityManager();
+		CriteriaBuilder criteriaBuilder = em.getCriteriaBuilder();
+		CriteriaQuery<Long> criteria = criteriaBuilder.createQuery(Long.class);
+
+		Root<T> from = criteria.from(tEntityClass);
+		Expression<Long> countExpression = criteriaBuilder
+				.count(from.get("id"));
+		criteria.select(countExpression);
+
+		Predicate resourceConditions = buildResourceSpecificConditions(
+				criteriaBuilder, from, searchCriteria);
+		Predicate userConditions = buildUserConditions(
+				searchCriteria.getParamList(), searchFieldList,
+				criteriaBuilder, from);
+
+		if (resourceConditions != null) {
+			criteria.where(criteriaBuilder.and(resourceConditions,
+					userConditions));
+		} else {
+			criteria.where(criteriaBuilder.and(userConditions));
+		}
+
+		TypedQuery<Long> countQuery = em.createQuery(criteria);
+		long count = getDao().executeCountQueryInSecurityContext(tEntityClass,
+				countQuery);
+
+		VXLong vXLong = new VXLong();
+		vXLong.setValue(count);
+		return vXLong;
+	}
+
+	protected List<T> searchResourcesUsingCriteria(
+			SearchCriteria searchCriteria, List<SearchField> searchFieldList,
+			List<SortField> sortFieldList, VList vList) {
+		// boolean filterEnabled = getDao().enableVisiblityFilters(tClass,
+		// true);
+
+		EntityManager em = getDao().getEntityManager();
+		CriteriaBuilder criteriaBuilder = em.getCriteriaBuilder();
+		CriteriaQuery criteria = criteriaBuilder.createQuery();
+		Root<T> from = criteria.from(tEntityClass);
+
+		Predicate resourceConditions = buildResourceSpecificConditions(
+				criteriaBuilder, from, searchCriteria);
+		Predicate userConditions = buildUserConditions(
+				searchCriteria.getParamList(), searchFieldList,
+				criteriaBuilder, from);
+
+		if (resourceConditions != null) {
+			criteria.where(criteriaBuilder.and(resourceConditions,
+					userConditions));
+		} else {
+			criteria.where(criteriaBuilder.and(userConditions));
+		}
+
+		// Get total count of the rows which meet the search criteria
+		long count = -1;
+		if (searchCriteria.isGetCount()) {
+
+			Expression<Long> countExpression = criteriaBuilder.count(from
+					.get("id"));
+			criteria.select(countExpression);
+			TypedQuery<Long> countQuery = em.createQuery(criteria);
+			count = getDao().executeCountQueryInSecurityContext(tEntityClass,
+					countQuery);
+			if (count == 0) {
+				return Collections.emptyList();
+			}
+		}
+
+		// construct the sort clause
+		setSortClause(searchCriteria, sortFieldList, criteriaBuilder, criteria,
+				from);
+
+		criteria.select(from);
+		TypedQuery<T> typedQuery = em.createQuery(criteria);
+		searchUtil.updateQueryPageSize(typedQuery, searchCriteria);
+
+		List<T> resultList = getDao().executeQueryInSecurityContext(
+				tEntityClass, typedQuery);
+
+		if (vList != null) {
+			// Set the meta values for the query result
+			vList.setPageSize(typedQuery.getMaxResults());
+			vList.setSortBy(searchCriteria.getSortBy());
+			vList.setSortType(searchCriteria.getSortType());
+			vList.setStartIndex(typedQuery.getFirstResult());
+			vList.setTotalCount(count);
+		}
+
+		// if (filterEnabled) {
+		// getDao().disableVisiblityFilters(tClass);
+		// }
+
+		return resultList;
+	}
+
+	protected Predicate buildUserConditions(Map<String, Object> paramList,
+			List<SearchField> searchFields, CriteriaBuilder cb,
+			Root<? extends XXDBBase> from) {
+		Predicate userConditions = cb.conjunction();
+
+		for (SearchField searchField : searchFields) {
+			if (paramList.containsKey(searchField.getClientFieldName())) {
+				Path<Object> tableField = null;
+				String fieldName = searchField.getFieldName();
+
+				// stuff to handle jpql syntax (e.g. obj.id, obj.city.city etc).
+				// There has to be better way of dealing with this. Will look
+				// again.
+				int dotIndex = fieldName.indexOf(".");
+				if (dotIndex != -1) {
+					fieldName = fieldName.substring(dotIndex + 1);
+				}
+				dotIndex = fieldName.indexOf(".");
+				if (dotIndex == -1) {
+					tableField = from.get(fieldName);
+				} else {
+					String joinTable = fieldName.substring(0, dotIndex);
+					fieldName = fieldName.substring(dotIndex + 1);
+					tableField = from.join(joinTable).get(fieldName);
+				}
+
+				Object value = paramList.get(searchField.getClientFieldName());
+				if (value == null) {
+					userConditions = cb.and(userConditions,
+							cb.isNull(tableField));
+					continue;
+				}
+
+				if (searchField.getDataType() == SearchField.DATA_TYPE.INTEGER
+						|| searchField.getDataType() == SearchField.DATA_TYPE.BOOLEAN) {
+					userConditions = cb.and(userConditions,
+							cb.equal(tableField, value));
+				} else if (searchField.getDataType() == SearchField.DATA_TYPE.STRING) {
+					String strFieldValue = (String) value;
+					Expression<String> tableFieldWithLowerExpr = cb
+							.lower(tableField.as(String.class));
+
+					if (searchField.getSearchType() == SearchField.SEARCH_TYPE.FULL) {
+						Expression<String> literal = cb.lower(cb
+								.literal(strFieldValue));
+						userConditions = cb.and(userConditions,
+								cb.equal(tableFieldWithLowerExpr, literal));
+					} else {
+						Expression<String> literal = cb.lower(cb.literal("%"
+								+ strFieldValue + "%"));
+						userConditions = cb.and(userConditions,
+								cb.like(tableFieldWithLowerExpr, literal));
+					}
+				} else if (searchField.getDataType() == SearchField.DATA_TYPE.INT_LIST) {
+
+					@SuppressWarnings("unchecked")
+					Collection<Number> intValueList = (Collection<Number>) value;
+					if (intValueList.size() == 1) {
+						userConditions = cb.and(userConditions,
+								cb.equal(tableField, value));
+					} else if (intValueList.size() > 1) {
+						userConditions = cb.and(userConditions,
+								tableField.in(intValueList));
+					}
+				}
+
+			}
+
+		} // for
+
+		return userConditions;
+	}
+
+	protected Predicate buildResourceSpecificConditions(
+			CriteriaBuilder criteriaBuilder, Root<T> from, SearchCriteria sc) {
+		return null;
+	}
+
+	public void setSortClause(SearchCriteria searchCriteria,
+			List<SortField> sortFields, CriteriaBuilder criteriaBuilder,
+			CriteriaQuery<? extends Object> criteria, Root<? extends XXDBBase> from) {
+
+		String sortBy = searchCriteria.getSortBy();
+		String sortByField = null;
+
+		if (!stringUtil.isEmpty(sortBy)) {
+			sortBy = sortBy.trim();
+			for (SortField sortField : sortFields) {
+				if (sortBy.equalsIgnoreCase(sortField.getParamName())) {
+					sortByField = sortField.getFieldName();
+					// Override the sortBy using the normalized value
+					// searchCriteria.setSortBy(sortByField);
+					break;
+				}
+			}
+		}
+
+		if (sortByField == null) {
+			for (SortField sortField : sortFields) {
+				if (sortField.isDefault()) {
+					sortByField = sortField.getFieldName();
+					// Override the sortBy using the default value
+					searchCriteria.setSortBy(sortField.getParamName());
+					searchCriteria.setSortType(sortField.getDefaultOrder()
+							.name());
+					break;
+				}
+			}
+		}
+
+		if (sortByField != null) {
+			int dotIndex = sortByField.indexOf(".");
+			if (dotIndex != -1) {
+				sortByField = sortByField.substring(dotIndex + 1);
+			}
+
+			// Add sort type
+			String sortType = searchCriteria.getSortType();
+			if (sortType != null && sortType.equalsIgnoreCase("desc")) {
+				criteria.orderBy(criteriaBuilder.desc(from.get(sortByField)));
+			} else {
+				criteria.orderBy(criteriaBuilder.asc(from.get(sortByField)));
+			}
+
+		}
+	}
+}

http://git-wip-us.apache.org/repos/asf/incubator-argus/blob/7defc061/security-admin/src/main/java/com/xasecure/service/AuthSessionService.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/service/AuthSessionService.java b/security-admin/src/main/java/com/xasecure/service/AuthSessionService.java
new file mode 100644
index 0000000..9fdfaa6
--- /dev/null
+++ b/security-admin/src/main/java/com/xasecure/service/AuthSessionService.java
@@ -0,0 +1,188 @@
+package com.xasecure.service;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import com.xasecure.common.XAConstants;
+import com.xasecure.common.SearchCriteria;
+import com.xasecure.common.SearchField;
+import com.xasecure.common.SortField;
+import com.xasecure.common.StringUtil;
+import com.xasecure.common.db.BaseDao;
+import com.xasecure.entity.XXAuthSession;
+import com.xasecure.entity.XXPortalUser;
+import com.xasecure.view.VXAuthSession;
+import com.xasecure.view.VXAuthSessionList;
+
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.context.annotation.Scope;
+import org.springframework.stereotype.Service;
+
+@Service
+@Scope("singleton")
+public class AuthSessionService extends
+		AbstractBaseResourceService<XXAuthSession, VXAuthSession> {
+	@Autowired
+	StringUtil stringUtil;
+
+	public static final String NAME = "AuthSession";
+
+	public static final List<SortField> AUTH_SESSION_SORT_FLDS = new ArrayList<SortField>();
+	static {
+		AUTH_SESSION_SORT_FLDS.add(new SortField("id", "obj.id"));
+		AUTH_SESSION_SORT_FLDS.add(new SortField("authTime", "obj.authTime",
+				true, SortField.SORT_ORDER.DESC));
+	}
+
+	public static List<SearchField> AUTH_SESSION_SEARCH_FLDS = new ArrayList<SearchField>();
+	static {
+		AUTH_SESSION_SEARCH_FLDS.add(SearchField.createLong("id", "obj.id"));
+		AUTH_SESSION_SEARCH_FLDS.add(SearchField.createString("loginId",
+				"obj.loginId", SearchField.SEARCH_TYPE.PARTIAL,
+				StringUtil.VALIDATION_LOGINID));
+		AUTH_SESSION_SEARCH_FLDS.add(SearchField.createLong("userId",
+				"obj.userId"));
+		AUTH_SESSION_SEARCH_FLDS.add(SearchField.createEnum("authStatus",
+				"obj.authStatus", "statusList", XXAuthSession.AuthStatus_MAX));
+		AUTH_SESSION_SEARCH_FLDS.add(SearchField.createEnum("authType",
+				"obj.authType", "Authentication Type",
+				XXAuthSession.AuthType_MAX));
+		AUTH_SESSION_SEARCH_FLDS.add(SearchField.createEnum("deviceType",
+				"obj.deviceType", "Device Type", XAConstants.DeviceType_MAX));
+		AUTH_SESSION_SEARCH_FLDS.add(SearchField.createString("requestIP",
+				"obj.requestIP", SearchField.SEARCH_TYPE.PARTIAL,
+				StringUtil.VALIDATION_IP_ADDRESS));
+		AUTH_SESSION_SEARCH_FLDS.add(SearchField.createString(
+				"requestUserAgent", "obj.requestUserAgent",
+				SearchField.SEARCH_TYPE.PARTIAL, null));
+		AUTH_SESSION_SEARCH_FLDS.add(new SearchField("firstName",
+				"obj.user.firstName", SearchField.DATA_TYPE.STRING,
+				SearchField.SEARCH_TYPE.PARTIAL));
+		AUTH_SESSION_SEARCH_FLDS.add(new SearchField("lastName",
+				"obj.user.lastName", SearchField.DATA_TYPE.STRING,
+				SearchField.SEARCH_TYPE.PARTIAL));
+		AUTH_SESSION_SEARCH_FLDS.add(SearchField.createString("requestIP",
+				"obj.requestIP", SearchField.SEARCH_TYPE.PARTIAL,
+				StringUtil.VALIDATION_IP_ADDRESS));	
+		AUTH_SESSION_SEARCH_FLDS.add(new SearchField("startDate", "obj.createTime",
+				SearchField.DATA_TYPE.DATE, SearchField.SEARCH_TYPE.GREATER_EQUAL_THAN));
+		AUTH_SESSION_SEARCH_FLDS.add(new SearchField("endDate", "obj.createTime",
+				SearchField.DATA_TYPE.DATE, SearchField.SEARCH_TYPE.LESS_EQUAL_THAN));
+	}
+
+	@Override
+	protected String getResourceName() {
+		return NAME;
+	}
+
+	@Override
+	protected int getClassType() {
+		return XAConstants.CLASS_TYPE_AUTH_SESS;
+	}
+
+	/*
+	 * (non-Javadoc)
+	 */
+	@Override
+	protected BaseDao<XXAuthSession> getDao() {
+		return daoMgr.getXXAuthSession();
+	}
+
+	/*
+	 * (non-Javadoc)
+	 */
+	@Override
+	protected XXAuthSession createEntityObject() {
+		return new XXAuthSession();
+	}
+
+	/*
+	 * (non-Javadoc)
+	 */
+	@Override
+	protected VXAuthSession createViewObject() {
+		return new VXAuthSession();
+	}
+
+	/*
+	 * (non-Javadoc)
+	 */
+	@Override
+	protected void validateForCreate(VXAuthSession vXAuthSession) {
+		logger.error("This method is not required and shouldn't be called.",
+				new Throwable().fillInStackTrace());
+	}
+
+	/*
+	 * (non-Javadoc)
+	 */
+	@Override
+	protected void validateForUpdate(VXAuthSession vXAuthSession,
+			XXAuthSession mObj) {
+		logger.error("This method is not required and shouldn't be called.",
+				new Throwable().fillInStackTrace());
+	}
+
+	/*
+	 * (non-Javadoc)
+	 */
+	@Override
+	protected XXAuthSession mapViewToEntityBean(VXAuthSession vXAuthSession,
+			XXAuthSession t, int OPERATION_CONTEXT) {
+		logger.error("This method is not required and shouldn't be called.",
+				new Throwable().fillInStackTrace());
+		return null;
+	}
+
+	/*
+	 * (non-Javadoc)
+	 */
+	@Override
+	protected VXAuthSession mapEntityToViewBean(VXAuthSession viewObj,
+			XXAuthSession resource) {
+		viewObj.setLoginId(resource.getLoginId());
+		viewObj.setAuthTime(resource.getAuthTime());
+		viewObj.setAuthStatus(resource.getAuthStatus());
+		viewObj.setAuthType(resource.getAuthType());
+		viewObj.setDeviceType(resource.getDeviceType());
+		viewObj.setExtSessionId(resource.getExtSessionId());
+		viewObj.setId(resource.getId());
+		viewObj.setRequestIP(resource.getRequestIP());
+
+		viewObj.setRequestUserAgent(resource.getRequestUserAgent());
+
+		if (resource.getUserId() != null) {
+			XXPortalUser gjUser = daoMgr.getXXPortalUser().getById(resource.getUserId());
+			viewObj.setEmailAddress(gjUser.getEmailAddress());
+			viewObj.setFamilyScreenName(gjUser.getEmailAddress());
+			viewObj.setFirstName(gjUser.getFirstName());
+			viewObj.setLastName(gjUser.getLastName());
+			viewObj.setLastName(gjUser.getLastName());
+			viewObj.setPublicScreenName(gjUser.getPublicScreenName());
+			viewObj.setUserId(resource.getUserId());
+		}
+
+		return viewObj;
+	}
+
+	/**
+	 * @param searchCriteria
+	 * @return
+	 */
+	public VXAuthSessionList search(SearchCriteria searchCriteria) {
+		VXAuthSessionList returnList = new VXAuthSessionList();
+		List<VXAuthSession> viewList = new ArrayList<VXAuthSession>();
+
+		List<XXAuthSession> resultList = searchResources(searchCriteria,
+				AUTH_SESSION_SEARCH_FLDS, AUTH_SESSION_SORT_FLDS, returnList);
+
+		// Iterate over the result list and create the return list
+		for (XXAuthSession gjObj : resultList) {
+			VXAuthSession viewObj = populateViewBean(gjObj);
+			viewList.add(viewObj);
+		}
+
+		returnList.setVXAuthSessions(viewList);
+		return returnList;
+	}
+}

http://git-wip-us.apache.org/repos/asf/incubator-argus/blob/7defc061/security-admin/src/main/java/com/xasecure/service/PublicAPIServiceBase.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/service/PublicAPIServiceBase.java b/security-admin/src/main/java/com/xasecure/service/PublicAPIServiceBase.java
new file mode 100644
index 0000000..b2d2b59
--- /dev/null
+++ b/security-admin/src/main/java/com/xasecure/service/PublicAPIServiceBase.java
@@ -0,0 +1,26 @@
+package com.xasecure.service;
+
+import com.xasecure.view.VXDataObject;
+
+public abstract class PublicAPIServiceBase<VXA extends VXDataObject, VX extends VXDataObject> {
+
+	protected VX mapBaseAttributesToPublicObject(VXA vXAObj, VX vPublicObj) {
+		vPublicObj.setId(vXAObj.getId());
+		vPublicObj.setCreateDate(vXAObj.getCreateDate());
+		vPublicObj.setUpdateDate(vXAObj.getUpdateDate());
+		vPublicObj.setOwner(vXAObj.getOwner());
+		vPublicObj.setUpdatedBy(vXAObj.getUpdatedBy());
+		return vPublicObj;
+	}
+
+	protected VXA mapBaseAttributesToXAObject(VX vPublicObj, VXA vXAObj) {
+		vXAObj.setId(vPublicObj.getId());
+		vXAObj.setCreateDate(vPublicObj.getCreateDate());
+		vXAObj.setUpdateDate(vPublicObj.getUpdateDate());
+		vXAObj.setOwner(vPublicObj.getOwner());
+		vXAObj.setUpdatedBy(vPublicObj.getUpdatedBy());
+
+		return vXAObj;
+	}
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-argus/blob/7defc061/security-admin/src/main/java/com/xasecure/service/UserService.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/service/UserService.java b/security-admin/src/main/java/com/xasecure/service/UserService.java
new file mode 100644
index 0000000..b7a0068
--- /dev/null
+++ b/security-admin/src/main/java/com/xasecure/service/UserService.java
@@ -0,0 +1,310 @@
+package com.xasecure.service;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.List;
+
+import com.xasecure.common.XAConstants;
+import com.xasecure.common.ContextUtil;
+import com.xasecure.common.XAConfigUtil;
+import com.xasecure.common.MessageEnums;
+import com.xasecure.common.StringUtil;
+import com.xasecure.common.UserSessionBase;
+import com.xasecure.entity.XXPortalUser;
+import com.xasecure.entity.XXPortalUserRole;
+import com.xasecure.view.VXMessage;
+import com.xasecure.view.VXResponse;
+import com.xasecure.view.VXPortalUser;
+
+import org.apache.log4j.Logger;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.context.annotation.Scope;
+import org.springframework.stereotype.Service;
+
+@Service
+@Scope("singleton")
+public class UserService extends UserServiceBase<XXPortalUser, VXPortalUser> {
+	static Logger logger = Logger.getLogger(UserService.class);
+
+	public static final String NAME = "User";
+
+	@Autowired
+	XAConfigUtil configUtil;
+
+	private static UserService instance = null;
+
+	public UserService() {
+		super();
+		instance = this;
+	}
+
+	public static UserService getInstance() {
+		if (instance == null) {
+			logger.error("Instance is null", new Throwable());
+		}
+		return instance;
+	}
+
+	@Override
+	protected void validateForCreate(VXPortalUser userProfile) {
+		List<VXMessage> messageList = new ArrayList<VXMessage>();
+		if (stringUtil.isEmpty(userProfile.getEmailAddress())) {
+			logger.info("Empty Email Address." + userProfile);
+			messageList.add(MessageEnums.NO_INPUT_DATA.getMessage(null,
+					"emailAddress"));
+		}
+
+		if (stringUtil.isEmpty(userProfile.getFirstName())) {
+			logger.info("Empty firstName." + userProfile);
+			messageList.add(MessageEnums.NO_INPUT_DATA.getMessage(null,
+					"firstName"));
+		}
+		if (stringUtil.isEmpty(userProfile.getLastName())) {
+			logger.info("Empty lastName." + userProfile);
+			messageList.add(MessageEnums.NO_INPUT_DATA.getMessage(null,
+					"lastName"));
+		}
+		// firstName
+		if (!stringUtil.isValidName(userProfile.getFirstName())) {
+			logger.info("Invalid first name." + userProfile);
+			messageList.add(MessageEnums.INVALID_INPUT_DATA.getMessage(null,
+					"firstName"));
+		}
+		userProfile.setFirstName(stringUtil.toCamelCaseAllWords(userProfile
+				.getFirstName()));
+
+		// lastName
+		if (!stringUtil.isValidName(userProfile.getLastName())) {
+			logger.info("Invalid last name." + userProfile);
+			messageList.add(MessageEnums.INVALID_INPUT_DATA.getMessage(null,
+					"lastName"));
+		}
+		userProfile.setLastName(stringUtil.toCamelCaseAllWords(userProfile
+				.getLastName()));
+
+		if (!stringUtil.validateEmail(userProfile.getEmailAddress())) {
+			logger.info("Invalid email address." + userProfile);
+			messageList.add(MessageEnums.INVALID_INPUT_DATA.getMessage(null,
+					"emailAddress"));
+
+		}
+
+		// Normalize email. Make it lower case
+		userProfile.setEmailAddress(stringUtil.normalizeEmail(userProfile
+				.getEmailAddress()));
+
+		// loginId
+		userProfile.setLoginId(userProfile.getEmailAddress());
+
+		// password
+		if (!stringUtil.validatePassword(
+				userProfile.getPassword(),
+				new String[] { userProfile.getFirstName(),
+						userProfile.getLastName() })) {
+			logger.info("Invalid password." + userProfile);
+			messageList.add(MessageEnums.INVALID_INPUT_DATA.getMessage(null,
+					"password"));
+		}
+
+		// firstName
+		if (!stringUtil.validateString(StringUtil.VALIDATION_NAME,
+				userProfile.getFirstName())) {
+			logger.info("Invalid first name." + userProfile);
+			messageList.add(MessageEnums.INVALID_INPUT_DATA.getMessage(null,
+					"firstName"));
+		}
+
+		// lastName
+		if (!stringUtil.validateString(StringUtil.VALIDATION_NAME,
+				userProfile.getLastName())) {
+			logger.info("Invalid last name." + userProfile);
+			messageList.add(MessageEnums.INVALID_INPUT_DATA.getMessage(null,
+					"lastName"));
+		}
+
+		// create the public screen name
+		userProfile.setPublicScreenName(userProfile.getFirstName() + " "
+				+ userProfile.getLastName());
+
+		if (messageList.size() > 0) {
+			VXResponse gjResponse = new VXResponse();
+			gjResponse.setStatusCode(VXResponse.STATUS_ERROR);
+			gjResponse.setMsgDesc("Validation failure");
+			gjResponse.setMessageList(messageList);
+			logger.info("Validation Error in createUser() userProfile="
+					+ userProfile + ", error=" + gjResponse);
+			throw restErrorUtil.createRESTException(gjResponse);
+		}
+	}
+
+	@Override
+	protected void validateForUpdate(VXPortalUser userProfile, XXPortalUser xXPortalUser) {
+		List<VXMessage> messageList = new ArrayList<VXMessage>();
+
+		if (userProfile.getEmailAddress() != null
+				&& !userProfile.getEmailAddress().equalsIgnoreCase(
+						xXPortalUser.getEmailAddress())) {
+			throw restErrorUtil.createRESTException("serverMsg.userEmail",
+					MessageEnums.DATA_NOT_UPDATABLE, null, "emailAddress",
+					userProfile.getEmailAddress());
+		}
+
+		// Login Id can't be changed
+		if (userProfile.getLoginId() != null
+				&& !xXPortalUser.getLoginId().equalsIgnoreCase(
+						userProfile.getLoginId())) {
+			throw restErrorUtil.createRESTException("serverMsg.userUserName",
+					MessageEnums.DATA_NOT_UPDATABLE, null, "loginId",
+					userProfile.getLoginId());
+		}
+		// }
+
+		userProfile.setFirstName(restErrorUtil.validateStringForUpdate(
+				userProfile.getFirstName(), xXPortalUser.getFirstName(),
+				StringUtil.VALIDATION_NAME, "serverMsg.userFirstName",
+				MessageEnums.INVALID_INPUT_DATA, null, "firstName"));
+
+		userProfile.setFirstName(restErrorUtil.validateStringForUpdate(
+				userProfile.getFirstName(), xXPortalUser.getFirstName(),
+				StringUtil.VALIDATION_NAME, "serverMsg.userFirstName",
+				MessageEnums.INVALID_INPUT_DATA, null, "firstName"));
+
+		userProfile.setLastName(restErrorUtil.validateStringForUpdate(
+				userProfile.getLastName(), xXPortalUser.getLastName(),
+				StringUtil.VALIDATION_NAME, "serverMsg.userLastName",
+				MessageEnums.INVALID_INPUT_DATA, null, "lastName"));
+
+		// firstName
+		if (!stringUtil.isValidName(userProfile.getFirstName())) {
+			logger.info("Invalid first name." + userProfile);
+			messageList.add(MessageEnums.INVALID_INPUT_DATA.getMessage(null,
+					"firstName"));
+		}
+
+		// lastName
+		if (!stringUtil.isValidName(userProfile.getLastName())) {
+			logger.info("Invalid last name." + userProfile);
+			messageList.add(MessageEnums.INVALID_INPUT_DATA.getMessage(null,
+					"lastName"));
+		}
+
+		userProfile.setNotes(restErrorUtil.validateStringForUpdate(
+				userProfile.getNotes(), xXPortalUser.getNotes(),
+				StringUtil.VALIDATION_NAME, "serverMsg.userNotes",
+				MessageEnums.INVALID_INPUT_DATA, null, "notes"));
+
+		// validate status
+		restErrorUtil.validateMinMax(userProfile.getStatus(), 0,
+				XAConstants.ActivationStatus_MAX, "Invalid status", null,
+				"status");
+
+		// validate user roles
+		if (userProfile.getUserRoleList() != null) {
+			// First let's normalize it
+			splitUserRoleList(userProfile.getUserRoleList());
+			for (String userRole : userProfile.getUserRoleList()) {
+				restErrorUtil.validateStringList(userRole,
+						configUtil.getRoles(), "serverMsg.userRole", null,
+						"userRoleList");
+			}
+
+		}
+
+		// TODO: Need to see whether user can set user as internal
+
+		if (messageList.size() > 0) {
+			VXResponse gjResponse = new VXResponse();
+			gjResponse.setStatusCode(VXResponse.STATUS_ERROR);
+			gjResponse.setMsgDesc("Validation failure");
+			gjResponse.setMessageList(messageList);
+			logger.info("Validation Error in updateUser() userProfile="
+					+ userProfile + ", error=" + gjResponse);
+			throw restErrorUtil.createRESTException(gjResponse);
+		}
+	}
+
+	void splitUserRoleList(Collection<String> collection) {
+		Collection<String> newCollection = new ArrayList<String>();
+		for (String role : collection) {
+			String roles[] = role.split(",");
+			for (int i = 0; i < roles.length; i++) {
+				String str = roles[i];
+				newCollection.add(str);
+			}
+		}
+		collection.clear();
+		collection.addAll(newCollection);
+	}
+
+	@Override
+	protected XXPortalUser mapViewToEntityBean(VXPortalUser userProfile, XXPortalUser mObj,
+			int OPERATION_CONTEXT) {
+		mObj.setEmailAddress(userProfile.getEmailAddress());
+		mObj.setFirstName(userProfile.getFirstName());
+		mObj.setLastName(userProfile.getLastName());
+		mObj.setLoginId(userProfile.getLoginId());
+		mObj.setPassword(userProfile.getPassword());
+		mObj.setPublicScreenName(bizUtil.generatePublicName(userProfile, null));
+		mObj.setUserSource(userProfile.getUserSource());
+		return mObj;
+
+	}
+
+	@Override
+	protected VXPortalUser mapEntityToViewBean(VXPortalUser userProfile,
+			XXPortalUser user) {
+		userProfile.setId(user.getId());
+		userProfile.setLoginId(user.getLoginId());
+		userProfile.setFirstName(user.getFirstName());
+		userProfile.setLastName(user.getLastName());
+		userProfile.setPublicScreenName(user.getPublicScreenName());
+		userProfile.setStatus(user.getStatus());
+		userProfile.setUserRoleList(new ArrayList<String>());
+		String emailAddress = user.getEmailAddress();
+		if (emailAddress != null && stringUtil.validateEmail(emailAddress)) {
+			userProfile.setEmailAddress(user.getEmailAddress());
+		}
+
+		UserSessionBase sess = ContextUtil.getCurrentUserSession();
+		if (sess != null) {
+			userProfile.setUserSource(sess.getAuthProvider());
+		}
+
+		List<XXPortalUserRole> gjUserRoleList = daoMgr.getXXPortalUserRole().findByParentId(
+				user.getId());
+
+		for (XXPortalUserRole gjUserRole : gjUserRoleList) {
+			userProfile.getUserRoleList().add(gjUserRole.getUserRole());
+		}
+		return userProfile;
+	}
+
+	// TODO: Need to remove this ASAP
+	public void gjUserToUserProfile(XXPortalUser user, VXPortalUser userProfile) {
+		userProfile.setId(user.getId());
+		userProfile.setLoginId(user.getLoginId());
+		userProfile.setFirstName(user.getFirstName());
+		userProfile.setLastName(user.getLastName());
+		userProfile.setPublicScreenName(user.getPublicScreenName());
+		userProfile.setStatus(user.getStatus());
+		userProfile.setUserRoleList(new ArrayList<String>());
+		UserSessionBase sess = ContextUtil.getCurrentUserSession();
+
+		String emailAddress = user.getEmailAddress();
+		if (emailAddress != null && stringUtil.validateEmail(emailAddress)) {
+			userProfile.setEmailAddress(user.getEmailAddress());
+		}
+
+		if (sess != null) {
+			userProfile.setUserSource(sess.getAuthProvider());
+		}
+
+		List<XXPortalUserRole> gjUserRoleList = daoMgr.getXXPortalUserRole().findByParentId(
+				user.getId());
+
+		for (XXPortalUserRole gjUserRole : gjUserRoleList) {
+			userProfile.getUserRoleList().add(gjUserRole.getUserRole());
+		}
+	}
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-argus/blob/7defc061/security-admin/src/main/java/com/xasecure/service/UserServiceBase.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/service/UserServiceBase.java b/security-admin/src/main/java/com/xasecure/service/UserServiceBase.java
new file mode 100644
index 0000000..766be55
--- /dev/null
+++ b/security-admin/src/main/java/com/xasecure/service/UserServiceBase.java
@@ -0,0 +1,64 @@
+package com.xasecure.service;
+/*
+ * Copyright (c) 2014 XASecure
+ * All rights reserved.
+ *
+ * This software is the confidential and proprietary information of
+ * XASecure. ("Confidential Information").  You shall not
+ * disclose such Confidential Information and shall use it only in
+ * accordance with the terms of the license agreement you entered into
+ * with XASecure.
+ */
+
+import java.util.ArrayList;
+import java.util.List;
+
+import com.xasecure.common.*;
+import com.xasecure.entity.*;
+import com.xasecure.view.*;
+import com.xasecure.service.*;
+
+public abstract class UserServiceBase<T extends XXPortalUser, V extends VXPortalUser>
+		extends AbstractBaseResourceService<T, V> {
+	public static final String NAME = "User";
+
+	public UserServiceBase() {
+
+	}
+
+	@SuppressWarnings("unchecked")
+	@Override
+	protected XXPortalUser mapViewToEntityBean(VXPortalUser vObj, XXPortalUser mObj, int OPERATION_CONTEXT) {
+		return mObj;
+	}
+
+	@SuppressWarnings("unchecked")
+	@Override
+	protected VXPortalUser mapEntityToViewBean(VXPortalUser vObj, XXPortalUser mObj) {
+		return vObj;
+	}
+
+	/**
+	 * @param searchCriteria
+	 * @return
+	 */
+	public VXPortalUserList searchUsers(SearchCriteria searchCriteria) {
+		VXPortalUserList returnList = new VXPortalUserList();
+		List<VXPortalUser> userList = new ArrayList<VXPortalUser>();
+
+		@SuppressWarnings("unchecked")
+		List<XXPortalUser> resultList = (List<XXPortalUser>)searchResources(searchCriteria,
+				searchFields, sortFields, returnList);
+
+		// Iterate over the result list and create the return list
+		for (XXPortalUser gjUser : resultList) {
+			@SuppressWarnings("unchecked")
+			VXPortalUser vUser = populateViewBean((T)gjUser);
+			userList.add(vUser);
+		}
+
+		returnList.setVXPortalUsers(userList);
+		return returnList;
+	}
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-argus/blob/7defc061/security-admin/src/main/java/com/xasecure/service/XAccessAuditService.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/service/XAccessAuditService.java b/security-admin/src/main/java/com/xasecure/service/XAccessAuditService.java
new file mode 100644
index 0000000..8e2c0dd
--- /dev/null
+++ b/security-admin/src/main/java/com/xasecure/service/XAccessAuditService.java
@@ -0,0 +1,246 @@
+package com.xasecure.service;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+
+import javax.persistence.Query;
+
+import com.xasecure.common.SearchCriteria;
+import com.xasecure.common.SearchField;
+import com.xasecure.common.SearchUtil;
+import com.xasecure.common.SortField;
+import com.xasecure.common.SearchField.DATA_TYPE;
+import com.xasecure.common.SearchField.SEARCH_TYPE;
+import com.xasecure.common.SortField.SORT_ORDER;
+import com.xasecure.common.view.VList;
+import com.xasecure.view.*;
+import com.xasecure.db.XADaoManager;
+import com.xasecure.entity.*;
+
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.context.annotation.Scope;
+import org.springframework.stereotype.Service;
+
+@Service
+@Scope("singleton")
+public class XAccessAuditService extends XAccessAuditServiceBase<XXAccessAudit, VXAccessAudit>{
+	public static final String NAME = "XAccessAudit";
+	public List<SortField> sortFields = new ArrayList<SortField>();
+	public List<SearchField> searchFields = new ArrayList<SearchField>();
+
+	@Autowired
+	protected SearchUtil searchUtil;
+	
+	@Autowired
+	XADaoManager appDaoMgr;
+
+	protected String queryStr;
+	protected final String distinctCountQueryStr;
+	protected final String distinctQueryStr;
+	protected String countQueryStr;
+
+
+	public XAccessAuditService() {
+		countQueryStr = "SELECT COUNT(obj) FROM XXAccessAudit  obj ";
+		queryStr = "SELECT obj FROM XXAccessAudit obj ";
+		distinctCountQueryStr = "SELECT COUNT(distinct obj.id) FROM XXAccessAudit obj ";
+		distinctQueryStr = "SELECT distinct obj FROM XXAccessAudit obj ";
+		
+		searchFields.add(new SearchField("accessType", "obj.accessType",
+				SearchField.DATA_TYPE.STRING, SearchField.SEARCH_TYPE.PARTIAL));
+		searchFields.add(new SearchField("aclEnforcer", "obj.aclEnforcer",
+				SearchField.DATA_TYPE.STRING, SearchField.SEARCH_TYPE.PARTIAL));
+		searchFields.add(new SearchField("agentId", "obj.agentId",
+				SearchField.DATA_TYPE.STRING, SearchField.SEARCH_TYPE.PARTIAL));
+		searchFields.add(new SearchField("repoName", "obj.repoName",
+				SearchField.DATA_TYPE.STRING, SearchField.SEARCH_TYPE.PARTIAL));
+		searchFields.add(new SearchField("sessionId", "obj.sessionId",
+				SearchField.DATA_TYPE.STRING, SearchField.SEARCH_TYPE.PARTIAL));
+		searchFields.add(new SearchField("requestUser", "obj.requestUser",
+				SearchField.DATA_TYPE.STRING, SearchField.SEARCH_TYPE.PARTIAL));
+		searchFields.add(new SearchField("requestData", "obj.requestData",
+				SearchField.DATA_TYPE.STRING, SearchField.SEARCH_TYPE.PARTIAL));
+		searchFields.add(new SearchField("resourcePath", "obj.resourcePath",
+				SearchField.DATA_TYPE.STRING, SearchField.SEARCH_TYPE.PARTIAL));
+		searchFields.add(new SearchField("clientIP", "obj.clientIP",
+				SearchField.DATA_TYPE.STRING, SearchField.SEARCH_TYPE.PARTIAL));
+
+		searchFields.add(new SearchField("auditType", "obj.auditType",
+				SearchField.DATA_TYPE.INTEGER, SearchField.SEARCH_TYPE.FULL));
+		searchFields.add(new SearchField("accessResult", "obj.accessResult",
+				SearchField.DATA_TYPE.INTEGER, SearchField.SEARCH_TYPE.FULL));
+		searchFields.add(new SearchField("assetId", "obj.assetId",
+				SearchField.DATA_TYPE.INTEGER, SearchField.SEARCH_TYPE.FULL));
+		searchFields.add(new SearchField("policyId", "obj.policyId",
+				SearchField.DATA_TYPE.INTEGER, SearchField.SEARCH_TYPE.FULL));
+		searchFields.add(new SearchField("repoType", "obj.repoType",
+				SearchField.DATA_TYPE.INTEGER, SearchField.SEARCH_TYPE.FULL));
+
+		searchFields.add(new SearchField("startDate", "obj.eventTime", 
+				DATA_TYPE.DATE, SEARCH_TYPE.GREATER_EQUAL_THAN));
+		searchFields.add(new SearchField("endDate", "obj.eventTime", 
+				DATA_TYPE.DATE, SEARCH_TYPE.LESS_EQUAL_THAN));
+		sortFields.add(new SortField("eventTime", "obj.eventTime", true, SORT_ORDER.DESC));
+}
+
+	protected XXAccessAudit mapViewToEntityBean(VXAccessAudit vObj, XXAccessAudit mObj, int OPERATION_CONTEXT) {
+		mObj.setId(vObj.getId());
+		mObj.setAuditType( vObj.getAuditType());
+		mObj.setAccessResult( vObj.getAccessResult());
+		mObj.setAccessType( vObj.getAccessType());
+		mObj.setAclEnforcer( vObj.getAclEnforcer());
+		mObj.setAgentId( vObj.getAgentId());
+		mObj.setPolicyId( vObj.getPolicyId());
+		mObj.setRepoName( vObj.getRepoName());
+		mObj.setRepoType( vObj.getRepoType());
+		mObj.setResultReason( vObj.getResultReason());
+		mObj.setSessionId( vObj.getSessionId());
+		mObj.setEventTime( vObj.getEventTime());
+		mObj.setRequestUser( vObj.getRequestUser());
+		mObj.setRequestData( vObj.getRequestData());
+		mObj.setResourcePath( vObj.getResourcePath());
+		mObj.setResourceType(vObj.getResourceType());
+		mObj.setClientIP(vObj.getClientIP());
+		mObj.setClientType(vObj.getClientType());
+		return mObj;
+	}
+
+	protected VXAccessAudit mapEntityToViewBean(VXAccessAudit vObj, XXAccessAudit mObj) {
+		vObj.setAuditType( mObj.getAuditType());
+		vObj.setAccessResult( mObj.getAccessResult());
+		vObj.setAccessType( mObj.getAccessType());
+		vObj.setAclEnforcer( mObj.getAclEnforcer());
+		vObj.setAgentId( mObj.getAgentId());
+		vObj.setPolicyId( mObj.getPolicyId());
+		vObj.setRepoName( mObj.getRepoName());
+		vObj.setRepoType( mObj.getRepoType());
+		vObj.setResultReason( mObj.getResultReason());
+		vObj.setSessionId( mObj.getSessionId());
+		vObj.setEventTime( mObj.getEventTime());
+		vObj.setRequestUser( mObj.getRequestUser());
+		vObj.setRequestData( mObj.getRequestData());
+		vObj.setResourcePath( mObj.getResourcePath());
+		vObj.setResourceType( mObj.getResourceType());
+		vObj.setClientIP( mObj.getClientIP());
+		vObj.setClientType( mObj.getClientType());
+		return vObj;
+	}
+
+	/**
+	 * @param searchCriteria
+	 * @return
+	 */
+	public VXAccessAuditList searchXAccessAudits(SearchCriteria searchCriteria) {
+		VXAccessAuditList returnList = new VXAccessAuditList();
+		List<VXAccessAudit> xAccessAuditList = new ArrayList<VXAccessAudit>();
+
+		List<XXAccessAudit> resultList = (List<XXAccessAudit>)searchResources(searchCriteria,
+				searchFields, sortFields, returnList);
+
+		// Iterate over the result list and create the return list
+		for (XXAccessAudit gjXAccessAudit : resultList) {
+			VXAccessAudit vXAccessAudit = populateViewBean(gjXAccessAudit);
+			xAccessAuditList.add(vXAccessAudit);
+		}
+
+		returnList.setVXAccessAudits(xAccessAuditList);
+		return returnList;
+	}
+	
+	public VXAccessAudit populateViewBean(XXAccessAudit gjXAccessAudit) {
+		VXAccessAudit vXAccessAudit = new VXAccessAudit();
+		return mapEntityToViewBean(vXAccessAudit, gjXAccessAudit);
+	}
+    /*
+	protected List<XXAccessAudit> searchResources(SearchCriteria searchCriteria,
+			List<SearchField> searchFieldList, List<SortField> sortFieldList,
+			VList vList) {
+
+		// Get total count of the rows which meet the search criteria
+		long count = -1;
+		if (searchCriteria.isGetCount()) {
+			count = getCountForSearchQuery(searchCriteria, searchFieldList);
+			if (count == 0) {
+				return Collections.emptyList();
+			}
+		}
+		// construct the sort clause
+		String sortClause = searchUtil.constructSortClause(searchCriteria,
+				sortFieldList);
+
+		String q=queryStr;
+		if(searchCriteria.isDistinct()){
+			q=distinctQueryStr;
+		}
+		// construct the query object for retrieving the data
+		Query query = createQuery(q, sortClause, searchCriteria,
+				searchFieldList, false);
+
+		List<XXAccessAudit> resultList = appDaoMgr.getXXAccessAudit().executeQueryInSecurityContext(
+				XXAccessAudit.class, query);
+
+		if (vList != null) {
+			// Set the meta values for the query result
+			vList.setPageSize(query.getMaxResults());
+			vList.setSortBy(searchCriteria.getSortBy());
+			vList.setSortType(searchCriteria.getSortType());
+			vList.setStartIndex(query.getFirstResult());
+			vList.setTotalCount(count);
+			vList.setResultSize(resultList.size());
+		}
+		return resultList;
+	}
+
+	public VXLong getSearchCount(SearchCriteria searchCriteria,
+			List<SearchField> searchFieldList) {
+		long count = getCountForSearchQuery(searchCriteria, searchFieldList);
+
+		VXLong vXLong = new VXLong();
+		vXLong.setValue(count);
+		return vXLong;
+	}
+
+	protected long getCountForSearchQuery(SearchCriteria searchCriteria,
+			List<SearchField> searchFieldList) {
+
+		String q = countQueryStr;
+		// Get total count of the rows which meet the search criteria
+		if( searchCriteria.isDistinct()) {
+			q = distinctCountQueryStr;
+		}
+		
+		// Get total count of the rows which meet the search criteria
+		Query query = createQuery(q, null, searchCriteria,
+				searchFieldList, true);
+
+		// Make the database call to get the total count
+		Long count = appDaoMgr.getXXAccessAudit().executeCountQueryInSecurityContext(XXAccessAudit.class,
+				query);
+		if (count == null) {
+			// If no data that meets the criteria, return 0
+			return 0;
+		}
+		return count.longValue();
+	}
+
+//	protected Query createQuery(String searchString, String sortString,
+//			SearchCriteria searchCriteria, List<SearchField> searchFieldList,
+//			boolean isCountQuery) {
+//		Query query = searchUtil.createSearchQuery(appDaoMgr.getXXAccessAudit().getEntityManager(), searchString, sortString,
+//				searchCriteria, searchFieldList, isCountQuery);
+//		return query;
+//	}
+*/
+	@Override
+	protected void validateForCreate(VXAccessAudit viewBaseBean) {
+		// TODO Auto-generated method stub
+		
+	}
+
+	@Override
+	protected void validateForUpdate(VXAccessAudit viewBaseBean, XXAccessAudit t) {
+		// TODO Auto-generated method stub
+		
+	}
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-argus/blob/7defc061/security-admin/src/main/java/com/xasecure/service/XAccessAuditServiceBase.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/service/XAccessAuditServiceBase.java b/security-admin/src/main/java/com/xasecure/service/XAccessAuditServiceBase.java
new file mode 100644
index 0000000..d474383
--- /dev/null
+++ b/security-admin/src/main/java/com/xasecure/service/XAccessAuditServiceBase.java
@@ -0,0 +1,104 @@
+package com.xasecure.service;
+/*
+ * Copyright (c) 2014 XASecure
+ * All rights reserved.
+ *
+ * This software is the confidential and proprietary information of
+ * XASecure ("Confidential Information").  You shall not
+ * disclose such Confidential Information and shall use it only in
+ * accordance with the terms of the license agreement you entered into
+ * with XASecure
+ */
+
+/**
+ * 
+ */
+
+import java.util.ArrayList;
+import java.util.List;
+
+import com.xasecure.common.*;
+import com.xasecure.entity.*;
+import com.xasecure.view.*;
+import com.xasecure.service.*;
+
+public abstract class XAccessAuditServiceBase<T extends XXAccessAudit, V extends VXAccessAudit>
+		extends AbstractBaseResourceService<T, V> {
+	public static final String NAME = "XAccessAudit";
+
+	public XAccessAuditServiceBase() {
+
+	}
+
+	@SuppressWarnings("unchecked")
+	@Override
+	protected XXAccessAudit mapViewToEntityBean(VXAccessAudit vObj, XXAccessAudit mObj, int OPERATION_CONTEXT) {
+		mObj.setAuditType( vObj.getAuditType());
+		mObj.setAccessResult( vObj.getAccessResult());
+		mObj.setAccessType( vObj.getAccessType());
+		mObj.setAclEnforcer( vObj.getAclEnforcer());
+		mObj.setAgentId( vObj.getAgentId());
+		mObj.setClientIP( vObj.getClientIP());
+		mObj.setClientType( vObj.getClientType());
+		mObj.setPolicyId( vObj.getPolicyId());
+		mObj.setRepoName( vObj.getRepoName());
+		mObj.setRepoType( vObj.getRepoType());
+		mObj.setResultReason( vObj.getResultReason());
+		mObj.setSessionId( vObj.getSessionId());
+		mObj.setEventTime( vObj.getEventTime());
+		mObj.setRequestUser( vObj.getRequestUser());
+		mObj.setAction( vObj.getAction());
+		mObj.setRequestData( vObj.getRequestData());
+		mObj.setResourcePath( vObj.getResourcePath());
+		mObj.setResourceType( vObj.getResourceType());
+		return mObj;
+	}
+
+	@SuppressWarnings("unchecked")
+	@Override
+	protected VXAccessAudit mapEntityToViewBean(VXAccessAudit vObj, XXAccessAudit mObj) {
+		vObj.setAuditType( mObj.getAuditType());
+		vObj.setAccessResult( mObj.getAccessResult());
+		vObj.setAccessType( mObj.getAccessType());
+		vObj.setAclEnforcer( mObj.getAclEnforcer());
+		vObj.setAgentId( mObj.getAgentId());
+		vObj.setClientIP( mObj.getClientIP());
+		vObj.setClientType( mObj.getClientType());
+		vObj.setPolicyId( mObj.getPolicyId());
+		vObj.setRepoName( mObj.getRepoName());
+		vObj.setRepoType( mObj.getRepoType());
+		vObj.setResultReason( mObj.getResultReason());
+		vObj.setSessionId( mObj.getSessionId());
+		vObj.setEventTime( mObj.getEventTime());
+		vObj.setRequestUser( mObj.getRequestUser());
+		vObj.setAction( mObj.getAction());
+		vObj.setRequestData( mObj.getRequestData());
+		vObj.setResourcePath( mObj.getResourcePath());
+		vObj.setResourceType( mObj.getResourceType());
+		return vObj;
+	}
+
+	/**
+	 * @param searchCriteria
+	 * @return
+	 */
+	public VXAccessAuditList searchXAccessAudits(SearchCriteria searchCriteria) {
+		VXAccessAuditList returnList = new VXAccessAuditList();
+		List<VXAccessAudit> xAccessAuditList = new ArrayList<VXAccessAudit>();
+
+		@SuppressWarnings("unchecked")
+		List<XXAccessAudit> resultList = (List<XXAccessAudit>)searchResources(searchCriteria,
+				searchFields, sortFields, returnList);
+
+		// Iterate over the result list and create the return list
+		for (XXAccessAudit gjXAccessAudit : resultList) {
+			@SuppressWarnings("unchecked")
+			VXAccessAudit vXAccessAudit = populateViewBean((T)gjXAccessAudit);
+			xAccessAuditList.add(vXAccessAudit);
+		}
+
+		returnList.setVXAccessAudits(xAccessAuditList);
+		return returnList;
+	}
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-argus/blob/7defc061/security-admin/src/main/java/com/xasecure/service/XAgentService.java
----------------------------------------------------------------------
diff --git a/security-admin/src/main/java/com/xasecure/service/XAgentService.java b/security-admin/src/main/java/com/xasecure/service/XAgentService.java
new file mode 100644
index 0000000..c423784
--- /dev/null
+++ b/security-admin/src/main/java/com/xasecure/service/XAgentService.java
@@ -0,0 +1,125 @@
+package com.xasecure.service;
+
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.Callable;
+import java.util.concurrent.TimeUnit;
+
+import com.xasecure.common.DateUtil;
+import com.xasecure.common.PropertiesUtil;
+import com.xasecure.common.SearchCriteria;
+import com.xasecure.common.StringUtil;
+
+import org.apache.log4j.Logger;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.context.annotation.Scope;
+import org.springframework.stereotype.Service;
+
+import com.xasecure.common.AppConstants;
+import com.xasecure.common.TimedEventUtil;
+import com.xasecure.view.VXAuditRecord;
+import com.xasecure.view.VXAuditRecordList;
+
+@Service
+@Scope("singleton")
+public class XAgentService {
+
+	@Autowired
+	StringUtil stringUtil;
+
+	@Autowired
+	DateUtil dateUtil;
+	
+	private static Logger logger = Logger.getLogger(XAgentService.class);
+	
+	protected String defaultDBDateFormat="yyyy-MM-dd";
+	protected boolean auditSupported = false;
+	
+	public XAgentService() {
+		defaultDBDateFormat = PropertiesUtil.getProperty(
+				"xa.db.defaultDateformat", defaultDBDateFormat);
+		auditSupported = PropertiesUtil.getBooleanProperty("xa.audit.supported", 
+				false);
+	}
+	
+	private boolean isHDFSLog(String loggerName, int fieldCount) {
+		boolean ret = false ;
+		if (loggerName != null) {
+			ret = loggerName.startsWith("org.") ;
+		}
+		else {
+			ret = (fieldCount == 5) ;
+		}
+		return ret;
+	}
+	
+	private boolean isHiveLog(String loggerName, int fieldCount) {
+		boolean ret = false ;
+		if (loggerName != null) {
+			ret = loggerName.startsWith("com.xasecure.authorization.hive")  || loggerName.startsWith("com.xasecure.pdp.hive.") ;
+		}
+		else {
+			ret = (fieldCount == 11) ;
+		}
+		return ret;
+	}
+
+	private boolean isHBaseLog(String loggerName, int fieldCount) {
+		boolean ret = false ;
+		if (loggerName != null) {
+			ret = loggerName.startsWith("com.xasecure.authorization.hbase") ;
+		}
+		else {
+			ret = ((fieldCount != 5) && (fieldCount != 11)) ;
+		}
+		return ret;
+	}
+
+
+	// The resource type field in the message has "@" at the start
+	// remove and then compare
+	
+	private int getResourceType(String field) {
+		field = field.startsWith("@") ? field.substring(1) : field;
+		
+		int resourceType = AppConstants.RESOURCE_UNKNOWN;
+		if (field.equals("db")) {
+			resourceType = AppConstants.RESOURCE_DB;
+		} else if (field.equals("table")) {
+			resourceType = AppConstants.RESOURCE_TABLE;
+		} else if (field.equals("column")) {
+			resourceType = AppConstants.RESOURCE_COLUMN;
+		}
+		
+		return resourceType;
+	}
+
+	private String bulidWhereClause(SearchCriteria searchCriteria) {
+		StringBuffer whereClause = new StringBuffer();
+		Date startDate = (Date) searchCriteria.getParamValue("startDate");
+		Date endDate = (Date) searchCriteria.getParamValue("endDate");
+
+		if (startDate == null) {
+			startDate = new Date(0);
+		}
+
+		if (endDate == null) {
+			endDate = DateUtil.getUTCDate();
+
+		}
+		String startDateString = DateUtil.dateToString(startDate, defaultDBDateFormat);
+		String endDateString = DateUtil.dateToString(endDate, defaultDBDateFormat);
+		
+		whereClause.append(" DATE(inserted_date)  BETWEEN  '" + startDateString
+				+ "' AND  '" + endDateString + "'");
+		
+		if (whereClause.length() != 0) {
+			return "WHERE " + whereClause.toString();
+		}
+		
+		return "";
+	}
+
+}


Mime
View raw message