ranger-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From omal...@apache.org
Subject [10/44] ARGUS-1. Initial code commit (Selvamohan Neethiraj via omalley)
Date Thu, 14 Aug 2014 20:50:21 GMT
http://git-wip-us.apache.org/repos/asf/incubator-argus/blob/7defc061/security-admin/src/main/webapp/scripts/views/common/FormInputItemList.js
----------------------------------------------------------------------
diff --git a/security-admin/src/main/webapp/scripts/views/common/FormInputItemList.js b/security-admin/src/main/webapp/scripts/views/common/FormInputItemList.js
new file mode 100644
index 0000000..277b2ab
--- /dev/null
+++ b/security-admin/src/main/webapp/scripts/views/common/FormInputItemList.js
@@ -0,0 +1,398 @@
+/*
+ *
+ */
+define(function(require) {
+    'use strict';
+    
+	var Backbone		= require('backbone');
+    var App		        = require('App');
+	var XAEnums			= require('utils/XAEnums');
+	var XAUtil			= require('utils/XAUtils');
+	var localization	= require('utils/XALangSupport');
+	var VXGroup			= require('models/VXGroup');
+	require('bootstrap-editable');
+    	
+	var FormInputItem = Backbone.Marionette.ItemView.extend({
+		_msvName : 'FormInputItem',
+		template : require('hbs!tmpl/common/formInputItem'),
+		tagName : 'tr',
+		templateHelpers : function(){
+			
+			return {
+				permissions 	: _.flatten(_.pick(XAEnums.XAPermType,  XAUtil.getPerms(this.policyType))),
+				policyKnox 		: this.policyType == XAEnums.AssetType.ASSET_KNOX.value ? true :false,
+				policyStorm 	: this.policyType == XAEnums.AssetType.ASSET_STORM.value ? true :false,
+				isModelNew		: !this.model.has('editMode'),
+				stormPerms		: this.stormPermsIds.length == 14 ? _.union(this.stormPermsIds,[-1]) : this.stormPermsIds  
+						
+			};
+		},
+		ui : {
+			selectGroups	: '[data-js="selectGroups"]',
+			inputIPAddress	: '[data-js="ipAddress"]',
+			tags			: '[class=tags]'
+		},
+		events : {
+			'click [data-action="delete"]'	: 'evDelete',
+			'click td'						: 'evClickTD',
+			'change [data-js="selectGroups"]': 'evSelectGroup',
+			'change [data-js="ipAddress"]'	: 'evIPAddress'
+		},
+
+		initialize : function(options) {
+			_.extend(this, _.pick(options, 'groupList','policyType'));
+            //this.subjectList = this.mStudent.getSubjectList();
+			this.stormPermsIds = [];
+			if(this.policyType == XAEnums.AssetType.ASSET_STORM.value){
+				if(this.model.has('editMode') && this.model.get('editMode')){
+					this.stormPermsIds = _.map(this.model.get('_vPermList'), function(p){return p.permType;});
+				}
+			}
+		},
+ 
+		onRender : function() {
+			var that = this;
+			if(!_.isUndefined(this.model.get('groupId'))){
+				this.ui.selectGroups.val(this.model.get('groupId').split(','));
+			}
+			if(!_.isUndefined(this.model.get('ipAddress'))){
+				this.ui.inputIPAddress.val(this.model.get('ipAddress').toString());
+			}
+			
+			this.createGroupDropDown();
+			this.groupDropDownChange();
+			if(this.policyType == XAEnums.AssetType.ASSET_STORM.value){
+				this.renderStormPerms();
+			}
+			else{
+				// TODO FIXME Remove
+				if(this.model.has('editMode') && this.model.get('editMode')){
+					_.each(this.model.get('_vPermList'), function(p){
+						this.$el.find('input[data-id="' + p.permType + '"]').attr('checked', 'checked');
+					},this);
+				}
+			}
+		},
+		groupDropDownChange : function(){
+			var that = this;
+			this.ui.selectGroups.on('change',function(e){
+		//		console.log(e.currentTarget.value);
+				that.checkDirtyFieldForDropDown(e);
+				var duplicateGroupName = false;
+				
+				that.toggleAddButton(e);
+				if(e.removed != undefined){
+					var gIdArr = [],gNameArr = [];
+					gIdArr = _.without(that.model.get('groupId').split(','), e.removed.id);
+					if(that.model.get('groupName') != undefined)
+						gNameArr = _.without(that.model.get('groupName').split(','), e.removed.text);
+					if(!_.isEmpty(gIdArr)){
+						that.model.set('groupId',gIdArr.join(','));
+						that.model.set('groupName',gNameArr.join(','));
+					}else{
+						that.model.unset('groupId');
+						that.model.unset('groupName');
+					}
+					return;
+				}
+				if(!_.isUndefined(e.added)){
+						that.model.set('groupId', e.currentTarget.value);
+				}
+			});
+		},
+		createGroupDropDown :function(){
+			var that = this;
+			if(this.model.has('editMode') && !_.isEmpty(this.ui.selectGroups.val())){
+				var temp = this.ui.selectGroups.val().split(",");
+				_.each(temp , function(id){
+					if(_.isUndefined(that.groupList.get(id))){
+						var group = new VXGroup({id : id});
+						group.fetch({async:false}).done(function(){
+							that.groupList.add(group);
+						});
+					}
+				});
+			}
+			this.groupArr = this.groupList.map(function(m){
+				return { id : m.id+"" , text : m.get('name')};
+			});
+			this.ui.selectGroups.select2({
+				closeOnSelect : true,
+				placeholder : 'Select Group',
+			//	maximumSelectionSize : 1,
+				width :'220px',
+				tokenSeparators: [",", " "],
+				tags : this.groupArr, 
+				initSelection : function (element, callback) {
+					var data = [];
+					console.log(that.groupList);
+					
+					$(element.val().split(",")).each(function () {
+						var obj = _.findWhere(that.groupArr,{id:this});
+					//	if(!_.isUndefined(obj))
+							data.push({id: this, text: obj.text});
+						/*else{
+							var group = new VXGroup({id : this});
+							group.fetch().done(function(){
+									data.push({id: group.id, text: group.get('name')});
+							});
+						}*/
+					});
+					callback(data);
+				},
+				createSearchChoice: function(term, data) {
+				/*	if ($(data).filter(function() {
+						return this.text.localeCompare(term) === 0;
+					}).length === 0) {
+						return {
+							id : term,
+							text: term
+						};
+					}*/
+				},
+				ajax: { 
+					url: "service/xusers/groups",
+					dataType: 'json',
+					data: function (term, page) {
+						return {name : term};
+					},
+					results: function (data, page) { 
+						var results = [] , selectedVals = [];
+						/*if(!_.isEmpty(that.ui.selectGroups.select2('val')))
+							selectedVals = that.ui.selectGroups.select2('val');*/
+						selectedVals = that.getGroupSelectdValues();
+						if(data.resultSize != "0"){
+							//if(data.vXGroups.length > 1){
+
+								results = data.vXGroups.map(function(m, i){	return {id : m.id+"", text: m.name};	});
+								if(!_.isEmpty(selectedVals))
+									results = XAUtil.filterResultByIds(results, selectedVals);
+						//		console.log(results.length);
+								return {results : results};
+							//}
+						//	results = [{id : data.vXGroups.id+"", text: data.vXGroups.name}];
+						//	return {results : results};
+						}
+						return {results : results};
+					}
+				},	
+				formatResult : function(result){
+					return result.text;
+				},
+				formatSelection : function(result){
+					return result.text;
+				},
+				formatNoMatches: function(result){
+					return 'No group found.';
+				}
+			}).on('select2-focus', XAUtil.select2Focus);
+		},
+		getGroupSelectdValues : function(){
+			var vals = [],selectedVals = [];
+			this.collection.each(function(m){
+				if(!_.isUndefined(m.get('groupId'))){
+					vals.push.apply(vals, m.get('groupId').split(','));
+				}
+			});
+			if(!_.isEmpty(this.ui.selectGroups.select2('val')))
+				selectedVals = this.ui.selectGroups.select2('val');
+			vals.push.apply(vals , selectedVals);
+			vals = $.unique(vals);
+			return vals;
+		},
+		evDelete : function(){
+			var that = this;
+			this.collection.remove(this.model);
+			this.toggleAddButton();
+		},
+		evClickTD : function(e){
+			var $el = $(e.currentTarget),permList =[],perms =[];
+			if($(e.toElement).is('td')){
+				var $checkbox = $el.find('input');
+				$checkbox.is(':checked') ? $checkbox.prop('checked',false) : $checkbox.prop('checked',true);
+			}
+			var curPerm = $el.find('input').data('id');
+			var perms = [];
+			if(this.model.has('_vPermList')){
+				if(_.isArray(this.model.get('_vPermList')))
+					perms = this.model.get('_vPermList');
+				else
+					perms.push(this.model.get('_vPermList'));
+			}
+			/* permMapList = [ {id: 18, groupId : 1, permType :5}, {id: 18, groupId : 1, permType :4}, {id: 18, groupId : 2, permType :5} ]
+			   [1] => [ {id: 18, groupId : 1, permType :5}, {id: 19, groupId : 1, permType :4} ]
+			   [2] => [ {id: 20, groupId : 2, permType :5} ]
+			{ 	groupId : 1,
+				_vPermList : [ { id: 18, permType : 5 }, { id: 19, permType : 4 } ]
+			}
+			this.model => { 	groupId : 2,
+				_vPermList : [ { id: 20, permType : 5 }, { permType : 6 } ]
+			}
+			
+			*/
+//			perms = this.model.has('_vPermList') ? this.model.get('_vPermList'): [];
+			
+			if($el.find('input[type="checkbox"]').is(':checked')){
+				perms.push({permType : curPerm});
+				if(curPerm == XAEnums.XAPermType.XA_PERM_TYPE_ADMIN.value){
+					$el.parent().find('input[type="checkbox"]:not(:checked)[data-id!="'+curPerm+'"]').map(function(){
+							perms.push({ permType :$(this).data('id')});
+					    //  return { permType :$(this).data('id')};
+					});
+					$el.parent().find('input[type="checkbox"]').prop('checked',true);
+				}
+			} else {
+				perms = _.reject(perms,function(el) { return el.permType == curPerm; });
+			}
+			
+			this.checkDirtyFieldForCheckBox(perms);
+			if(!_.isEmpty(perms))
+				this.model.set('_vPermList', perms);
+			else 
+				this.model.unset('_vPermList');
+		},
+		checkDirtyFieldForCheckBox : function(perms){
+			var permList = [];
+			if(!_.isUndefined(this.model.get('_vPermList')))
+				permList = _.map(this.model.attributes._vPermList,function(obj){return obj.permType;});
+			perms = _.map(perms,function(obj){return obj.permType;});
+			XAUtil.checkDirtyField(permList, perms, this.$el);
+		},
+		toggleAddButton : function(e){
+			var temp = [];
+			this.collection.each(function(m){
+				if(!_.isUndefined(m.get('groupId'))){
+					temp.push.apply(temp, m.get('groupId').split(','));
+					
+				}
+			});
+			if(!_.isUndefined(e)){
+				if( !_.isUndefined(e.added) && ((temp.length + 1) == this.groupList.length)) 
+					$('[data-action="addGroup"]').hide();
+				if(!_.isUndefined(e.removed))
+					$('[data-action="addGroup"]').show();
+			}else{
+				$('[data-action="addGroup"]').show();
+			}
+		},
+		evIPAddress :function(e){
+			if(!_.isEmpty($(e.currentTarget).val()))
+				this.model.set('ipAddress',$(e.currentTarget).val().split(','));
+			else
+				this.model.unset('ipAddress');
+		},
+		renderStormPerms :function(){
+			var that = this;
+			var permArr = _.pick(XAEnums.XAPermType,  XAUtil.getPerms(this.policyType));
+			this.stormPerms =  _.map(permArr,function(m){return {text:m.label, value:m.value};});
+			this.stormPerms.push({'value' : -1, 'text' : 'Select/Deselect All'});
+			this.ui.tags.editable({
+			    placement: 'right',
+//			    emptytext : 'Please select',
+			    source: this.stormPerms,
+			    display: function(idList,srcData) {
+			    	if(_.isEmpty(idList.toString())){
+			    		$(this).html('');
+			    		return;
+			    	}
+			    	if(!_.isArray(idList))
+			    		idList = [idList];
+//			    	that.checkDirtyFieldForGroup(values);
+			    	var permTypeArr = [];
+		    		var valArr = _.map(idList, function(id){
+		    			if(!(parseInt(id) <= 0)){
+		    				var obj = _.findWhere(srcData,{'value' : parseInt(id)});
+		    				permTypeArr.push({permType : obj.value});
+		    				return "<span class='label label-inverse'>" + obj.text + "</span>";
+		    			}
+		    		});
+		    		that.model.set('_vPermList', permTypeArr);
+		    		$(this).html(valArr.join(" "));
+			    },
+			});
+			this.$('[id^="tags-edit-"]').click(function(e) {
+			    e.stopPropagation();
+			    e.preventDefault();
+			    that.$('#' + $(this).data('editable') ).editable('toggle');
+			    that.$('input[type="checkbox"][value="-1"]').click(function(e){
+					var checkboxlist =$(this).closest('.editable-checklist').find('input[type="checkbox"][value!=-1]')
+					$(this).is(':checked') ? checkboxlist.prop('checked',true) : checkboxlist.prop('checked',false); 
+					
+				});
+			});
+			
+		},
+		checkDirtyFieldForDropDown : function(e){
+			//that.model.has('groupId')
+			var groupIdList =[];
+			if(!_.isUndefined(this.model.get('groupId')))
+				groupIdList = this.model.get('groupId').split(',');
+			XAUtil.checkDirtyField(groupIdList, e.val, $(e.currentTarget));
+		},
+
+	});
+
+
+
+	return Backbone.Marionette.CompositeView.extend({
+		_msvName : 'FormInputItemList',
+		template : require('hbs!tmpl/common/formInputItemList'),
+		//tagName : 'ul', 
+		//className : 'timeline-container',
+		templateHelpers :function(){
+			console.log(XAUtil.getPermHeaders(this.policyType));
+			return {
+				permHeaders : XAUtil.getPermHeaders(this.policyType)
+			};
+		},
+		getItemView : function(item){
+			if(!item){
+				return;
+			}
+			return FormInputItem;
+		},
+		itemViewContainer : ".js-formInput",
+		itemViewOptions : function() {
+			return {
+				'collection' 	: this.collection,
+				'groupList' 	: this.groupList,
+				'policyType'	: this.policyType,
+			};
+		},
+		events : {
+			'click [data-action="addGroup"]' : 'addNew'
+		},
+		initialize : function(options) {
+			_.extend(this, _.pick(options, 'groupList','policyType'));
+			//this.hiveGroupPerm = _.has(options,'hiveGroupPerm') ? true : false;
+			this.listenTo(this.groupList, 'sync', this.render, this);
+			if(this.collection.length == 0)
+				this.collection.add(new Backbone.Model());
+		},
+		onRender : function(){
+			//console.log("onRender of ArtifactFormNoteList called");
+			this.toggleAddButton();
+		},
+		addNew : function(){
+			var that =this;
+			if(this.groupList.length > this.collection.length){
+				this.collection.add(new Backbone.Model());
+				this.toggleAddButton();
+			}
+		},
+		toggleAddButton : function(){
+			var groupIds=[];
+			this.collection.each(function(m){
+				if(!_.isUndefined(m.get('groupId'))){
+					var temp = m.get('groupId').split(',');
+					groupIds.push.apply(groupIds,temp);
+				}
+			});
+			if(groupIds.length == this.groupList.length)
+				this.$('button[data-action="addGroup"]').hide();
+			else
+				this.$('button[data-action="addGroup"]').show();
+		},
+	});
+
+});

http://git-wip-us.apache.org/repos/asf/incubator-argus/blob/7defc061/security-admin/src/main/webapp/scripts/views/common/ProfileBar.js
----------------------------------------------------------------------
diff --git a/security-admin/src/main/webapp/scripts/views/common/ProfileBar.js b/security-admin/src/main/webapp/scripts/views/common/ProfileBar.js
new file mode 100644
index 0000000..9914144
--- /dev/null
+++ b/security-admin/src/main/webapp/scripts/views/common/ProfileBar.js
@@ -0,0 +1,98 @@
+/*
+ * 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.
+ */
+
+define(function(require){
+    'use strict';
+
+	var App				= require('App');
+    var Backbone		= require('backbone');
+	var Communicator	= require('communicator');
+	var SessionMgr 		= require('mgrs/SessionMgr');
+	
+	var ProfileBar_tmpl = require('hbs!tmpl/common/ProfileBar_tmpl'); 
+	
+	var ProfileBar = Backbone.Marionette.ItemView.extend(
+	/** @lends ProfileBar */
+	{
+		_viewName : ProfileBar,
+		
+    	template: ProfileBar_tmpl,
+    	templateHelpers : function(){
+    		return {
+    			userProfile : this.userProfile
+    		};
+    	},
+        
+    	/** ui selector cache */
+    	ui: {
+    		logout : 'a[data-id="logout"]'
+    	},
+
+		/** ui events hash */
+		events: function() {
+			var events = {};
+			//events['change ' + this.ui.input]  = 'onInputChange';
+			events['click ' + this.ui.logout]  = 'onLogout';
+			return events;
+		},
+		onLogout : function(){
+			var url = 'security-admin-web/logout.html';
+			$.ajax({
+				url : url,
+				type : 'GET',
+				headers : {
+					"cache-control" : "no-cache"
+				},
+				success : function() {
+					window.location.replace('login.jsp');
+				},
+				error : function(jqXHR, textStatus, err ) {
+				}
+				
+			});
+		},
+    	/**
+		* intialize a new ProfileBar ItemView 
+		* @constructs
+		*/
+		initialize: function(options) {
+			console.log("initialized a ProfileBar ItemView");
+
+			_.extend(this, _.pick(options, ''));
+
+			this.userProfile = SessionMgr.getUserProfile();
+			this.bindEvents();
+		},
+
+		/** all events binding here */
+		bindEvents : function(){
+			//this.listenTo(this.userProfile, "change", this.render, this);
+			this.listenTo(Communicator.vent,'ProfileBar:rerender', this.render, this);
+		},
+
+		/** on render callback */
+		onRender: function() {
+
+			this.initializePlugins();
+		},
+
+		/** all post render plugin initialization */
+		initializePlugins: function(){
+		},
+
+		/** on close */
+		onClose: function(){
+		}
+
+	});
+
+	return ProfileBar;
+});

http://git-wip-us.apache.org/repos/asf/incubator-argus/blob/7defc061/security-admin/src/main/webapp/scripts/views/common/Spinner.js
----------------------------------------------------------------------
diff --git a/security-admin/src/main/webapp/scripts/views/common/Spinner.js b/security-admin/src/main/webapp/scripts/views/common/Spinner.js
new file mode 100644
index 0000000..7daa858
--- /dev/null
+++ b/security-admin/src/main/webapp/scripts/views/common/Spinner.js
@@ -0,0 +1,81 @@
+/*
+ * 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.
+ */
+
+define(function(require){
+    'use strict';
+
+	var Backbone		= require('backbone');
+	var Handlebars		= require('handlebars');
+	var Communicator	= require('communicator');
+
+	
+	var Spinner = Backbone.Marionette.Layout.extend(
+	/** @lends Spinner */
+	{
+		_viewName : 'Spinner',
+		
+		template  : Handlebars.compile("<span></span>"),
+
+		tagName	  : 'span',
+        
+    	/** ui selector cache */
+    	ui: {},
+
+		/** ui events hash */
+		events: function() {
+			var events = {};
+			//events['change ' + this.ui.input]  = 'onInputChange';
+			return events;
+		},
+
+    	/**
+		* intialize a new Spinner Layout 
+		* @constructs
+		*/
+		initialize: function(options) {
+			console.log("initialized a Spinner ItemView");
+
+			_.extend(this, _.pick(options, 'collection'));
+
+			this.bindEvents();
+		},
+
+		/** all events binding here */
+		bindEvents : function(){
+            this.listenTo(this.collection, 'request', this.displaySpinner);
+            this.listenTo(this.collection, 'sync error', this.removeSpinner);
+		},
+
+		/** on render callback */
+		onRender: function() {
+			this.initializePlugins();
+		},
+
+		/** all post render plugin initialization */
+		initializePlugins: function(){
+		},
+
+		displaySpinner: function () {
+            this.$el.empty().append('<i class="icon-spinner icon-spin icon-3x white spin-position"></i>');
+        },
+
+        removeSpinner: function () {
+            this.$el.empty();
+        },
+		
+		/** on close */
+		onClose: function(){
+		}
+
+	});
+
+	return Spinner;
+});

http://git-wip-us.apache.org/repos/asf/incubator-argus/blob/7defc061/security-admin/src/main/webapp/scripts/views/common/TopNav.js
----------------------------------------------------------------------
diff --git a/security-admin/src/main/webapp/scripts/views/common/TopNav.js b/security-admin/src/main/webapp/scripts/views/common/TopNav.js
new file mode 100644
index 0000000..7d60ff7
--- /dev/null
+++ b/security-admin/src/main/webapp/scripts/views/common/TopNav.js
@@ -0,0 +1,88 @@
+/*
+ * 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.
+ */
+
+define(function(require){
+    'use strict';
+
+	var Backbone		= require('backbone');
+
+	var TopNav_tmpl = require('hbs!tmpl/common/TopNav_tmpl'); 
+	require('jquery.cookie');
+	var TopNav = Backbone.Marionette.ItemView.extend(
+	/** @lends TopNav */
+	{
+		_viewName : TopNav,
+		
+    	template: TopNav_tmpl,
+    	templateHelpers : function(){
+    		
+    	},
+        
+    	/** ui selector cache */
+    	ui: {},
+
+		/** ui events hash */
+		events: function() {
+			var events = {};
+			//events['change ' + this.ui.input]  = 'onInputChange';
+			events['click li']  = 'onNavMenuClick';
+			return events;
+		},
+
+    	/**
+		* intialize a new TopNav ItemView 
+		* @constructs
+		*/
+		initialize: function(options) {
+			console.log("initialized a TopNav ItemView");
+			_.extend(this, _.pick(options, ''));
+			this.bindEvents();
+			this.appState = options.appState;
+        	this.appState.on('change:currentTab', this.highlightNav,this);
+		},
+
+		/** all events binding here */
+		bindEvents : function(){
+			/*this.listenTo(this.model, "change:foo", this.modelChanged, this);*/
+			/*this.listenTo(communicator.vent,'someView:someEvent', this.someEventHandler, this)'*/
+		},
+
+		/** on render callback */
+		onRender: function() {
+			var that = this;
+			this.initializePlugins();
+			$('.page-logo').on('click',function(){
+				that.$('ul li').removeClass('active');
+				that.$('ul li:first').addClass('active');
+			});
+			$.cookie('clientTimeOffset', new Date().getTimezoneOffset());
+		},
+
+		/** all post render plugin initialization */
+		initializePlugins: function(){
+		},
+		onNavMenuClick : function(e){
+			var ele = $(e.currentTarget);
+			this.$('ul li').removeClass('active');
+			ele.addClass('active');
+		},
+		highlightNav : function(e){
+			this.$('ul li').removeClass('active');
+        	this.$('#nav' + this.appState.get('currentTab')).parent().addClass('active');
+        },
+		/** on close */
+		onClose: function(){
+		}
+
+	});
+
+	return TopNav;
+});

http://git-wip-us.apache.org/repos/asf/incubator-argus/blob/7defc061/security-admin/src/main/webapp/scripts/views/common/UserPermissionList.js
----------------------------------------------------------------------
diff --git a/security-admin/src/main/webapp/scripts/views/common/UserPermissionList.js b/security-admin/src/main/webapp/scripts/views/common/UserPermissionList.js
new file mode 100644
index 0000000..f6bea49
--- /dev/null
+++ b/security-admin/src/main/webapp/scripts/views/common/UserPermissionList.js
@@ -0,0 +1,399 @@
+/*
+ * 
+ */
+define(function(require) {
+    'use strict';
+    
+	var Backbone	= require('backbone');
+    	var App         = require('App');
+	var XAEnums		= require('utils/XAEnums');
+	var XAUtil			= require('utils/XAUtils');
+	var localization	= require('utils/XALangSupport');
+	var VXUser		= require('models/VXUser');
+	require('bootstrap-editable');
+    	
+	var UserPermissionItem = Backbone.Marionette.ItemView.extend({
+		_msvName : 'UserPermissionItem',
+		template : require('hbs!tmpl/common/UserPermissionItem'),
+		tagName : 'tr',
+		templateHelpers : function(){
+						
+			return {
+			   permissions 		: _.flatten(_.pick(XAEnums.XAPermType,  XAUtil.getPerms(this.policyType))),
+			   policyKnox 		: this.policyType == XAEnums.AssetType.ASSET_KNOX.value ? true :false,
+			   policyStorm 		: this.policyType == XAEnums.AssetType.ASSET_STORM.value ? true :false,
+			   isModelNew		: !this.model.has('editMode'),
+			   stormPerms		: this.stormPermsIds.length == 14 ? _.union(this.stormPermsIds,[-1]) : this.stormPermsIds
+			};
+		},
+		ui : {
+			selectUsers		: '[data-js="selectUsers"]',
+			inputIPAddress	: '[data-js="ipAddress"]',
+			tags			: '[class=tags]'
+		},
+		events : {
+			'click [data-action="delete"]'	: 'evDelete',
+			'click td'						: 'evClickTD',
+			'change [data-js="selectUsers"]': 'evSelectUser',
+			'change [data-js="ipAddress"]'	: 'evIPAddress'
+		},
+
+		initialize : function(options) {
+			_.extend(this, _.pick(options, 'userList','policyType'));
+            //this.subjectList = this.mStudent.getSubjectList();
+			this.stormPermsIds = [];
+			if(this.policyType == XAEnums.AssetType.ASSET_STORM.value){
+				if(this.model.has('editMode') && this.model.get('editMode')){
+					this.stormPermsIds = _.map(this.model.get('_vPermList'), function(p){return p.permType;});
+				}
+			}
+		},
+ 
+		onRender : function() {
+			var that = this;
+			
+			if(this.model.get('userName') != undefined){
+				this.ui.selectUsers.val(this.model.get('userId').split(','));
+			}
+			if(!_.isUndefined(this.model.get('ipAddress'))){
+				this.ui.inputIPAddress.val(this.model.get('ipAddress').toString());
+			}
+			
+			if(this.policyType == XAEnums.AssetType.ASSET_STORM.value)
+				this.renderStormPerms();
+			else{
+				// TODO FIXME Remove
+				if(this.model.has('editMode') && this.model.get('editMode')){
+					_.each(this.model.get('_vPermList'), function(p){
+						this.$el.find('input[data-id="' + p.permType + '"]').attr('checked', 'checked');
+					},this);
+				}
+			}
+			
+			this.createSelectUserDropDown();
+			this.userDropDownChange();
+		},
+		checkDirtyFieldForDropDown : function(e){
+			//that.model.has('groupId')
+			var userIdList =[];
+			if(!_.isUndefined(this.model.get('userId')))
+				userIdList = this.model.get('userId').split(',');
+			XAUtil.checkDirtyField(userIdList, e.val, $(e.currentTarget));
+		},
+		toggleAddButton : function(e){
+			var temp = [];
+			this.collection.each(function(m){
+				if(!_.isUndefined(m.get('userId'))){
+					temp.push.apply(temp, m.get('userId').split(','));
+					
+				}
+			});
+			if(!_.isUndefined(e)){
+				if( !_.isUndefined(e.added) && ((temp.length + 1) == this.userList.length)) 
+					$('[data-action="addUser"]').hide();
+				if(!_.isUndefined(e.removed))
+					$('[data-action="addUser"]').show();
+			}else{
+				$('[data-action="addUser"]').show();
+			}
+		},
+		evDelete : function(){
+			var that = this;
+			this.collection.remove(this.model);
+			this.toggleAddButton();
+		},
+		evClickTD : function(e){
+			var $el = $(e.currentTarget),permList =[],perms =[];
+			if($(e.toElement).is('td')){
+				var $checkbox = $el.find('input');
+				$checkbox.is(':checked') ? $checkbox.prop('checked',false) : $checkbox.prop('checked',true);  
+			}
+			var curPerm = $el.find('input').data('id');
+			var perms = [];
+			if(this.model.has('_vPermList')){
+				if(_.isArray(this.model.get('_vPermList')))
+					perms = this.model.get('_vPermList');
+				else
+					perms.push(this.model.get('_vPermList'));
+			}
+				
+			
+			/* permMapList = [ {id: 18, groupId : 1, permType :5}, {id: 18, groupId : 1, permType :4}, {id: 18, groupId : 2, permType :5} ]
+			   [1] => [ {id: 18, groupId : 1, permType :5}, {id: 19, groupId : 1, permType :4} ]
+			   [2] => [ {id: 20, groupId : 2, permType :5} ]
+			{ 	groupId : 1,
+				_vPermList : [ { id: 18, permType : 5 }, { id: 19, permType : 4 } ]
+			}
+			this.model => { 	groupId : 2,
+				_vPermList : [ { id: 20, permType : 5 }, { permType : 6 } ]
+			}
+			
+			*/
+			
+//			perms = this.model.has('_vPermList') ? this.model.get('_vPermList'): [];
+			
+			if($el.find('input[type="checkbox"]').is(':checked')){
+				perms.push({permType : curPerm});
+				if(curPerm == XAEnums.XAPermType.XA_PERM_TYPE_ADMIN.value){
+					$el.parent().find('input[type="checkbox"]:not(:checked)[data-id!="'+curPerm+'"]').map(function(){
+							perms.push({ permType :$(this).data('id')});
+					   //   return { permType :$(this).data('id')};
+					});
+				//	this.model.set('_vPermList', perms);
+					$el.parent().find('input[type="checkbox"]').prop('checked',true);
+				}
+			} else {
+				perms = _.reject(perms,function(el) { return el.permType == curPerm; });
+
+				//perms = _.without(perms, curPerm);
+				
+			}
+			this.checkDirtyFieldForCheckBox(perms);
+			if(!_.isEmpty(perms)){
+				this.model.set('_vPermList', perms);
+			} else {
+				this.model.unset('_vPermList');
+			}
+		},
+		checkDirtyFieldForCheckBox : function(perms){
+			var permList = [];
+			if(!_.isUndefined(this.model.get('_vPermList')))
+				permList = _.map(this.model.attributes._vPermList,function(obj){return obj.permType;});
+			perms = _.map(perms,function(obj){return obj.permType;});
+			XAUtil.checkDirtyField(permList, perms, this.$el);
+		},
+		createSelectUserDropDown :function(){
+			var that = this;
+			if(this.model.has('editMode') && !_.isEmpty(this.ui.selectUsers.val())){
+				var temp = this.ui.selectUsers.val().split(",");
+				_.each(temp , function(id){
+					if(_.isUndefined(that.userList.get(id))){
+						var user = new VXUser({id : id});
+						user.fetch({async:false}).done(function(){
+							that.userList.add(user);
+						});
+					}
+				});
+			}
+			this.userArr = this.userList.map(function(m){
+				return { id : m.id+"" , text : m.get('name')};
+			});
+			this.ui.selectUsers.select2({
+				closeOnSelect : true,
+				placeholder : 'Select User',
+		//		maximumSelectionSize : 1,
+				width :'220px',
+				tokenSeparators: [",", " "],
+				tags : this.userArr, 
+				initSelection : function (element, callback) {
+					var data = [];
+					$(element.val().split(",")).each(function () {
+						var obj = _.findWhere(that.userArr,{id:this});	
+						data.push({id: this, text: obj.text});
+					});
+					callback(data);
+				},
+				createSearchChoice: function(term, data) {
+					/*if ($(data).filter(function() {
+						return this.text.localeCompare(term) === 0;
+						//return this.value == (term) ?  true : false;
+					}).length === 0) {
+						return {
+							id : term,
+							text: term
+						};
+					}*/
+				},
+				ajax: { 
+					url: "service/xusers/users",
+					dataType: 'json',
+					data: function (term, page) {
+						return {name : term};
+					},
+					results: function (data, page) { 
+						var results = [],selectedVals=[];
+						/*if(!_.isEmpty(that.ui.selectUsers.select2('val')))
+							selectedVals = that.ui.selectUsers.select2('val');
+						selectedVals.push.apply(selectedVals, that.getUsersSelectdValues());
+						selectedVals = $.unique(selectedVals);*/
+						selectedVals = that.getUsersSelectdValues();
+						if(data.resultSize != "0"){
+							//if(data.vXUsers.length > 1){
+
+								results = data.vXUsers.map(function(m, i){	return {id : m.id+"", text: m.name};	});
+								if(!_.isEmpty(selectedVals))
+									results = XAUtil.filterResultByIds(results, selectedVals);
+								//console.log(results.length);
+								return {results : results};
+						//	}
+						//	results = [{id : data.vXUsers.id+"", text: data.vXUsers.name}];
+						//	return {results : results};
+						}
+						return {results : results};
+					}
+				},	
+				formatResult : function(result){
+					return result.text;
+				},
+				formatSelection : function(result){
+					return result.text;
+				},
+				formatNoMatches: function(result){
+					return 'No user found.';
+				}
+				
+			}).on('select2-focus', XAUtil.select2Focus);
+		},
+		userDropDownChange : function(){
+			var that = this;
+			this.ui.selectUsers.on('change',function(e){
+				//	console.log(e.currentTarget.value);
+					that.checkDirtyFieldForDropDown(e);
+					that.toggleAddButton(e);
+					var duplicateUsername = false;
+					if(e.removed != undefined){
+						var gIdArr = [],gNameArr = [];
+						gIdArr = _.without(that.model.get('userId').split(','), e.removed.id);
+						if(that.model.get('userName') != undefined)
+							gNameArr = _.without(that.model.get('userName').split(','), e.removed.text);
+						if(!_.isEmpty(gIdArr)){
+							that.model.set('userId',gIdArr.join(','));
+							that.model.set('userName',gNameArr.join(','));
+						}else{
+							that.model.unset('userId');
+							that.model.unset('userName');
+						}
+						return;
+						
+					}
+					if(!_.isUndefined(e.added)){
+							that.model.set('userId', e.currentTarget.value);
+					}
+				});
+		},
+		getUsersSelectdValues : function(){
+			var vals = [],selectedVals = [];
+			this.collection.each(function(m){
+				if(!_.isUndefined(m.get('userId'))){
+					vals.push.apply(vals, m.get('userId').split(','));
+				}
+			});
+			if(!_.isEmpty(this.ui.selectUsers.select2('val')))
+				selectedVals = this.ui.selectUsers.select2('val');
+			vals.push.apply(vals , selectedVals);
+			vals = $.unique(vals);
+			return vals;
+		},
+		evIPAddress :function(e){
+			if(!_.isEmpty($(e.currentTarget).val()))
+				this.model.set('ipAddress',$(e.currentTarget).val().split(','));
+			else
+				this.model.unset('ipAddress');
+		},
+		renderStormPerms :function(){
+			var that = this;
+			var permArr = _.pick(XAEnums.XAPermType,  XAUtil.getPerms(this.policyType));
+			this.stormPerms =  _.map(permArr,function(m){return {text:m.label, value:m.value};});
+			this.stormPerms.push({'value' : -1, 'text' : 'Select/Deselect All'});
+			this.ui.tags.editable({
+			    placement: 'right',
+//			    emptytext : 'Please select',
+			    source: this.stormPerms,
+			    display: function(idList,srcData) {
+			    	if(_.isEmpty(idList.toString())){
+			    		$(this).html('');
+			    		return;
+			    	}
+			    	if(!_.isArray(idList))
+			    		idList = [idList];
+//			    	that.checkDirtyFieldForGroup(values);
+			    	var permTypeArr = [];
+		    		var valArr = _.map(idList, function(id){
+		    			if(!(parseInt(id) <= 0)){
+			    			var obj = _.findWhere(srcData,{'value' : parseInt(id)});
+			    			permTypeArr.push({permType : obj.value});
+			    			return "<span class='label label-inverse'>" + obj.text + "</span>";
+		    			}
+		    		});
+		    		that.model.set('_vPermList', permTypeArr);
+		    		$(this).html(valArr.join(" "));
+			    },
+			});
+			this.$('[id^="tags-edit-"]').click(function(e) {
+			    e.stopPropagation();
+			    e.preventDefault();
+			    that.$('#' + $(this).data('editable') ).editable('toggle');
+			    that.$('input[type="checkbox"][value="-1"]').click(function(e){
+					var checkboxlist =$(this).closest('.editable-checklist').find('input[type="checkbox"][value!=-1]');
+					$(this).is(':checked') ? checkboxlist.prop('checked',true) : checkboxlist.prop('checked',false); 
+					
+				});
+			});
+		},
+
+	});
+
+
+
+	return Backbone.Marionette.CompositeView.extend({
+		_msvName : 'UserPermissionList',
+		template : require('hbs!tmpl/common/UserPermissionList'),
+		//tagName : 'ul', 
+		//className : 'timeline-container',
+		templateHelpers :function(){
+			return {
+				permHeaders : XAUtil.getPermHeaders(this.policyType,false)
+			};
+		},
+		getItemView : function(item){
+			if(!item){
+				return;
+			}
+			return UserPermissionItem;
+		},
+		itemViewContainer : ".js-formInput",
+		itemViewOptions : function() {
+			return {
+				'collection' : this.collection,
+				'userList' : this.userList,
+				'policyType'	: this.policyType,
+			};
+		},
+		events : {
+			'click [data-action="addUser"]' : 'addNew'
+		},
+		initialize : function(options) {
+			_.extend(this, _.pick(options, 'userList','policyType'));
+			//this.listenTo(this.collection, 'removeAddBtn', this.render, this);
+			/*if(options.model.isNew())
+				this.collection.add(new Backbone.Model());*/
+			if(this.collection.length == 0)
+				this.collection.add(new Backbone.Model());
+				
+		},
+		onRender : function(){
+			//console.log("onRender of ArtifactFormNoteList called");
+			this.toggleAddButton();
+		},
+		addNew : function(){
+			var that =this;
+			this.collection.add(new Backbone.Model());
+			this.toggleAddButton();
+		},
+		toggleAddButton : function(){
+			var userIds=[];
+			this.collection.each(function(m){
+				if(!_.isUndefined(m.get('userId'))){
+					var temp = m.get('userId').split(',');
+					userIds.push.apply(userIds,temp);
+				}
+			});
+			if(userIds.length == this.userList.length)
+				this.$('button[data-action="addUser"]').hide();
+			else
+				this.$('button[data-action="addUser"]').show();
+		}
+	
+	});
+
+});

http://git-wip-us.apache.org/repos/asf/incubator-argus/blob/7defc061/security-admin/src/main/webapp/scripts/views/common/XABackgrid.js
----------------------------------------------------------------------
diff --git a/security-admin/src/main/webapp/scripts/views/common/XABackgrid.js b/security-admin/src/main/webapp/scripts/views/common/XABackgrid.js
new file mode 100644
index 0000000..0ff4452
--- /dev/null
+++ b/security-admin/src/main/webapp/scripts/views/common/XABackgrid.js
@@ -0,0 +1,387 @@
+/*
+ * 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.
+ */
+
+define(function(require){
+    'use strict';
+
+	var Backbone		= require('backbone');
+	var Communicator	= require('communicator');
+	var XAUtil			= require('utils/XAUtils');
+	var XAGlobals 	= require('utils/XAGlobals');
+
+	require('backgrid-filter');
+	require('backgrid-paginator');
+	require('select2');
+
+
+	var HeaderSearchCell = Backbone.View.extend({
+
+		tagName: "td",
+
+		className: "backgrid-filter",
+
+		template: _.template('<input type="search" <% if (placeholder) { %> placeholder="<%- placeholder %>" <% } %> name="<%- name %>" <% if (style) { %> style="<%- style %>" <% } %> />'),
+							 //<a class="clear" href="#">&times;</a>'),
+
+		placeholder: "",
+
+		events: {
+			"keyup input": "evKeyUp",
+			"submit": "search"
+		},
+
+		initialize: function (options) {
+			_.extend(this, _.pick(options, 'column'));
+			this.name = this.column.get('name');
+			if(this.column.get('reName') != undefined)
+				this.name = this.column.get('reName');
+				
+
+			var collection = this.collection, self = this;
+			if (Backbone.PageableCollection && collection instanceof Backbone.PageableCollection ) {
+				collection.queryParams[this.name] = function () {
+					return self.searchBox().val() || null;
+				};
+			}
+		},
+
+		render: function () {
+			this.$el.empty().append(this.template({
+				name: this.column.get('name'),
+				placeholder: this.column.get('placeholder') || "Search",
+				style : this.column.get('headerSearchStyle')
+			}));
+			this.$el.addClass('renderable');
+			this.delegateEvents();
+			return this;
+
+		},
+
+		evKeyUp: function (e) {
+			var $clearButton = this.clearButton();
+			var searchTerms = this.searchBox().val();
+
+	      //  if(e.which === XAGlobals.keys.ENTER_KEY ){
+			if(!e.shiftKey)
+				this.search();
+		//	}
+			
+			if (searchTerms) {
+				$clearButton.show();
+			} else {
+				$clearButton.hide();
+			}
+		},
+
+		searchBox: function () {
+			return this.$el.find("input[type=search]");
+		},
+
+		clearButton: function () {
+			return this.$el.find(".clear");
+		},
+
+		search: function () {
+
+			var data = {};
+
+			// go back to the first page on search
+			var collection = this.collection;
+			if (Backbone.PageableCollection &&
+				collection instanceof Backbone.PageableCollection &&
+					collection.mode == "server") {
+				collection.state.currentPage = collection.state.firstPage;
+			}
+			var query = this.searchBox().val();
+			if (query) data[this.name] = query;
+			if(collection.extraSearchParams){
+				_.extend(data, collection.extraSearchParams);
+			}
+			collection.fetch({
+				data: data,
+				reset: true,
+				success : function(){},
+				error  : function(msResponse){
+					XAUtil.notifyError('Error', 'Invalid input data!');
+				}
+			});
+		},
+
+		clear: function (e) {
+			if (e) e.preventDefault();
+			this.searchBox().val(null);
+			this.collection.fetch({reset: true});
+		}
+
+	});
+	
+	var HeaderMultiSelectSearchCell = Backbone.View.extend({
+
+		tagName: "td",
+
+		className: "backgrid-filter",
+
+		template: _.template('<input type="search" name="<%- name %>" />'),
+							 //<a class="clear" href="#">&times;</a>'),
+
+		placeholder: "",
+
+		events: {
+			"change input": "evKeyUp",
+			"submit": "search"
+		},
+
+		initialize: function (options) {
+			_.extend(this, _.pick(options, 'column'));
+			this.name = this.column.get('name');
+			if(this.column.get('reName') != undefined)
+				this.name = this.column.get('reName');
+				
+			this.pluginAttr = this.column.has('optSelect2') ? this.column.get('optSelect2') : {};
+			var collection = this.collection, self = this;
+			if (Backbone.PageableCollection && collection instanceof Backbone.PageableCollection ) {
+				collection.queryParams[this.name] = function () {
+					return self.searchBox().val() || null;
+				};
+			}
+		},
+
+		render: function () {
+			this.$el.empty().append(this.template({
+				name: this.column.get('name'),
+				style : this.column.get('headerSearchStyle')
+			}));
+			this.$el.find('input').select2(this.pluginAttr);
+			this.$el.addClass('renderable');
+			this.delegateEvents();
+			return this;
+
+		},
+
+		evKeyUp: function (e) {
+			var $clearButton = this.clearButton();
+			var searchTerms = this.searchBox().val();
+
+	      //  if(e.which === XAGlobals.keys.ENTER_KEY ){
+			if(!e.shiftKey)
+				this.search();
+		//	}
+			
+			if (searchTerms) {
+				$clearButton.show();
+			} else {
+				$clearButton.hide();
+			}
+		},
+
+		searchBox: function () {
+			return this.$el.find("input[type=search]");
+		},
+
+		clearButton: function () {
+			return this.$el.find(".clear");
+		},
+
+		search: function () {
+
+			var data = {};
+
+			// go back to the first page on search
+			var collection = this.collection;
+			if (Backbone.PageableCollection &&
+				collection instanceof Backbone.PageableCollection &&
+					collection.mode == "server") {
+				collection.state.currentPage = collection.state.firstPage;
+			}
+			var query = this.searchBox().val();
+			if (query) data[this.name] = query;
+			if(collection.extraSearchParams){
+				_.extend(data, collection.extraSearchParams);
+			}
+			collection.fetch({
+				data: data,
+				reset: true,
+				success : function(){},
+				error  : function(msResponse){
+					XAUtil.notifyError('Error', 'Invalid input data!');
+				}
+			});
+		},
+
+		clear: function (e) {
+			if (e) e.preventDefault();
+			this.searchBox().val(null);
+			this.collection.fetch({reset: true});
+		}
+
+	});
+	
+	
+	var HeaderFilterCell = Backbone.View.extend({
+
+		tagName: "td",
+
+		className: "backgrid-filter",
+
+		template: _.template('<select >  <option>ALL</option>\
+				 				<% _.each(list, function(data) {\
+				 						if(_.isObject(data)){ %>\
+				 							<option value="<%= data.value %>"><%= data.label %></option>\
+				 						<% }else{ %>\
+												<option value="<%= data %>"><%= data %></option>\
+				 						<% } %>\
+				 				<% }); %></select>') ,
+					 
+		placeholder: "",
+
+		events: {
+			"click": function(){
+			}
+		},
+
+		initialize: function (options) {
+			_.extend(this, _.pick(options, 'column'));
+			this.name = this.column.get('name');
+			this.headerFilterOptions = this.column.get('headerFilterOptions');
+		},
+
+		render: function () {
+			var that =this;
+			this.$el.empty().append(this.template({
+				name: this.column.get('name'),
+				list : this.headerFilterOptions.filterList
+			}));
+			
+			this.$el.find('select').select2({
+				allowClear: true,
+				closeOnSelect : false,
+				width : this.headerFilterOptions.filterWidth || '100%' ,
+				height : this.headerFilterOptions.filterHeight || '20px'
+			});
+			
+			this.$el.addClass('renderable');
+			
+			this.$el.find('select').on('click',function(e){
+				that.search(e.currentTarget.value);
+			});
+			//this.delegateEvents();
+			return this;
+
+		},
+
+		
+
+		search: function (selectedOptionValue) {
+
+			var data = {};
+
+			// go back to the first page on search
+			var collection = this.collection;
+			if (Backbone.PageableCollection &&
+				collection instanceof Backbone.PageableCollection &&
+					collection.mode == "server") {
+				collection.state.currentPage = collection.state.firstPage;
+			}
+			if(selectedOptionValue != "ALL") var query = selectedOptionValue;
+			if (query) data[this.name] = query;
+			if(collection.extraSearchParams){
+				_.extend(data, collection.extraSearchParams);
+			}
+			collection.fetch({data: data, reset: true});
+		}
+
+		/*clear: function (e) {
+			if (e) e.preventDefault();
+			this.searchBox().val(null);
+			this.collection.fetch({reset: true});
+		}*/
+
+	});
+
+	
+	
+	var HeaderRow = Backgrid.Row.extend({
+
+		requiredOptions: ["columns", "collection"],
+
+		initialize: function () {
+			Backgrid.Row.prototype.initialize.apply(this, arguments);
+		},
+
+		makeCell: function (column, options) {
+			var headerCell;
+			switch(true){
+				case (column.has('canHeaderSearch') && column.get('canHeaderSearch') === true) :
+					headerCell = new HeaderSearchCell({
+						column		: column,
+						collection	: this.collection
+					});
+					break;
+				case (column.has('canHeaderMultiSelectSearch') && column.get('canHeaderMultiSelectSearch') === true) :
+					headerCell = new HeaderMultiSelectSearchCell({
+						column		: column,
+						collection	: this.collection
+					});
+					break;	
+				case (column.has('canHeaderFilter') && column.get('canHeaderFilter') === true) :
+					headerCell = new HeaderFilterCell({
+						column		: column,
+						collection	: this.collection
+					});
+					break;
+				default :
+					headerCell = new Backbone.View({
+						tagName : 'td'
+					});
+			}
+			return headerCell;
+		}
+
+	});
+
+
+
+	var XAHeader = Backgrid.Header.extend({
+
+		initialize: function (options) {
+			var args = Array.prototype.slice.apply(arguments);
+			Backgrid.Header.prototype.initialize.apply(this, args);
+
+			this.searchRow = new HeaderRow({
+				columns: this.columns,
+				collection: this.collection
+			});
+		},
+
+		/**
+		  Renders this table head with a single row of header cells.
+		  */
+		render: function () {
+			var args = Array.prototype.slice.apply(arguments);
+			Backgrid.Header.prototype.render.apply(this, args);
+
+			this.$el.append(this.searchRow.render().$el);
+			return this;
+		},
+
+		remove: function () {
+			var args = Array.prototype.slice.apply(arguments);
+			Backgrid.Header.prototype.remove.apply(this, args);
+
+			this.searchRow.remove.apply(this.searchRow, arguments);
+			return Backbone.View.prototype.remove.apply(this, arguments);
+		}
+
+	});
+
+
+	return XAHeader;
+});

http://git-wip-us.apache.org/repos/asf/incubator-argus/blob/7defc061/security-admin/src/main/webapp/scripts/views/common/XATableLayout.js
----------------------------------------------------------------------
diff --git a/security-admin/src/main/webapp/scripts/views/common/XATableLayout.js b/security-admin/src/main/webapp/scripts/views/common/XATableLayout.js
new file mode 100644
index 0000000..64a07b1
--- /dev/null
+++ b/security-admin/src/main/webapp/scripts/views/common/XATableLayout.js
@@ -0,0 +1,183 @@
+/*
+ * 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.
+ */
+
+define(function(require){
+    'use strict';
+
+	var Backbone		= require('backbone');
+	var Communicator	= require('communicator');
+	var XAEnums 		= require('utils/XAEnums');
+	var XALinks 		= require('modules/XALinks');
+	var XAGlobals 		= require('utils/XAGlobals');
+	var localization	= require('utils/XALangSupport');
+	
+	var XATablelayoutTmpl = require('hbs!tmpl/common/XATableLayout_tmpl');
+	var Spinner		= require('views/common/Spinner');
+
+	require('backgrid-filter');
+	require('backgrid-paginator');
+
+	var XATableLayout = Backbone.Marionette.Layout.extend(
+	/** @lends XATableLayout */
+	{
+		_viewName : 'XATableLayout',
+		
+    	template: XATablelayoutTmpl,
+
+		/** Layout sub regions */
+    	regions: {
+			'rTableList'	: 'div[data-id="r_tableList"]',
+			'rTableSpinner'	: 'div[data-id="r_tableSpinner"]',
+			'rPagination'	: 'div[data-id="r_pagination"]'
+		},
+
+    	// /** ui selector cache */
+    	ui: {},
+
+		gridOpts : {
+			className: 'table table-bordered table-condensed backgrid',
+			emptyText : 'No Records found!'
+		},
+
+		filterOpts : {
+			placeholder: localization.tt('plcHldr.searchByResourcePath'),
+			wait: 150
+		},
+
+		includePagination : true,
+
+		includeFilter : false,
+
+		includeHeaderSearch : false,
+
+		/** ui events hash */
+		events: function() {
+			var events = {};
+			//events['change ' + this.ui.input]  = 'onInputChange';
+			return events;
+		},
+
+    	/**
+		* intialize a new HDXATableLayout Layout 
+		* @constructs
+		*/
+		initialize: function(options) {
+			console.log("initialized a XATableLayout Layout");
+			/*
+			 * mandatory :
+			 * collection
+			 * columns,
+			 *
+			 * optional :
+			 * includePagination (true),
+			 * includeFilter (false),
+			 * includeHeaderSearch (false),
+			 * gridOpts : {
+			 * 	className: 'table table-bordered table-condensed backgrid',
+			 *  row: TableRow,
+			 *  header : XABackgrid,
+			 *  emptyText : 'No Records found!',
+			 * }
+			 * filterOpts : {
+			 *	name: ['name'],
+			 *  placeholder: localization.tt('plcHldr.searchByResourcePath'),
+			 *  wait: 150
+			 * }
+			 *
+			 */
+			_.extend(this, _.pick(options,	'collection', 'columns', 'includePagination', 
+											'includeHeaderSearch', 'includeFilter' ,'scrollToTop', 'paginationCache'));
+
+			_.extend(this.gridOpts, options.gridOpts, { collection : this.collection, columns : this.columns } );
+			_.extend(this.filterOpts, options.filterOpts);
+			
+			this.scrollToTop = _.has(options, 'scrollToTop') ? options.scrollToTop : true;
+			this.paginationCache = _.has(options, 'paginationCache') ? options.paginationCache : true;
+			
+			this.bindEvents();
+		},
+
+		/** all events binding here */
+		bindEvents : function(){
+			/*this.listenTo(this.model, "change:foo", this.modelChanged, this);*/
+			/*this.listenTo(communicator.vent,'someView:someEvent', this.someEventHandler, this)'*/
+
+			this.listenTo(this.collection, "sync reset", this.showHidePager);
+			
+            this.listenTo(this.collection, 'request', function(){
+				$(this.rTableSpinner.el).addClass('loading');
+			},this);
+            this.listenTo(this.collection, 'sync error', function(){
+				$(this.rTableSpinner.el).removeClass('loading');
+			},this);
+		},
+
+		/** on render callback */
+		onRender: function() {
+			this.initializePlugins();
+			this.renderTable();
+			if(this.includePagination) {
+				this.renderPagination();
+			}
+			/*if(this.includeFilter){
+				this.renderFilter();
+			}*/
+		},
+
+		/** all post render plugin initialization */
+		initializePlugins: function(){
+		},
+
+		renderTable : function(){
+			var that = this;
+			this.rTableList.show(new Backgrid.Grid(this.gridOpts));
+
+			/*this.rTableSpinner.show(new Spinner({
+				collection: this.collection
+			}));*/
+
+		},
+		renderPagination : function(){
+			this.rPagination.show(new Backgrid.Extension.Paginator({
+				collection: this.collection,
+				scrollToTop : this.scrollToTop,
+				paginationCache : this.paginationCache
+				
+			}));
+		},
+		showHidePager : function(){
+			if(this.collection.state && this.collection.state.totalRecords > XAGlobals.settings.PAGE_SIZE)	{
+				$(this.rPagination.el).show();
+			} else {
+				$(this.rPagination.el).hide();
+			}
+		},
+		renderFilter : function(){
+			this.rFilter.show(new Backgrid.Extension.ServerSideFilter({
+				  collection: this.collection,
+				  name: ['name'],
+				  placeholder: localization.tt('plcHldr.searchByResourcePath'),
+				  wait: 150
+			}));
+			
+			setTimeout(function(){
+				that.$('table').colResizable({liveDrag :true});
+			},0);
+		},
+
+		/** on close */
+		onClose: function(){
+		}
+
+	});
+
+	return XATableLayout; 
+});

http://git-wip-us.apache.org/repos/asf/incubator-argus/blob/7defc061/security-admin/src/main/webapp/scripts/views/folders/FolderInfo.js
----------------------------------------------------------------------
diff --git a/security-admin/src/main/webapp/scripts/views/folders/FolderInfo.js b/security-admin/src/main/webapp/scripts/views/folders/FolderInfo.js
new file mode 100644
index 0000000..055a514
--- /dev/null
+++ b/security-admin/src/main/webapp/scripts/views/folders/FolderInfo.js
@@ -0,0 +1,164 @@
+/*
+ * 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.
+ */
+
+define(function(require){
+    'use strict';
+
+	var Backbone		= require('backbone');
+	var Communicator	= require('communicator');
+	
+	var XAUtil			= require('utils/XAUtils');
+	var XAEnums			= require('utils/XAEnums');
+	var VXPermMapList 	= require('collections/VXPermMapList');
+	var FolderInfo_tmpl = require('hbs!tmpl/folders/FolderInfo_tmpl');
+	var KnoxInfo_tmpl = require('hbs!tmpl/knox/KnoxInfo_tmpl');
+
+	var FolderInfo = Backbone.Marionette.ItemView.extend(
+	/** @lends FolderInfo */
+	{
+		_viewName : FolderInfo,
+		
+    	template: FolderInfo_tmpl,
+        templateHelpers :function(){
+        	
+        	var hiveModel = this.model.get('assetType') == XAEnums.AssetType.ASSET_HIVE.value ? true : false;
+        	var hbaseModel = this.model.get('assetType') == XAEnums.AssetType.ASSET_HBASE.value ? true : false;
+        	var hiveOrHbaseModel = hiveModel || hbaseModel;
+        	return {
+        		groupPermListArr: this.getGroupPermListArr(),
+        		userPermListArr : this.getUserPermListArr(),
+   				hdfsModel 		: this.model.get('assetType') == XAEnums.AssetType.ASSET_HDFS.value ? true : false,
+        		hiveOrHbaseModel: hiveOrHbaseModel,
+        		
+        	};
+        },
+    	/** ui selector cache */
+    	ui: {},
+
+		/** ui events hash */
+		events: function() {
+			var events = {};
+			//events['change ' + this.ui.input]  = 'onInputChange';
+			return events;
+		},
+
+    	/**
+		* intialize a new FolderInfo ItemView 
+		* @constructs
+		*/
+		initialize: function(options) {
+			console.log("initialized a FolderInfo ItemView");
+
+			_.extend(this, _.pick(options, ''));
+			//this.model.set('permMapList',new VXPermMapList(this.model.attributes.permMapList))
+			this.bindEvents();
+			this.getTemplateForView();
+		},
+
+		/** all events binding here */
+		bindEvents : function(){
+			/*this.listenTo(this.model, "change:foo", this.modelChanged, this);*/
+			/*this.listenTo(communicator.vent,'someView:someEvent', this.someEventHandler, this)'*/
+		},
+
+		/** on render callback */
+		onRender: function() {
+			this.initializePlugins();
+		},
+
+		/** all post render plugin initialization */
+		initializePlugins: function(){
+		},
+		getTemplateForView : function(){
+			if(this.model.get('assetType') == XAEnums.AssetType.ASSET_KNOX.value){
+				this.template = KnoxInfo_tmpl;
+			}
+		},
+		getGroupPermListArr : function(){
+			var groupList = [];
+			var perm=[],permListArr =[];
+			if(!_.isUndefined(this.model.attributes.permMapList)){
+				if(_.isArray(this.model.attributes.permMapList)){
+					groupList = new VXPermMapList(this.model.attributes.permMapList);
+					groupList =  groupList.groupBy('groupId');
+				}else{
+					groupList =  this.model.attributes.permMapList.groupBy('groupId');
+				}
+				
+				_.each(groupList,function(val,prop){
+					var groups = groupList[prop];
+					var permTypeArr =[],name ='',ipAddressArr =[];
+					groups = _.sortBy(groups, function (m) {return m.get('permType');});
+					_.each(groups,function(gprop){
+						var permVal = _.pick(gprop.attributes,'permType').permType;
+						var label = XAUtil.enumValueToLabel(XAEnums.XAPermType,permVal);
+						permTypeArr.push(label);
+						name = _.pick(gprop.attributes,'groupName').groupName;
+						if(!_.isUndefined(gprop.get('ipAddress')))
+							ipAddressArr.push(gprop.get('ipAddress'))
+								
+					});
+					if(name != undefined){
+						var ipAddress = _.uniq(ipAddressArr).toString();
+						permListArr.push({
+							name :name,
+							permType :permTypeArr.toString(),
+							ipAddress :_.isEmpty(ipAddress) ? "--" : ipAddress
+						});
+					}
+					
+				});
+			}
+        	return permListArr;
+	     },
+	     getUserPermListArr : function(){
+    	 	var userList = [];
+    	 	var perm=[],permListArr =[];
+    	 	if(!_.isUndefined(this.model.attributes.permMapList)){
+	    		 if(_.isArray(this.model.attributes.permMapList)){
+	    			 userList = new VXPermMapList(this.model.attributes.permMapList);
+	    			 userList =  userList.groupBy('userId');
+	    		 }else{
+	    			 userList =  this.model.attributes.permMapList.groupBy('userId');
+	    		 }
+	    		 //var userList =  this.model.attributes.permMapList.groupBy('userId');
+	    		 _.each(userList,function(val,prop){
+	    			 var users = userList[prop];
+	    			 users = _.sortBy(users, function (m) {return m.get('permType');});
+	    			 var permTypeArr =[],name ='', ipAddressArr =[];
+	    			 _.each(users,function(gprop){
+	    				 var permVal = _.pick(gprop.attributes,'permType').permType;
+	    				 var label = XAUtil.enumValueToLabel(XAEnums.XAPermType,permVal);
+	    				 permTypeArr.push(label);
+	    				 name = _.pick(gprop.attributes,'userName').userName;
+	    				 if(!_.isUndefined(gprop.get('ipAddress')))
+							ipAddressArr.push(gprop.get('ipAddress'))
+	    			 });
+	    			 if(name != undefined){
+	    				 var ipAddress = _.uniq(ipAddressArr).toString();	    				 
+	    				 permListArr.push({ name :name,
+	    					 permType :permTypeArr.toString(),
+	    					 ipAddress :_.isEmpty(ipAddress) ? "--" : ipAddress
+	    				 });
+	    			 }
+	    			 
+	    		 });
+	    	 }	
+	        return permListArr;
+		     },
+		/** on close */
+		onClose: function(){
+		}
+
+	});
+
+	return FolderInfo;
+});

http://git-wip-us.apache.org/repos/asf/incubator-argus/blob/7defc061/security-admin/src/main/webapp/scripts/views/hbase/HbasePolicyCreate.js
----------------------------------------------------------------------
diff --git a/security-admin/src/main/webapp/scripts/views/hbase/HbasePolicyCreate.js b/security-admin/src/main/webapp/scripts/views/hbase/HbasePolicyCreate.js
new file mode 100644
index 0000000..5c314f8
--- /dev/null
+++ b/security-admin/src/main/webapp/scripts/views/hbase/HbasePolicyCreate.js
@@ -0,0 +1,289 @@
+/*
+ * 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.
+ */
+
+define(function(require){
+    'use strict';
+
+    	var App				= require('App');
+	var Backbone		= require('backbone');
+	var XALinks 		= require('modules/XALinks');
+	
+	var XAUtil			= require('utils/XAUtils');
+	var XAEnums			= require('utils/XAEnums');
+	var localization	= require('utils/XALangSupport');
+	var VXResourceList	= require('collections/VXResourceList');
+	
+	var HbasePolicyForm	= require('views/hbase/HbasePolicyForm');
+	var HbasepolicycreateTmpl = require('hbs!tmpl/hbase/HbasePolicyCreate_tmpl');
+
+	var HbasePolicyCreate = Backbone.Marionette.Layout.extend(
+	/** @lends HbasePolicyCreate */
+	{
+		_viewName : 'HbasePolicyCreate',
+		
+    	template: HbasepolicycreateTmpl,
+    	templateHelpers : function(){
+    		return {
+    			editPolicy : this.editPolicy
+    		};
+    	},
+    	breadCrumbs :function(){
+    		if(this.model.isNew())
+    			return [XALinks.get('RepositoryManager'),XALinks.get('ManageHbasePolicies',{model : this.assetModel}),XALinks.get('PolicyCreate')];
+    		else
+    			return [XALinks.get('RepositoryManager'),XALinks.get('ManageHbasePolicies',{model : this.assetModel}),XALinks.get('PolicyEdit')];
+    	} ,
+		/** Layout sub regions */
+    	regions: {
+    		'rForm' :'div[data-id="r_form"]'
+    	},
+
+    	/** ui selector cache */
+    	ui: {
+    		'btnSave'	: '[data-id="save"]',
+			'btnCancel' : '[data-id="cancel"]',
+			'btnDelete' : '[data-id="delete"]'
+    	},
+
+		/** ui events hash */
+		events: function() {
+			var events = {};
+			events['click ' + this.ui.btnSave]		= 'onSave';
+			events['click ' + this.ui.btnCancel]	= 'onCancel';
+			events['click ' + this.ui.btnDelete]	= 'onDelete';
+			return events;
+		},
+
+    	/**
+		* intialize a new HbasePolicyCreate Layout 
+		* @constructs
+		*/
+		initialize: function(options) {
+			var that = this;
+			console.log("initialized a HbasePolicyCreate Layout");
+
+			_.extend(this, _.pick(options,'assetModel'));
+			this.bindEvents();
+
+			that.form = new HbasePolicyForm({
+					template : require('hbs!tmpl/hbase/HbasePolicyForm_tmpl'),
+					model : this.model,
+					assetModel : this.assetModel
+			});
+
+			this.editPolicy = this.model.has('id') ? true : false;
+		},
+
+		/** all events binding here */
+		bindEvents : function(){
+			/*this.listenTo(this.model, "change:foo", this.modelChanged, this);*/
+			/*this.listenTo(communicator.vent,'someView:someEvent', this.someEventHandler, this)'*/
+		},
+
+		/** on render callback */
+		onRender: function() {
+			this.rForm.show(this.form);
+			this.rForm.$el.dirtyFields();
+			XAUtil.preventNavigation(localization.tt('dialogMsg.preventNavHbasePolicyForm'), this.rForm.$el);
+			this.initializePlugins();
+		},
+
+		/** all post render plugin initialization */
+		initializePlugins: function(){
+		},
+		popupCallBack : function(msg,validateObj){
+			var that = this;
+			XAUtil.alertPopup({
+				msg :msg,
+				callback : function(){
+			//		if(validateObj.auditLoggin)
+			//			that.savePolicy();
+				}
+			});
+		},
+		onSave : function(){
+			var that =this, valid = false;
+			var errors = this.form.commit({validate : false});
+			if(! _.isEmpty(errors)){
+				return;
+			}
+			var validateObj = this.form.formValidation();
+			valid = (validateObj.groupSet && validateObj.permSet) || (validateObj.userSet && validateObj.userPerm);
+			if(!valid){
+				
+				if(validateObj.groupSet && (!validateObj.permSet)){
+					this.popupCallBack(localization.tt('msg.addGroupPermission'),validateObj);
+				}else if((!validateObj.groupSet) && (validateObj.permSet)) {
+					this.popupCallBack(localization.tt('msg.addGroup'),validateObj);
+						
+				}else if(validateObj.userSet && (!validateObj.userPerm)){
+					this.popupCallBack(localization.tt('msg.addUserPermission'),validateObj);
+				}else if((!validateObj.userSet) && (validateObj.userPerm)) {
+					this.popupCallBack(localization.tt('msg.addUser'),validateObj);
+						
+				}else if((!validateObj.auditLoggin) && (!validateObj.groupPermSet)){
+					XAUtil.alertPopup({
+						msg :localization.tt('msg.yourAuditLogginIsOff'),
+						callback : function(){
+							/*if(!that.model.isNew()){
+								that.model.destroy({success: function(model, response) {
+									XAUtil.notifySuccess('Success', localization.tt('msg.policyDeleteMsg'));
+									App.appRouter.navigate("#!/hbase/"+that.assetModel.id+"/policies",{trigger: true});
+								}});
+							}else{
+								XAUtil.notifyError('Error', localization.tt('msg.policyNotAddedMsg'));
+								App.appRouter.navigate("#!/hbase/"+that.assetModel.id+"/policies",{trigger: true});
+							}*/
+						}
+					});
+				}else{
+					this.savePolicy();
+				}
+			}else{
+				if(validateObj.groupSet && (!validateObj.permSet)){
+					this.popupCallBack(localization.tt('msg.addGroupPermission'),validateObj);
+				}else if((!validateObj.groupSet) && (validateObj.permSet)) {
+					this.popupCallBack(localization.tt('msg.addGroup'),validateObj);
+						
+				}else if(validateObj.userSet && (!validateObj.userPerm)){
+					this.popupCallBack(localization.tt('msg.addUserPermission'),validateObj);
+				}else if((!validateObj.userSet) && (validateObj.userPerm)) {
+					this.popupCallBack(localization.tt('msg.addUser'),validateObj);
+				}else
+					this.savePolicy();
+			}
+
+		},
+		savePolicy : function(){
+			var that = this;
+			this.form.afterCommit();
+			this.saveMethod();
+		},
+		saveMethod : function(){
+			var that = this;
+			XAUtil.blockUI();
+			this.model.save({},{
+				wait: true,
+				success: function () {
+					XAUtil.blockUI('unblock');
+					var msg = that.editPolicy ? 'Policy updated successfully' :'Policy created successfully';
+					XAUtil.notifySuccess('Success', msg);
+					XAUtil.allowNavigation();	
+					if(that.editPolicy){
+						App.appRouter.navigate("#!/hbase/"+that.assetModel.id+"/policies",{trigger: true});
+						return;
+					}
+					
+					App.appRouter.navigate("#!/hbase/"+that.assetModel.id+"/policies",{trigger: false});
+					
+					var view = require('views/hbase/HbaseTableLayout');
+					var resourceListForAsset = new VXResourceList([],{
+						   queryParams : {
+							   'assetId' : that.assetModel.id 
+						   }
+					   });
+					
+					resourceListForAsset.fetch({
+						cache : false,
+						data : {
+					//			'resourceType':XAEnums.AssetType.ASSET_HIVE.value,
+								'assetId' :that.assetModel.id
+							}
+					}).done(function(){
+						var newColl = resourceListForAsset;
+						resourceListForAsset.getLastPage({
+							cache : false,
+							data  : {
+					//					'resourceType':XAEnums.AssetType.ASSET_HIVE.value,
+										'assetId' :that.assetModel.id
+									}
+						}).done(function(){
+							var model = newColl.get(that.model.id);
+							if(model){
+								model.trigger("model1:highlightBackgridRow");
+							}
+						});
+						App.rContent.show(new view({
+							collection : resourceListForAsset,
+							assetModel : that.assetModel
+						}));
+						
+					});
+					
+					console.log("success");
+				},
+				error: function (model, response, options) {
+					XAUtil.blockUI('unblock');
+					if ( response && response.responseJSON && response.responseJSON.msgDesc){
+						if( response.responseJSON.messageList && response.responseJSON.messageList.length > 0 && !_.isUndefined(response.responseJSON.messageList[0].fieldName)){
+							if(response.responseJSON.messageList[0].fieldName == "parentPermission"){
+								XAUtil.confirmPopup({
+									msg :response.responseJSON.msgDesc,
+									callback : function(){
+										that.model.set('checkParentPermission',XAEnums.BooleanValue.BOOL_FALSE.value);
+										that.saveMethod();
+									}
+								});
+							}else
+								XAUtil.notifyError('Error', response.responseJSON.msgDesc);
+						}else{
+						//	that.form.fields.name.setError(response.responseJSON.msgDesc);
+							XAUtil.notifyError('Error', response.responseJSON.msgDesc);
+						}
+					}else
+						XAUtil.notifyError('Error', 'Error creating Policy!');
+					console.log("error");
+				}
+			});
+		},
+		
+		onDelete :function(){
+			var that = this;
+			XAUtil.confirmPopup({
+				//msg :localize.tt('msg.confirmDelete'),
+				msg :'Are you sure want to delete ?',
+				callback : function(){
+					XAUtil.blockUI();
+					that.model.destroy({
+						success: function(model, response) {
+							XAUtil.blockUI('unblock');
+							XAUtil.allowNavigation();
+							XAUtil.notifySuccess('Success', localization.tt('msg.policyDeleteMsg'));
+							App.appRouter.navigate("#!/hbase/"+that.assetModel.id+"/policies",{trigger: true});
+						},
+						error: function (model, response, options) {
+							XAUtil.blockUI('unblock');
+							if ( response && response.responseJSON && response.responseJSON.msgDesc){
+								    XAUtil.notifyError('Error', response.responseJSON.msgDesc);
+							    }else
+							    	XAUtil.notifyError('Error', 'Error deleting Policy!');
+							    console.log("error");
+						}
+					});
+					
+				}
+			});
+		},
+		onCancel : function(){
+			XAUtil.allowNavigation();
+			App.appRouter.navigate("#!/hbase/"+this.assetModel.id+"/policies",{trigger: true});
+
+		},
+		
+		/** on close */
+		onClose: function(){
+			XAUtil.allowNavigation();
+		}
+
+	});
+
+	return HbasePolicyCreate; 
+});

http://git-wip-us.apache.org/repos/asf/incubator-argus/blob/7defc061/security-admin/src/main/webapp/scripts/views/hbase/HbasePolicyForm.js
----------------------------------------------------------------------
diff --git a/security-admin/src/main/webapp/scripts/views/hbase/HbasePolicyForm.js b/security-admin/src/main/webapp/scripts/views/hbase/HbasePolicyForm.js
new file mode 100644
index 0000000..9e17b2f
--- /dev/null
+++ b/security-admin/src/main/webapp/scripts/views/hbase/HbasePolicyForm.js
@@ -0,0 +1,541 @@
+/*
+ * 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.
+ */
+
+define(function(require){
+    'use strict';
+
+	var Backbone		= require('backbone');
+
+	var XAEnums			= require('utils/XAEnums');
+	var localization	= require('utils/XALangSupport');
+	var XAUtil			= require('utils/XAUtils');
+    
+	var VXPermMapList	= require('collections/VXPermMapList');
+	var VXGroupList		= require('collections/VXGroupList');
+	var VXAuditMapList	= require('collections/VXAuditMapList');
+	var VXAuditMap		= require('models/VXAuditMap');
+	var VXPermMap		= require('models/VXPermMap');
+	var VXUserList		= require('collections/VXUserList');
+	var FormInputItemList = require('views/common/FormInputItemList');
+	var UserPermissionList = require('views/common/UserPermissionList');
+
+
+
+	require('Backbone.BootstrapModal');
+	require('backbone-forms.list');
+	require('backbone-forms.templates');
+	require('backbone-forms');
+
+	var HbasePolicyForm = Backbone.Form.extend(
+	/** @lends PolicyForm */
+	{
+		_viewName : 'PolicyForm',
+		
+		type : {
+			//DATABASE : 1,
+			TABLE    : 2,
+			COLUMN   : 3,
+			COLUMN_FAMILIES   : 4
+		},
+
+    	/**
+		* intialize a new PolicyForm Form View 
+		* @constructs
+		*/
+		initialize: function(options) {
+			console.log("initialized a PolicyForm Form View");
+    		Backbone.Form.prototype.initialize.call(this, options);
+
+			_.extend(this, _.pick(options, 'assetModel'));
+			this.initializeCollection();
+			this.bindEvents();
+		},
+		
+		/** all events binding here */
+		bindEvents : function(){
+			this.on('_vAuditListToggle:change', function(form, fieldEditor){
+    			this.evAuditChange(form, fieldEditor);
+    		});
+			this.on('resourceStatus:change', function(form, fieldEditor){
+    			this.evResourceStatusChange(form, fieldEditor);
+    		});
+			/*this.on('isEncrypt:change', function(form, fieldEditor){
+    			this.evEncryptChange(form, fieldEditor);
+    		});*/
+		},
+		initializeCollection: function(){
+			this.permMapList = this.model.isNew() ? new VXPermMapList() : this.model.get('permMapList');
+			this.auditList = this.model.isNew() ? new VXAuditMapList() : this.model.get('auditList');
+		   
+		   /*If the model passed to the fn is new return an empty collection
+		    * otherwise return a collection that has models like 
+		    * {
+		    * 	groupId : 5,
+		    * 	permissionList : [4,3]
+		    * }
+		    * The formInputList will be passed to the forminputitemlist view.
+		    */
+		   
+		   this.formInputList = XAUtil.makeCollForGroupPermission(this.model);
+		   this.userPermInputList = XAUtil.makeCollForUserPermission(this.model);
+		   
+		},
+		/** fields for the form
+		*/
+	//	fields: ['name', 'description', '_vAuditListToggle', 'isEncrypt','isRecursive'],
+		schema :function(){
+			var that = this;
+			//var plugginAttr = this.getPlugginAttr(true);
+			return {
+				policyName : {
+					   type 		: 'Text',
+					   title		: localization.tt("lbl.policyName"),
+//					   validators  	: [{'type' :'required'}]
+					   editorAttrs 	:{ maxlength: 255}
+				},
+				tables : {
+					type		: 'Select2Remote',
+					title		: localization.tt("lbl.selectTableName")+' *',
+					editorAttrs :{'data-placeholder': 'Select Tables'},
+					validators  : ['required'],//,{type:'regexp',regexp:/^[a-zA-Z*?][a-zA-Z0-9_'&-/\$]*[A-Za-z0-9]*$/i,message :localization.tt('validationMessages.enterValidName')}],
+					pluginAttr  : this.getPlugginAttr(true,this.type.TABLE),
+	                options    : function(callback, editor){
+	                    callback();
+	                }
+				},
+				columnFamilies : {
+					type		: 'Select2Remote',
+					title		: localization.tt("lbl.selectColumnFamilies"),
+					editorAttrs :{'data-placeholder': 'Select Column Families'},
+	//				editorAttrs :{'disabled' :'disabled','data-placeholder': 'Select Column Families'},
+					//validators  : [{type:'regexp',regexp:/^[a-zA-Z*?][a-zA-Z0-9_'&-/\$]*[A-Za-z0-9]*$/i,message :localization.tt('validationMessages.enterValidName')}],
+					pluginAttr  : this.getPlugginAttr(true,this.type.COLUMN_FAMILIES),
+					options    : function(callback, editor){
+						callback();
+					}
+					
+					
+				},
+				columns : {
+					//type		: 'Select2Remote',
+					type		: 'Text',
+					title		: localization.tt("lbl.enterColumnName"),
+		//			validators  : [{type:'regexp',regexp:/^[a-zA-Z*?][a-zA-Z0-9_'&-/\$]*[A-Za-z0-9]*$/i,message :localization.tt('validationMessages.enterValidName')}],
+					editorAttrs :{ 'placeholder': 'Enter Column Name'}
+					//pluginAttr  : this.getPlugginAttr(true,this.type.COLUMN),
+				},
+				_vAuditListToggle : {
+					type		: 'Switch',
+					title		: localization.tt("lbl.auditLogging"),
+					listType	: 'VNameValue',
+					switchOn	: true
+				},
+				/*isEncrypt : {
+					type		: 'Switch',
+					title		: localization.tt("lbl.encrypted"),
+					switchOn	: false
+	//				fieldAttrs : {style : 'display:none;'}
+				},*/
+				permMapList : {
+					getValue : function(){
+						console.log(this);
+					}
+				},
+				resourceStatus : {
+					type		: 'Switch',
+					title		: localization.tt("lbl.policyStatus"),
+					onText		: 'enabled',
+					offText		: 'disabled',
+					width		: '85',
+					switchOn	: true
+				},
+				description : { 
+					type		: 'TextArea',
+					title		: localization.tt("lbl.description"), 
+				//	validators	: [/^[A-Za-z ,.'-]+$/i],
+					template	:_.template('<div class="altField" data-editor></div>')
+				},
+			};	
+		},
+
+		evAuditChange : function(form, fieldEditor){
+			XAUtil.checkDirtyFieldForToggle(fieldEditor);
+			if(fieldEditor.getValue() == 1){
+				this.model.set('auditList', new VXAuditMapList(new VXAuditMap({
+					'auditType' : XAEnums.XAAuditType.XA_AUDIT_TYPE_ALL.value,//fieldEditor.getValue()//
+					'resourceId' :this.model.get('id')
+					
+				})));
+			} else {
+				var validation  = this.formValidation();
+				if(validation.groupPermSet || validation.isUsers)
+					this.model.unset('auditList');
+				else{
+					XAUtil.alertPopup({
+						msg :localization.tt("msg.policyNotHavingPerm"),
+						callback : function(){
+							fieldEditor.setValue('ON');
+						}
+					});
+				}
+			}
+			console.log(fieldEditor);
+		},
+		evResourceStatusChange : function(form, fieldEditor){
+			XAUtil.checkDirtyFieldForToggle(fieldEditor);
+		},
+		evEncryptChange : function(form, fieldEditor){
+			XAUtil.checkDirtyFieldForToggle(fieldEditor);
+		},
+		/** on render callback */
+		render: function(options) {
+			var that = this;
+			 Backbone.Form.prototype.render.call(this, options);
+
+			this.initializePlugins();
+			this.renderSelectTagsFields();
+			this.renderCustomFields();
+			if(!this.model.isNew()){
+				this.setUpSwitches();
+				if(!_.isEmpty(this.fields.tables.editor.$el.val()))
+					that.fields.columnFamilies.editor.$el.prop('disabled',false);
+				if(!_.isEmpty(this.fields.columnFamilies.editor.$el.val()))
+					that.fields.columns.editor.$el.prop('disabled',false);
+			}
+			if(this.model.isNew() && this.fields._vAuditListToggle.editor.getValue() == 1){
+				this.model.set('auditList', new VXAuditMapList(new VXAuditMap({
+					'auditType' : XAEnums.XAAuditType.XA_AUDIT_TYPE_ALL.value,//fieldEditor.getValue()//
+					'resourceId' :this.model.get('id')
+					
+				})));
+			}
+		},
+		renderSelectTagsFields :function(){
+			var that = this;
+			
+			this.fields.tables.editor.$el.on('change',function(e){
+				console.log('change on table Name');
+				that.checkMultiselectDirtyField(e, that.type.TABLE);
+				that.fields.tables.setValue(that.fields.tables.editor.$el.select2('data').map(function(obj){return obj.text}).toString());
+					
+			});
+			this.fields.columnFamilies.editor.$el.on('change',function(e){
+				console.log('change on column Families Name');
+				that.checkMultiselectDirtyField(e, that.type.COLUMN_FAMILIES);
+				that.fields.columnFamilies.setValue(that.fields.columnFamilies.editor.$el.select2('data').map(function(obj){return obj.text}).toString());
+			});
+			
+		},
+		getDataParams : function(type, term){
+			var dataParams = {
+			//	dataSourceName : 'hadoopdev',
+				dataSourceName : this.assetModel.get('name')
+			// databaseName: term,
+			};
+			if (type == this.type.TABLE && this.fields) {
+				//dataParams.databaseName = this.fields.databases.editor.$el.select2('data')[0].text;
+				dataParams.tableName = term;
+			}
+			if (type == this.type.COLUMN_FAMILIES && !_.isEmpty(this.fields.tables.getValue())) {
+				dataParams.tableName = this.fields.tables.editor.$el.select2('data')[0].text;
+				dataParams.columnFamilies  = _.isEmpty(term) ? "*" :  term;
+			}
+			return dataParams;
+		},
+		getPlugginAttr :function(autocomplete, searchType){
+			var that =this;
+			var type = searchType;
+			if(!autocomplete)
+				return{tags : true,width :'220px',multiple: true,minimumInputLength: 1};
+			else {
+				
+				
+				return {
+					closeOnSelect : true,
+					//placeholder : 'Select User',
+					tags:true,
+					multiple: true,
+				//	minimumInputLength: 1,
+					width :'220px',
+					tokenSeparators: [",", " "],
+					initSelection : function (element, callback) {
+						var data = [];
+						$(element.val().split(",")).each(function () {
+							data.push({id: this, text: this});
+						});
+						callback(data);
+					},
+					createSearchChoice: function(term, data) {
+						if ($(data).filter(function() {
+							return this.text.localeCompare(term) === 0;
+						}).length === 0) {
+							return {
+								id : term,
+								text: term
+							};
+						}
+					},
+					/*query: function (query) {
+						var url = "service/assets/hive/resources";
+						var data = _.extend(that.getDataParams(type, query.term));
+						//var results = [ {id: query.term, path: query.term}];
+
+						$.get(url, data, function (resp) {
+							var serverRes = [];
+							if(resp.resultSize){
+								serverRes = resp.vXStrings.map(function(m, i){	return {id : m.value, path: m.value};	});
+							}
+							query.callback({results: serverRes});
+						}, 'json');
+
+						//query.callback({results: results});
+					},*/
+
+					ajax: { 
+						url: "service/assets/hbase/resources",
+						dataType: 'json',
+						params : {
+							timeout: 3000
+						},
+						cache: false,
+						data: function (term, page) {
+							return _.extend(that.getDataParams(type, term));
+							
+						},
+						results: function (data, page) { 
+							var results = [];
+							if(data.resultSize != "0"){
+								results = data.vXStrings.map(function(m, i){	return {id : m.value, text: m.value};	});
+							}
+							return { 
+								results : results
+							};
+						},
+						transport: function (options) {
+							$.ajax(options).error(function() { 
+								console.log("ajax failed");
+								this.success({
+									resultSize : 0
+								});
+							});
+							/*$.ajax.error(function(data) { 
+								console.log("ajax failed");
+								return {
+									results : []
+								};
+							});*/
+
+						}
+
+					},	
+					formatResult : function(result){
+						return result.text;
+					},
+					formatSelection : function(result){
+						return result.text;
+					},
+					formatNoMatches : function(term){
+						switch (type){
+							case  that.type.COLUMN_FAMILIS :return localization.tt("msg.enterAlteastOneCharactere");
+							case  that.type.TABLE :return localization.tt("msg.enterAlteastOneCharactere");
+							case  that.type.COLUMN :return localization.tt("msg.enterAlteastOneCharactere");
+							default : return "No Matches found";
+						}
+					}
+				};	
+			}
+		},
+		formValidation : function(){
+			var groupSet = false,permSet = false,auditStatus= false,encryptStatus= false,groupPermSet = false,
+							userSet=false,userPerm = false,isUsers =false;
+			console.log('validation called..');
+			var breakFlag =false;
+			this.formInputList.each(function(m){
+				if(m.has('groupId') ||  m.has('_vPermList')){
+					if(! breakFlag){
+						groupSet = m.has('groupId') ? true : false ; 
+						if(!m.has('_vPermList')){
+							permSet = false;
+						}else
+							permSet = true;
+						if(groupSet && permSet)
+							groupPermSet = true;
+						else
+							breakFlag=true;
+					}
+				}
+			});
+			breakFlag = false;
+			this.userPermInputList.each(function(m){
+				if(!_.isUndefined(m.attributes)){
+					if(! breakFlag){
+						userSet = m.has('userId') || m.has('userName') ? true : false ;//|| userSet; 
+						if(!m.has('_vPermList')){
+							userPerm = false;
+						}else
+							userPerm = true;
+						if(userSet && userPerm)
+							isUsers = true;
+						else
+							breakFlag=true;
+					}
+				}
+			});
+			auditStatus = this.fields._vAuditListToggle.editor.getValue();
+			//encryptStatus = this.fields.isEncrypt.editor.getValue();
+			var auditLoggin = (auditStatus == XAEnums.BooleanValue.BOOL_TRUE.value) ? true : false;
+			//var encrypted = (encryptStatus == XAEnums.BooleanValue.BOOL_TRUE.value) ? true : false;
+			/*if((groupSet && permSet) || auditLoggin || encrypted )
+				return true;*/
+			
+			return {groupPermSet: groupPermSet , groupSet : groupSet,permSet : permSet,auditLoggin :auditLoggin,/*encrypted : encrypted,*/
+				userSet : userSet,userPerm:userPerm,isUsers:isUsers};	
+		},
+		setUpSwitches :function(){
+			var that = this;
+			var encryptStatus = false,auditStatus = false,recursiveStatus = false;
+			auditStatus = this.model.has('auditList') ? true : false; 
+			this.fields._vAuditListToggle.editor.setValue(auditStatus);
+			
+			/*_.each(_.toArray(XAEnums.BooleanValue),function(m){
+				if(parseInt(that.model.get('isEncrypt')) == m.value)
+					encryptStatus =  (m.label == XAEnums.BooleanValue.BOOL_TRUE.label) ? true : false;
+			});
+			this.fields.isEncrypt.editor.setValue(encryptStatus); */
+			if(parseInt(this.model.get('resourceStatus')) != XAEnums.BooleanValue.BOOL_TRUE.value)
+				this.fields.resourceStatus.editor.setValue(false);
+		},
+		/** all custom field rendering */
+		renderCustomFields: function(){
+			var that = this;
+			this.groupList = new VXGroupList();
+			var params = {sortBy : 'name', cache :false};
+			this.groupList.setPageSize(100,{fetch:false});
+			this.groupList.fetch({
+				cache :true,
+				data : params
+				}).done(function(){
+					that.$('[data-customfields="groupPerms"]').html(new FormInputItemList({
+						collection 	: that.formInputList,
+						groupList  	: that.groupList,
+						model 		: that.model,
+						policyType 	: XAEnums.AssetType.ASSET_HBASE.value
+					
+					}).render().el);
+			});	
+			
+			this.userList = new VXUserList();
+			var params = {sortBy : 'name', cache :false};
+			this.userList.setPageSize(100,{fetch:false});
+			this.userList.fetch({
+				cache :true,
+				data : params
+				}).done(function(){
+					that.$('[data-customfields="userPerms"]').html(new UserPermissionList({
+						collection 	: that.userPermInputList,
+						model 		: that.model,
+						userList 	: that.userList,
+						policyType 	: XAEnums.AssetType.ASSET_HBASE.value
+					}).render().el);
+			});
+		},
+		afterCommit : function(){
+			var that = this;
+			//TODO FIXME remove the hard coding 
+			//this.model.set('assetId', XAGlobals.hardcoded.HiveAssetId);
+			this.model.set('assetId', this.assetModel.id);
+			var permMapList = new VXPermMapList();
+			this.formInputList.each(function(m){
+				if(!_.isUndefined(m.get('groupId'))){
+					var uniqueID = _.uniqueId(new Date()+':');
+					_.each(m.get('groupId').split(","),function(groupId){
+						_.each(m.get('_vPermList'), function(perm){
+							var params = {
+									//groupId: m.get('groupId'),
+									groupId: groupId,
+									permFor : XAEnums.XAPermForType.XA_PERM_FOR_GROUP.value,
+									permType : perm.permType,
+									permGroup : uniqueID
+							};
+							if(parseInt(groupId) == perm.groupId)
+								params = $.extend(params, {id : perm.id});
+							//TODO FIXME remove the hardcoding
+							permMapList.add(new VXPermMap(params));
+						}, this);
+					});
+				}
+			}, this);
+			
+			this.userPermInputList.each(function(m){
+				if(!_.isUndefined(m.get('userId'))){
+					var uniqueID = _.uniqueId(new Date()+':');
+					_.each(m.get('userId').split(","),function(userId){
+						_.each(m.get('_vPermList'), function(perm){
+							var params = {
+									//groupId: m.get('groupId'),
+									userId: userId,
+									permFor : XAEnums.XAPermForType.XA_PERM_FOR_USER.value,
+									permType : perm.permType,
+									permGroup : uniqueID
+							};
+							if(parseInt(userId) == perm.userId)
+								params = $.extend(params, {id : perm.id});
+							//TODO FIXME remove the hardcoding
+							permMapList.add(new VXPermMap(params));
+						}, this);
+					});
+				}
+			}, this);
+			
+			this.model.set('permMapList', permMapList);
+			var columns = !_.isEmpty(this.model.get('columns'));
+			var columnFamilies = !_.isEmpty(this.model.get('columnFamilies'));
+			
+			if(columns)
+				this.model.set('resourceType',XAEnums.ResourceType.RESOURCE_COLUMN.value);
+			else if(columnFamilies)	
+				this.model.set('resourceType',XAEnums.ResourceType.RESOURCE_COL_FAM.value);
+			else
+				this.model.set('resourceType',XAEnums.ResourceType.RESOURCE_TABLE.value);
+			
+			//TODO Already handled by server side so we need to remove following line 
+			if(_.isEmpty(this.model.get('columnFamilies')))	{
+				this.model.unset('columnFamilies');
+				this.model.unset('columns'); 
+			}
+				
+			if(_.isEmpty(this.model.get('columns')))	this.model.unset('columns');
+			if(this.model.get('resourceStatus') != XAEnums.BooleanValue.BOOL_TRUE.value){
+				this.model.set('resourceStatus', XAEnums.ActiveStatus.STATUS_DISABLED.value);
+			}
+			
+			
+		},
+		checkMultiselectDirtyField : function(e, type){
+			var elem = $(e.currentTarget),columnName='',newNameList = [], nameList = [];
+			switch(type){
+				case 2 :columnName = 'tables';break;
+				case 4 :columnName = 'columnFamilies';break;
+			}
+			if(!_.isUndefined(this.model.get(columnName)) && !_.isEqual(this.model.get(columnName),""))
+				nameList = this.model.get(columnName).split(',');
+			if(!_.isEqual(e.currentTarget.value, ""))
+				newNameList = e.currentTarget.value.split(',');
+			XAUtil.checkDirtyField(nameList, newNameList, elem);
+		},
+		/* all post render plugin initialization */
+		initializePlugins: function(){
+		}
+
+	});
+
+	return HbasePolicyForm;
+});


Mime
View raw message