Initial commit

This commit is contained in:
Isaac Parenteau committed 2018-07-07 20:43:51 -05:00
commit 880e39de2e
511 files changed
+38363

No files matched your search

@@ -0,0 +1,125 @@
(function () {
'use strict';
/**
* DESCRIPTION: Deferred authorization handler.
*/
angular.module('portal.common.services.authorize', ['ui.router'])
.service('authorize', authorizeService);
function authorizeService($state, $q, cache, accountStores) {
/**
* Defines the different types of auth checkers.
* @type type
*/
var authHandlers = {
account: function (args) {
var deferred = $q.defer();
var mCache = cache.request([new accountStores.Account()]).once(function () {
var authorized = false;
for (var i = 0; i < args.length; i++) {
if (mCache.account.data.authoritiesMap.containsKey(args[i])) {
authorized = true;
break;
}
}
deferred.resolve(authorized);
}).catch(function () {
deferred.reject();
});
return deferred.promise;
},
permission: function (args) {
var deferred = $q.defer();
var mCache = cache.request([new accountStores.Account()]).once(function () {
var acct = mCache.account.data;
if (!acct.enabled) {
deferred.resolve(false);
return;
}
var authorized = false;
for (var i = 0; i < args.length; i++) {
if (acct.hasPermission(args[i])) {
authorized = true;
break;
}
}
deferred.resolve(authorized);
}).catch(function (err) {
deferred.reject();
});
return deferred.promise;
}
};
/**
* Chains deferrals so we don't have to nest them.
*
* Yes, this is kind of complicated, its async recursion. Tried to help with
* comments but only so much you can do.
*
* @param {type} authorities
* @param {type} keys
* @param {type} i
* @param {type} isValid
* @returns {$q@call;defer.promise}
*/
function validate(authorities, keys, i, isValid) {
var deferred = $q.defer();
//If still within bounds of authorities array
//call the auth handler and if we are still valid
//No point in continuing if we are no longer valid.
if (i < keys.length && isValid) {
authHandlers[keys[i]](authorities[keys[i]]).then(function (valid) {
//When the auth handler returns, chain up the next one
//by calling validate again.
//Its important to combine the valid status as we go.
return validate(authorities, keys, i + 1, isValid && valid);
}).then(function (valid) {
//calling deferred in the then allows us to close our chains.
deferred.resolve(valid);
}).catch(function(){
deferred.reject();
});
} else {
//This is the last link in the chain, if we don't call resolve
//we won't start linking the rest of the chains.
deferred.resolve(isValid);
}
return deferred.promise;
}
return {
/**
* Deferred validation routine for the ui-router resolve
* functionality. UI-router listens for the promise to be resolved
* before movingn to the next state.
*
* This avoids us having to do awkard redirects while we check
* server for status.
*
* @param {type} args
* @returns {$q@call;defer.promise}
*/
validate: function (args) {
var deferred = $q.defer();
if (angular.isObject(args.authorities)) {
var keys = Object.keys(args.authorities);
validate(args.authorities, keys, 0, true).then(function (isValid) {
if (!isValid) {
$state.go(args.redirect);
}
deferred.resolve();
}).catch(function () {
$state.go(args.redirect);
});
} else {
deferred.resolve();
}
return deferred.promise;
}
};
} //end authorizeService function
})();
@@ -0,0 +1,200 @@
(function () {
'use strict';
/**
* DESCRIPTION:
*
* Special map object for easy access to both an object map and an array.
*
* This object mimics maps as defined by the Java map interface.
*/
angular.module('portal.common.services.map', ['ui.router'])
.factory('Map', mapService);
function mapService() {
/**
* Defines a map object that allows storage of data as array and object.
* @param {type} accessor The value used on elements for the key, e.g. element.id => "id"
* @returns {map_L35.mapService.Map}
*/
function Map(accessor, groupKeys) {
var map = this;
/** Array Storage. */
map.values = [];
/** Object Storage. */
map.object = {};
/** Group Storage. */
map.groups = {};
/** Group keys. */
map.groupKeys = [];
if (angular.isArray(groupKeys)) {
map.groupKeys = groupKeys.slice();
} else if (angular.isDefined(groupKeys)) {
map.groupKeys.push(groupKeys);
}
//Initialize Groups
for (var i = 0; i < map.groupKeys.length; i++) {
map.groups[map.groupKeys[i]] = {};
}
/**
* defines the part of the element that comprises the key.
* May be undefined, not guaranteed.
*/
map.accessor = accessor;
/**
* @returns {Boolean} True if emtpy.
*/
map.isEmpty = function () {
return map.values.length === 0;
};
/**
* Determins if an item is stored inside based on its key.
* @param {type} key
* @returns {Boolean} True if contained.
*/
map.containsKey = function (key) {
return angular.isDefined(map.object[key]);
};
/**
* Searches for element, via loop.
* @param {type} value
* @returns {Boolean} True if element found.
*/
map.containsValue = function (value) {
for (var i = 0; i < map.values.length; i++) {
if (map.values[i] === value) {
return true;
}
}
return false;
};
/**
* @param {type} key
* @returns {type} element found by key.
*/
map.get = function (key) {
return map.object[key];
};
/**
* Inserts element into both array and object storage.
* @param {type} key
* @param {type} value
*/
map.put = function (key, value) {
//Remove elements.
map.removeByKey(key);
//Insert.
map.values.push(value);
map.object[key] = value;
//Group
for (var i = 0; i < map.groupKeys.length; i++) {
var groupKey = map.groupKeys[i];
var group = value[groupKey];
if (!angular.isDefined(map.groups[groupKey][group])) {
map.groups[groupKey][group] = new Map(map.accessor);
}
map.groups[groupKey][group].put(key, value);
}
return value;
};
/**
* Allows access to a group map.
* Always returns a valid map, just may be empty.
* @param {type} group
* @returns {map_L35.mapService.Map}
*/
map.getGroup = function (groupKey, group) {
if (angular.isDefined(map.groups[groupKey][group])) {
return map.groups[groupKey][group];
}
return new Map();
};
/**
* Removes an element from both storage interfaces.
* @param {type} key
* @returns {Boolean} T/F if removed or not.
*/
map.removeByKey = function (key) {
if (!map.containsKey(key)) {
return false;
}
var value = map.object[key];
//Remove from Array.
for (var i = 0; i < map.values.length; i++) {
if (map.values[i] === value) {
map.values.splice(i, 1);
break;
}
}
//Remove from object.
delete map.object[key];
//Remove from groups.
for (var j = 0; j < map.groupKeys.length; j++) {
var groupKey = map.groupKeys[j];
var group = value[groupKey];
if (angular.isDefined(map.groups[groupKey][group])) {
map.groups[groupKey][group].removeByKey(key);
}
}
return true;
};
/**
* Empties the storage objects.
*/
map.clear = function () {
map.object = {};
map.values = [];
};
map.init = function (data, Constructor, accessor) {
map.clear();
map.accessor = accessor;
if (angular.isArray(data)) {
for (var i = 0; i < data.length; i++) {
var obj = new Constructor(data[i]);
map.put(obj[accessor], obj);
}
}
};
Object.defineProperties(map, {
/**
* Returns the keys from the object.
*/
keySet: {
get: function () {
return Object.keys(map.object);
}
},
length: {
get: function () {
return map.values.length;
}
}
});
}
Map.create = function (data, Constructor, accessor, groupKeys) {
var map = new Map(accessor, groupKeys);
map.init(data, Constructor, accessor);
return map;
};
return Map;
} //end mapService function
})();
+133
View File
@@ -0,0 +1,133 @@
(function () {
'use strict';
/**
* DESCRIPTION: Box contains data and status for the store and cache.
*/
angular.module('portal.common.services.model.cache')
.factory('Box', boxService);
function boxService(portalUtils, Listener, Triggers, $q) {
/**
* Box obejct to enacupsulate the data so it can be watched.
* @returns {undefined}
*/
var Box = portalUtils.inherit(function (args) {
var box = this;
Listener.call(box);
/**
* Container for data.
*/
box.data = undefined;
/**
* Container for error.
*/
box.errorData = undefined;
/**
* Status of the data request.
*/
box.status = Box.Status.NEW;
/** Function to handle client side data processing. */
box.processGui = args.processGui;
/** Function to handle parallel processing. */
box.processParallel = args.processParallel;
/** Function for deferred processing, expects $q promise. */
box.processDeferred = args.processDeferred;
if (angular.isDefined(args.triggers)) {
Triggers.listen(args.triggers, function(trigger, payload) {
portalUtils.call(args.processTrigger, trigger, payload, box);
});
}
box.init = function() {
if (box.status === Box.Status.NEW) {
box.status = Box.Status.PENDING;
if (angular.isFunction(args.source)) {
args.source(args.params).then(function (payload) {
box.update(payload);
}).catch(function(payload){
box.onError(payload);
});
} else {
console.error('Store source function was not a function.');
}
}
return box.listen();
};
box.refresh = function () {
var deferred = $q.defer();
if (box.status !== Box.Status.PENDING &&
angular.isFunction(args.source)) {
box.status = Box.Status.PENDING;
args.source(args.params).then(function (payload) {
if (angular.isFunction(box.processDeferred)) {
box.update(payload).then(deferred.resolve);
} else {
box.update(payload);
deferred.resolve();
}
});
} else {
deferred.resolve();
}
return deferred.promise;
};
box.update = function (_data) {
box.status = Box.Status.DONE;
var data = _data;
if (angular.isFunction(box.processParallel)) {
data = box.processParallel(data);
}
if (angular.isFunction(box.processGui)) {
data = box.processGui(data);
}
if (angular.isFunction(box.processDeferred)) {
return box.processDeferred(data).then(function(_data){
return update(_data);
});
} else {
return update(data);
}
};
box.onError = function(_data) {
box.status = Box.Status.ERROR;
box.errorData = _data;
box.notifyError();
};
function update(data) {
box.data = data;
box.notify();
}
box.clear = function () {
box.data = undefined;
box.status = Box.Status.new;
box.notify();
};
box.isDone = function () {
return box.status === Box.Status.DONE;
};
}, Listener);
/**
* Status enum
*/
Box.Status = {
NEW: 0,
PENDING: 1,
DONE: 2,
ERROR: 3
};
return Box;
} //end boxService function
})();
+192
View File
@@ -0,0 +1,192 @@
(function () {
'use strict';
/**
* DESCRIPTION: Provides entry to the cache service.
*/
angular.module('portal.common.services.model.cache', ['ui.router'])
.service('cache', cacheService);
function cacheService($cacheFactory, portalUtils, Store, Request, $rootScope, Listener) {
/**
* $cacheFactory instances for storing all cache data. Shared between tabs.
*
* This may be better placed in app.js
*
* Why are we collecting rootscopes? because when data changes on the
* shared cache we need to notify everyone via $digest. This is
* done in the Listener.digest function.
*
* @type @call;$cacheFactory
*/
var caches = {};
var scopes = [];
if (angular.isObject(window.opener) && angular.isObject(window.opener.cacheService)) {
caches = window.opener.cacheService.caches;
scopes = window.opener.cacheService.rootScopes;
scopes.push($rootScope);
} else {
caches.data = $cacheFactory('dataCache');
caches.http = $cacheFactory('httpCache');
scopes = [$rootScope];
window.cacheService = {caches: caches, rootScopes: scopes};
}
Store.registerCache(caches.data);
Request.registerCache(caches.http);
Listener.registerScopes(scopes);
/**
* Mini Cache Object.
* Provides an isolated cache with only data points
* that were requested.
* @param _stores
* @returns {undefined}
*/
function MiniCache(_stores) {
var miniCache = this;
/** Stores in this cache. */
var stores = _stores;
/** Callbacks registered on then(...) */
var dataCallBack = null;
var errorCallback = null;
/** Parent cache in chained caches. */
miniCache.parent = null;
/** Allows for a do once and unsubscribe. */
var doOnce = false;
/**
* Allows tracking of first round of notifications
* to avoid multiple notify calls when all data sets are
* ready.
*/
var storesReady = {};
//Activate (Listen) to the stores in this minicache.
for (var i = 0; i < stores.length; i++) {
var store = stores[i];
if (store instanceof Store) {
storesReady[store.id] = false;
store.init().then(notify(store)).catch(error(store));
miniCache[store.id] = store.getBox();
}
}
/**
* Promise Accessor
* @param {type} callback
* @returns {cache_L35.cacheService.MiniCache}
*/
miniCache.then = function (callback, errorCallback) {
dataCallBack = callback;
miniCache.catch(errorCallback);
return this;
};
miniCache.catch = function (callback) {
errorCallback = callback;
return this;
};
/**
* Promise Accessor
* @param {type} callback
* @returns {undefined}
*/
miniCache.once = function (callback) {
miniCache.then(callback);
doOnce = true;
return this;
};
/**
* Notifies callback in .then, only called when all are ready.
* @returns {undefined}
*/
function notify(store) {
var _store = store;
//returned function is what is called by the store,
//the wrapping allows us to keep track of which stores have
//triggered once.
return function () {
storesReady[_store.id] = true;
//Verify all stores are ready before notifiying listeners.
for (var j = 0; j < stores.length; j++) {
var store = stores[j];
if (!storesReady[store.id] || stores[j].isReady() === false) {
return;
}
}
if (doOnce) {
miniCache.unlisten();
}
miniCache.merge(portalUtils.call(dataCallBack));
};
}
function error(store) {
var _store = store;
return function () {
portalUtils.call(errorCallback, _store);
};
}
miniCache.merge = function (mCache) {
if (mCache instanceof MiniCache) {
mCache.parent = miniCache;
if (miniCache.parent === null) {
//Copy boxes.
var mCacheStores = mCache.getStores();
for (var i = 0; i < mCacheStores.length; i++) {
miniCache[mCacheStores[i].id] = mCache[mCacheStores[i].id];
}
} else {
miniCache.parent.merge(mCache);
}
}
};
miniCache.getStores = function () {
return stores;
};
/**
* Allows you to purge listeners.
* @returns {undefined}
*/
miniCache.unlisten = function () {
for (var i = 0; i < stores.length; i++) {
stores[i].unlisten();
}
};
}
/*
* Public Methods
*/
return {
/**
* Allows data to be requested.
* @param {type} stores
* @returns {MiniCache} Mini cache with requested data
*/
request: function (stores) {
var storesArray = [];
//Arrayify the data points.
if (angular.isArray(stores)) {
storesArray = stores.slice();
} else {
storesArray.push(stores);
}
return new MiniCache(storesArray);
},
/**
* Purges the cache.
*/
flush: function () {
caches.data.removeAll();
caches.http.removeAll();
}
};
} //end cacheService function
})();
@@ -0,0 +1,145 @@
(function () {
'use strict';
/**
* DESCRIPTION:
*/
angular.module('portal.common.services.model.cache')
.service('Listener', listenerService);
function listenerService(Map, $q, debounce, $rootScope) {
var Listener = function () {
var li = this;
var successMap = new Map();
var errorMap = new Map();
var subscriberId = 0;
var notified = false;
var errored = false;
var errorArgs = [];
var successArgs = [];
li.Listen = function () {
var pr = this;
pr.successIds = [];
pr.errorIds = [];
pr.then = function (success, error) {
if (angular.isFunction(success)) {
pr.successIds.push(subscriberId);
successMap.put(subscriberId, success);
subscriberId++;
}
pr.catch(error);
if (notified) {
call(success, successArgs);
}
return pr;
};
pr.catch = function (error) {
if (angular.isFunction(error)) {
pr.errorIds.push(subscriberId);
errorMap.put(subscriberId, error);
subscriberId++;
}
if (errored) {
call(error, errorArgs);
}
return pr;
};
pr.unlisten = function () {
var i = 0;
for (i = 0; i < pr.successIds.length; i++) {
successMap.removeByKey(pr.successIds[i]);
}
for (i = 0; i < pr.errorIds.length; i++) {
errorMap.removeByKey(pr.errorIds[i]);
}
};
};
li.listen = function () {
return new li.Listen();
};
li.notify = function (timeout) {
notified = true;
successArgs = arguments;
return callMap(successMap, successArgs, timeout);
};
li.notifyError = function () {
errored = true;
errorArgs = arguments;
return callMap(errorMap, arguments);
};
function callMap(map, args, timeout) {
var promises = [];
for (var i = 0; i < map.length; i++) {
promises.push(call(map.values[i], args, timeout));
}
return $q.all(promises);
}
function call(callee, args, timeout) {
var deferred = $q.defer();
if (angular.isFunction(callee)) {
window.setTimeout(function () {
callee.apply(li, args);
Listener.digest();
deferred.resolve();
}, timeout);
}
return deferred.promise;
}
};
var scopes;
Listener.registerScopes = function(_scopes) {
scopes = _scopes;
};
/**
* This allows us to only digest once we settle down.
* This debounce waits 100ms if it doesn't get another
* request to digest it will digest. Every request
* resets the timer to 100ms. This prevents us from
* hammering the CPU on load.
*
* Note: I have read the many many things on the internet that say
* we shouldn't do this. That we are breaking $angular convention, and I
* am ok with that. portal is not a public facing website.
*
* We are doing this because $timeout takes about 500ms to a 1s to make
* an async call. setTimeout is significantly faster. But that takes us
* outside of a digest cycle which means angular watches won't be re-evaluated.
* We must call $digest to get them to update.
*
* Conventionally you should call $scope.$apply, but that results in the same
* delays as $setTimout.
*
* Alternatively we could make this synchronous but doing so prohibits UI
* drawing/interaction which is not conducive to a good UI.
*
*/
Listener.digest = debounce(function () {
console.log('DIGESTING');
for (var i = 0; i < scopes.length; i++) {
try {
scopes[i].$digest();
} catch (err){
console.log('WARN: Digest already in progerss');
}
}
}, 100);
return Listener;
} //end listenerService function
})();
@@ -0,0 +1,91 @@
(function () {
'use strict';
/**
* DESCRIPTION: Defines an Account object, which defines the person who has
* authenticated with the server.
*/
angular.module('portal.common.services.model.cache')
.service('Account', accountService);
function accountService(Map, Constants) {
function Account(data) {
var account = this;
account.id = null;
account.authoritiesMap = new Map('id');
account.username = '';
account.password = '';
account.lastName = '';
account.firstName = '';
account.auId = null;
account.email = '';
account.role = '';
account.expirationDate = '';
account.effectiveDate = '';
account.stompTopics = [];
account.permissions = {};
account.enabled = false;
account.fromData = function (data) {
account.id = data.id;
account.authoritiesMap = new Map('id');
account.username = data.username;
account.password = null;
account.lastName = data.lastName;
account.firstName = data.firstName;
account.auId = data.auId;
account.email = data.email;
account.role = data.role;
account.expirationDate = data.expirationDate;
account.effectiveDate = data.effectiveDate;
account.stompTopics = data.stompTopics;
account.permissions = data.permissions;
account.enabled = data.enabled;
if (angular.isArray(data.authorities)) {
for (var i = 0; i < data.authorities.length; i++) {
var authority = Account.Authorities.getTypeFromString(data.authorities[i]);
account.authoritiesMap.put(authority.id, authority);
}
}
};
if (angular.isDefined(data)) {
account.fromData(data);
}
account.hasPermission = function(key) {
return account.authoritiesMap.containsKey(key);
};
}
/**
* Object defining a account authority
* @param {type} id
* @param {type} name
* @returns {Account.Authority}
*/
Account.Authority = function (id, name) {
var userType = this;
userType.id = id;
userType.name = name;
};
Account.Authority.prototype.toString = function () {
return this.id;
};
/**
* Defines the statically typed account Authority as an enum (of sorts)
*/
Account.Authorities = {
getTypeFromString: function (typeAsString) {
return Account.Authorities[typeAsString];
}
};
$.each(Constants.Permissions, function(key, value) {
Account.Authorities[key] = new Account.Authority(key, value.replace(/_/g, ' '));
});
return Account;
} //end accountService function
})();
@@ -0,0 +1,40 @@
(function () {
'use strict';
/**
* DESCRIPTION: Defines an Account object, which defines the person who has
* authenticated with the server.
*/
angular.module('portal.common.services.model.cache')
.service('ApplicationLog', appLogService);
function appLogService(Map) {
function ApplicationLog(data) {
var appLog = this;
appLog.id = '';
appLog.eventName = '';
appLog.event = '';
appLog.severity = '';
appLog.ipAddress = '';
appLog.timestamp = '';
appLog.loggedBy = '';
appLog.fromData = function (data) {
appLog.id = data.id;
appLog.loggedBy = data.loggedBy;
appLog.eventName = data.eventName;
appLog.event = data.event;
appLog.severity = data.severity;
appLog.ipAddress = data.ipAddress;
appLog.timestamp = moment(data.timestamp);
};
if (angular.isDefined(data)) {
appLog.fromData(data);
}
}
return ApplicationLog;
} //end appLogService function
})();
@@ -0,0 +1,44 @@
(function () {
'use strict';
/**
* DESCRIPTION: Defines an Account object, which defines the person who has
* authenticated with the server.
*/
angular.module('portal.common.services.model.cache')
.service('Config', configService);
function configService(Map) {
function Config(data) {
var config = this;
config.filepath = '';
config.dbUsername = '';
config.dbPassword = '';
config.dbRootUser = '';
config.dbRootPassword = '';
config.dbHost = '';
config.dbPort = 0;
config.userExpirationDays = 0;
config.logLevel = '';
config.fromData = function (data) {
config.filepath = data.filepath;
config.dbUsername = data.dbUsername;
config.dbPassword = data.dbPassword;
config.dbRootUser = data.dbRootUser;
config.dbRootPassword = data.dbRootPassword;
config.dbHost = data.dbHost;
config.dbPort = parseInt(data.dbPort);
config.userExpirationDays = parseInt(data.userExpirationDays);
config.logLevel = data.logLevel;
};
if (angular.isDefined(data)) {
config.fromData(data);
}
}
return Config;
} //end configService function
})();
@@ -0,0 +1,39 @@
(function () {
'use strict';
/**
* DESCRIPTION: Defines an creds object
*/
angular.module('portal.common.services.model.cache')
.service('Credentials', credentialsService);
function credentialsService(Map) {
function Credentials(data) {
var creds = this;
creds.id = null;
creds.uid = '';
creds.username = '';
creds.password = '';
creds.name = '';
creds.credentialType = '';
creds.key = '';
creds.passphrase = '';
creds.fromData = function (data) {
creds.id = data.id;
creds.uid = data.uid;
creds.username = data.username;
creds.name = data.name;
creds.credentialType = data.credentialType;
creds.key = '';
creds.passphrase = '';
};
if (angular.isDefined(data)) {
creds.fromData(data);
}
}
return Credentials;
} //end credentialsService function
})();
@@ -0,0 +1,30 @@
(function () {
'use strict';
/**
* DESCRIPTION: Defines an creds object
*/
angular.module('portal.common.services.model.cache')
.service('DropDownItem', dropDownService);
function dropDownService(Map) {
function DropDownItem(data) {
var creds = this;
creds.id = null;
creds.name = '';
creds.value = '';
creds.fromData = function (data) {
creds.id = data.id;
creds.name = data.name;
creds.value = data.value;
};
if (angular.isDefined(data)) {
creds.fromData(data);
}
}
return DropDownItem;
} //end dropDownService function
})();
@@ -0,0 +1,40 @@
(function () {
'use strict';
/**
* DESCRIPTION: Defines an Account object, which defines the person who has
* authenticated with the server.
*/
angular.module('portal.common.services.model.cache')
.service('EmailTemplate', emailTmplService);
function emailTmplService(Map, Account) {
function EmailTemplate(data) {
var emailTmpl = this;
emailTmpl.id = null;
emailTmpl.emailName = '';
emailTmpl.emailSubject = '';
emailTmpl.emailMessage = '';
emailTmpl.scriptId = '';
emailTmpl.recipients = [];
emailTmpl.fromData = function (data) {
emailTmpl.id = data.id;
emailTmpl.emailName = data.emailName;
emailTmpl.emailSubject = data.emailSubject;
emailTmpl.emailMessage = data.emailMessage;
emailTmpl.scriptId = data.scriptId;
emailTmpl.recipients = [];
$.each(data.recipients, function(key, value){
emailTmpl.recipients.push(new Account(value));
});
};
if (angular.isDefined(data)) {
emailTmpl.fromData(data);
}
}
return EmailTemplate;
} //end emailTmplService function
})();
@@ -0,0 +1,42 @@
(function () {
'use strict';
/**
* DESCRIPTION: Defines an creds object
*/
angular.module('portal.common.services.model.cache')
.service('GitInfo', gitInfoService);
function gitInfoService(Map, Credentials) {
function GitInfo(data) {
var gitInfo = this;
gitInfo.id = null;
gitInfo.name = '';
gitInfo.scm = '';
gitInfo.branch = '';
gitInfo.directory = '';
gitInfo.lastUpdated = null;
gitInfo.createDate = null;
gitInfo.createdBy = '';
gitInfo.credentials = null;
gitInfo.fromData = function (data) {
gitInfo.id = data.id;
gitInfo.name = data.name;
gitInfo.scm = data.scm;
gitInfo.branch = data.branch;
gitInfo.directory = data.directory;
gitInfo.credentials = new Credentials(data.credentials);
gitInfo.lastUpdated = data.lastUpdated;
gitInfo.createDate = data.createDate;
gitInfo.createdBy = data.createdBy;
};
if (angular.isDefined(data)) {
gitInfo.fromData(data);
}
}
return GitInfo;
} //end gitInfoService function
})();
@@ -0,0 +1,28 @@
(function () {
'use strict';
angular.module('portal.common.services.model.cache')
.service('HashType', hashTypeService);
function hashTypeService(Map) {
function HashType(data) {
var hash = this;
hash.id = null;
hash.name = '';
hash.displayName = '';
hash.valid = false;
hash.length = null;
if (angular.isDefined(data)) {
hash.id = data.id;
hash.name = data.name;
hash.displayName = data.displayName;
hash.valid = data.valid === 'true' || data.valid === true;
hash.length = parseInt(data.length);
}
}
return HashType;
}
})();
@@ -0,0 +1,30 @@
(function () {
'use strict';
/**
* DESCRIPTION: Defines an Account object, which defines the person who has
* authenticated with the server.
*/
angular.module('portal.common.services.model.cache')
.service('LoggerInfo', loggerService);
function loggerService(Map) {
function LoggerInfo(data) {
var info = this;
info.logger = '';
info.level = '';
info.fromData = function (data) {
info.logger = data.logger;
info.level = data.level;
};
if (angular.isDefined(data)) {
info.fromData(data);
}
}
return LoggerInfo;
} //end configService function
})();
@@ -0,0 +1,85 @@
(function () {
'use strict';
angular.module('portal.common.services.model.cache')
.service('permissionObjects', permissionService);
function permissionService(Map) {
/* jshint validthis: true */
var permissionObjects = this;
this.PermissionGroup = function(data) {
this.id = null;
this.name = '';
this.displayName = '';
this.enabled = false;
this.permissions = [];
if (data) {
this.id = data.id;
this.name = data.name;
this.displayName = data.displayName;
this.enabled = data.enabled;
this.permissions = [];
if(data.permissions) {
for (var i = 0; i < data.permissions.length; i++) {
this.permissions.push(new permissionObjects.PermissionGroupPermission(data.permissions[i]));
}
}
}
};
this.PermissionGroupPermission = function(data) {
this.type = 'PermissionGroupPermission';
this.id = null;
this.permissionId = null;
this.permissionGroupId = null;
this.name = '';
this.displayName = '';
this.permissionCategory = '';
this.allowed = false;
if (data) {
this.type = 'PermissionGroupPermission';
this.id = data.id;
this.permissionId = data.permissionId;
this.permissionGroupId = data.permissionGroupId;
this.name = data.name;
this.displayName = data.displayName;
this.permissionCategory = data.permissionCategory;
this.allowed = data.allowed;
}
};
this.PermissionCategory = function(data) {
this.id = null;
this.name = '';
this.displayName = '';
this.permissions = [];
if (data) {
this.id = data.id;
this.name = data.name;
this.displayName = data.displayName;
this.permissions = [];
if (data.permissions) {
for (var i = 0; i < data.permissions.length; i++) {
this.permissions.push(new permissionObjects.Permission(data.permissions[i]));
}
}
}
};
this.Permission = function(data) {
this.type = 'Permission';
this.id = null;
this.name = '';
this.displayName = '';
this.permissionCategory = '';
if (data) {
this.id = data.id;
this.name = data.name;
this.displayName = data.displayName;
this.permissionCategory = data.permissionCategory;
}
};
} //end permissionService function
})();
@@ -0,0 +1,33 @@
(function () {
'use strict';
/**
* DESCRIPTION: Defines an resource file object,
*/
angular.module('portal.common.services.model.cache')
.service('ResourceFile', resourceFileService);
function resourceFileService(Map) {
function ResourceFile(data) {
var resourceFile = this;
resourceFile.id = '';
resourceFile.fileName = '';
resourceFile.fileLocation = '';
resourceFile.fileType = '';
resourceFile.dateCreated = '';
resourceFile.valid = false;
if (angular.isDefined(data)) {
resourceFile.id = data.id;
resourceFile.fileName = data.fileName;
resourceFile.fileLocation = data.fileLocation;
resourceFile.fileType = data.fileType;
resourceFile.dateCreated = data.dateCreated;
resourceFile.valid = data.valid;
}
}
return ResourceFile;
} //end patchFileService function
})();
@@ -0,0 +1,207 @@
(function () {
'use strict';
/**
* DESCRIPTION: Defines an script object
*/
angular.module('portal.common.services.model.cache')
.service('scriptObjects', scriptService);
function scriptService(Map, Credentials, ResourceFile, EmailTemplate) {
/* jshint validthis: true */
var scriptObjects = this;
scriptObjects.Script = function (data) {
var script = this;
script.id = null;
script.name = '';
script.command = '';
script.baseDirectory = '';
script.outputDirectory = '';
script.scriptType = '';
script.parameters = [];
script.schedule = [];
script.scriptVariables = [];
script.scriptChain = [];
script.scriptEmails = [];
script.remote = null;
script.scp = null;
if (data) {
script.id = data.id;
script.name = data.name;
script.command = data.command;
script.baseDirectory = data.baseDirectory;
script.outputDirectory = data.outputDirectory;
script.scriptType = data.scriptType;
script.remote = new scriptObjects.ScriptRemote(data.remote);
script.scp = new scriptObjects.ScriptScp(data.scp);
script.parameters = [];
script.schedule = [];
script.scriptVariables = [];
script.scriptEmails = [];
$.each(data.parameters, function(key, value) {
script.parameters.push(new scriptObjects.ScriptParameter(value));
});
$.each(data.schedule, function(key, value) {
script.schedule.push(new scriptObjects.ScriptSchedule(value));
});
$.each(data.scriptVariables, function(key, value) {
script.scriptVariables.push(new scriptObjects.ScriptEnvironmentVariable(value));
});
$.each(data.scriptChain, function(key, value) {
script.scriptChain.push(new scriptObjects.ScriptChain(value));
});
$.each(data.scriptEmails, function(key, value) {
script.scriptEmails.push(new EmailTemplate(value));
});
}
};
scriptObjects.ScriptSchedule = function(data) {
var schedule = this;
schedule.id = null;
schedule.jobId = '';
schedule.startDatetime = moment().toDate();
schedule.endDatetime = null;
schedule.frequency = null;
schedule.maxExecutions = null;
schedule.currentExecutionCount = null;
schedule.lastRun = null;
schedule.script = null;
schedule.executionStatus = null;
if (data) {
schedule.id = data.id;
schedule.jobId = data.jobId;
schedule.startDatetime = data.startDatetime;
schedule.endDatetime = data.endDatetime;
schedule.frequency = data.frequency;
schedule.maxExecutions = data.maxExecutions;
schedule.currentExecutionCount = data.currentExecutionCount;
schedule.lastRun = data.lastRun;
schedule.script = data.script;
schedule.executionStatus = data.executionStatus;
}
};
scriptObjects.ScriptParameter = function(data) {
var param = this;
param.id = null;
param.parameter = '';
param.script = '';
if (data) {
param.id = data.id;
param.parameter = data.parameter;
param.script = data.script;
}
};
scriptObjects.ScriptChain = function(data) {
var chain = this;
chain.id = null;
chain.parentScript = undefined;
chain.childScript = undefined;
chain.executeAfterMin = undefined;
chain.exitStatus = undefined;
if (data) {
chain.id = data.id;
chain.parentScript = data.parentScript;
chain.childScript = data.childScript;
chain.executeAfterMin = data.executeAfterMin;
chain.exitStatus = data.exitStatus;
}
};
scriptObjects.ScriptEnvironmentVariable = function(data) {
var envVar = this;
envVar.id = null;
envVar.name = '';
envVar.value = '';
envVar.createdBy = null;
envVar.script = null;
envVar.lastUpdated = '';
envVar.dateCreated = '';
envVar.isNew = true;
if (data) {
envVar.id = data.id;
envVar.name = data.name;
envVar.value = data.value;
envVar.createdBy = data.createdBy;
envVar.script = data.script;
envVar.lastUpdated = data.lastUpdated;
envVar.dateCreated = data.dateCreated;
envVar.isNew = false;
}
};
scriptObjects.ScriptStatus = function(data) {
var status = this;
status.id = undefined;
status.exitStatus = undefined;
status.results = '';
status.startTime = undefined;
status.endTime = undefined;
status.resourceFiles = [];
if (data) {
status.id = data.id;
status.exitStatus = data.exitStatus;
status.results = data.results;
status.startTime = data.startTime;
status.endTime = data.endTime;
if (data.resourceFiles) {
$.each(data.resourceFiles, function(key, value) {
status.resourceFiles.push(new ResourceFile(value));
});
}
}
};
scriptObjects.ScriptRemote = function(data) {
var remote = this;
remote.scriptId = undefined;
remote.scriptCredentials = null;
remote.url = undefined;
remote.port = undefined;
if (data) {
remote.scriptId = data.scriptId;
remote.url = data.url;
remote.port = data.port;
if (data.scriptCredentials) {
remote.scriptCredentials = new Credentials(data.scriptCredentials);
}
}
};
scriptObjects.ScriptScp = function(data) {
var scp = this;
scp.id = undefined;
scp.scriptId = undefined;
scp.fromHost = '';
scp.fromPort = 0;
scp.toHost = '';
scp.toPort = 0;
scp.dataRegex = '';
scp.toCredentials = undefined;
scp.fromCredentials = undefined;
if (data) {
scp.id = data.id;
scp.scriptId = data.scriptId;
scp.fromHost = data.fromHost;
scp.fromPort = data.fromPort;
scp.toHost = data.toHost;
scp.toPort = data.toPort;
scp.dataRegex = data.dataRegex;
if (data.toCredentials) {
scp.toCredentials = new Credentials(data.toCredentials);
}
if (data.fromCredentials) {
scp.fromCredentials = new Credentials(data.fromCredentials);
}
}
};
} //end scriptService function
})();
@@ -0,0 +1,75 @@
(function () {
'use strict';
/**
* DESCRIPTION:
*/
angular.module('portal.common.services.model.cache')
.service('UploadFile', uploadFileService);
function uploadFileService() {
function UploadFile() {
var file = this;
file.name = '';
file.fileSize = null;
file.guid = '';
file.url = '';
file.rawFile = null;
file.uploadProgress = 0;
file.percentComplete = 0;
file.uploaded = null;
file.reason = '';
file.trackUploadProcessing = false;
file.uploadMax = 0;
file.init = function (rawFile, trackUploadProcessing) {
file.trackUploadProcessing = trackUploadProcessing;
file.rawFile = rawFile;
file.name = rawFile.name;
file.fileSize = rawFile.size;
// The file.uploadMax represents when the file upload is complete. If tracking upload
// processing, the server sends percent complete values as triggers periodically so the max is 100 (%).
// Otherwise, just track the uploaded byte progress so the max is the file size.
file.uploadMax = trackUploadProcessing ? 100 : file.fileSize;
file.type = rawFile.type;
return file;
};
file.uploaded = function (data, baseURI) {
file.uploaded = true;
baseURI = baseURI === undefined ? '' : baseURI;
if (data !== undefined) {
file.name = data.original_name; //jshint ignore:line
file.fileSize = data.file_size; //jshint ignore:line
file.guid = data.guid;
file.url = baseURI + data.guid;
file.uploadProgress = file.fileSize;
}
return file;
};
file.setUploadProgress = function (uploadProgress) {
file.uploadProgress = uploadProgress;
file.percentComplete = Math.min(Math.floor((file.uploadProgress / file.fileSize) * 100), 100);
};
file.uploadFailed = function (reason) {
file.uploaded = false;
file.reason = reason;
if (reason === undefined) {
file.reason = 'unknown failure';
}
};
file.finished = function () {
return file.uploaded === true ? true : false;
};
file.inProgress = function () {
return file.upload === null;
};
file.failed = function () {
return file.uploaded === false ? true : false;
};
}
return UploadFile;
} //end uploadFileService function
})();
@@ -0,0 +1,137 @@
(function () {
'use strict';
/**
* DESCRIPTION: Defines a store, or access point to get data out of the cache and from an external source.
*/
angular.module('portal.common.services.model.cache')
.service('Store', storeService);
function storeService($timeout, Box) {
var cache = null;
/**
* Store defines the information required to access data from the cache (id) and
* pull it from an external source if it hasn't been pulled.
* @param {type} args {id: '', source: function}
* @returns {store_L35.storeService.Store}
*/
function Store(args) {
var store = this;
/**Attach the args and a few for convenience directly to the Store (below). */
store.args = args;
/**
* Unique ID for this store, this will be the . accessor on the mini cache.
*/
store.id = args.id;
/**
* A function with registerable callback that provides the data.
*/
store.source = args.source;
/**
* Empty params object, used in conjunction with Id to generate unique key for store.
* Passed in to the source as the args.
* @type Number|Number
*/
store.params = args.params;
/**
* Key used for accessing data from the cache.
*/
store.key = getKey();
/**
* Reference to the box accessed by the key.
*/
store.box = cache.get(store.key);
/**
* Listeners for this store to unsubscribe.
*/
store.boxListener = null;
/**
* Registers a callback to be notified of data changes. If the data has not been initialized it is
* initialized, once and only once. Subsequent data changes
* @param {type} callback
* @returns {unresolved}
*/
store.init = function () {
store.boxListener = store.box.init();
return store.boxListener;
};
/**
* Forces a refresh from source.
* @returns {undefined}
*/
store.refresh = function () {
var box = store.getBox();
return box.refresh();
};
/**
* Updates store on the cache, and notifies listeners.
* Could be called to update data on trigger.
* @param {type} data
* @returns {undefined}
*/
store.update = function (data) {
store.getBox().update(data);
};
/**
* @returns {Boolean} True if ready, false if pending or not initialized.
*/
store.isReady = function () {
return store.getBox().isDone();
};
store.getBox = function () {
return store.box;
};
store.unlisten = function () {
if (store.boxListener !== null) {
store.boxListener.unlisten();
}
};
store.getParams = function () {
return store.params;
};
function getKey() {
var key = store.id;
for (var i in store.params) {
key += '_' + i + '_' + store.params[i];
}
/**
* Init box if doesn't already exist.
* Box persists between instnaces.
*/
if (!angular.isDefined(cache.get(key))) {
cache.put(key, new Box(args));
}
return key;
}
}
/**
* Static function for registering the cache.
* @param {type} _cache
* @returns {undefined}
*/
Store.registerCache = function (_cache) {
cache = _cache;
};
Store.notifyStores = function(stores) {
for (var i in stores) {
stores[i].getBox().notify();
}
};
return Store;
} //end storeService function
})();
@@ -0,0 +1,60 @@
(function () {
'use strict';
/**
* DESCRIPTION: Stores for account.
*/
angular.module('portal.common.services.model.cache')
.service('accountStores', accountStoresService);
function accountStoresService(stores, Store, Account, accountProvider, triggerManager, Triggers, Map) {
var accountStores = {
Account: stores.inherit('account', function () {
Store.call(this, {
id: 'account',
source: accountProvider.isLoggedIn,
processGui: function (data) {
var act = new Account(data);
triggerManager.subscribe(act.stompTopics);
return act;
}});
}),
UserPool: stores.inherit('userPool', function(){
Store.call(this, {
id: 'userPool',
source: accountProvider.getAllUsers,
processGui: function(data) {
return Map.create(data, Account, 'id');
}
});
}),
};
Triggers.listen([Triggers.USER_ADDED], function(trigger, payload){
var data = payload.resources;
var users = new accountStores.UserPool();
if (users.isReady()) {
for (var i = 0; i < data.length; i++) {
var user = new Account(data[i]);
users.getBox().data.put(user.id, user);
}
users.getBox().notify();
}
});
Triggers.listen([Triggers.USER_DELETED], function(trigger, payload){
var data = payload.resources;
var users = new accountStores.UserPool();
if (users.isReady()) {
for (var i = 0; i < data.length; i++) {
var user = new Account(data[i]);
users.getBox().data.removeByKey(user.id, user);
}
users.getBox().notify();
}
});
return accountStores;
} //end accountStoresService function
})();
@@ -0,0 +1,33 @@
(function () {
'use strict';
/**
* DESCRIPTION: Stores for account.
*/
angular.module('portal.common.services.model.cache')
.service('appLogStores', appLogStoresService);
function appLogStoresService(stores, Store, ApplicationLog, appLogProvider, Map, Triggers) {
var appLogStores = {
Logs: stores.inherit('logs', function(){
Store.call(this, {
id: 'logs',
source: appLogProvider.getAllLogs,
processGui: function(data) {
return Map.create(data, ApplicationLog, 'id');
}
});
}),
};
Triggers.listen([Triggers.APP_LOGS_UPDATED, Triggers.APP_LOGS_PURGED], function(trigger, payload){
var data = payload.resources;
var logs = new appLogStores.Logs();
if (logs.isReady()) {
logs.getBox().refresh();
}
});
return appLogStores;
} //end accountStoresService function
})();
@@ -0,0 +1,35 @@
(function () {
'use strict';
/**
* DESCRIPTION: Stores for account.
*/
angular.module('portal.common.services.model.cache')
.service('configStores', configStoresService);
function configStoresService(stores, Store, Config, configProvider, Map) {
var copnfigStores = {
Configs: stores.inherit('configs', function () {
Store.call(this, {
id: 'configs',
source: configProvider.getConfiguration,
processGui: function (data) {
var act = new Config(data);
return act;
}});
}),
Config: stores.inherit('config', function (configKey) {
Store.call(this, {
id: 'config',
source: configProvider.getConfigurationValue,
params: configKey,
processGui: function (data) {
var conf = new Config(data);
return conf;
}});
}),
};
return copnfigStores;
} //end configStoresService function
})();
@@ -0,0 +1,34 @@
(function () {
'use strict';
/**
* DESCRIPTION: Stores for account.
*/
angular.module('portal.common.services.model.cache')
.service('credentialStores', credentialStoresService);
function credentialStoresService(stores, Store, Credentials, credentialProvider, Map, DropDownItem) {
var credentialsStores = {
Credentials: stores.inherit('credentials', function () {
Store.call(this, {
id: 'credentials',
source: credentialProvider.getCredentials,
processGui: function (data) {
var map = Map.create(data, Credentials, 'uid');
return map;
}});
}),
CredentialTypes: stores.inherit('credentialTypes', function(){
Store.call(this, {
id: 'credentialTypes',
source: credentialProvider.getCredentialTypes,
processGui: function(data) {
return Map.create(data, DropDownItem, 'id');
}
});
}),
};
return credentialsStores;
} //end credentialsStoresService function
})();
@@ -0,0 +1,25 @@
(function () {
'use strict';
/**
* DESCRIPTION: Stores for account.
*/
angular.module('portal.common.services.model.cache')
.service('gitStores', gitStoresService);
function gitStoresService(stores, Store, GitInfo, gitProvider, Map) {
var gitStores = {
Repos: stores.inherit('repos', function () {
Store.call(this, {
id: 'repos',
source: gitProvider.getAllRepos,
processGui: function (data) {
var map = Map.create(data, GitInfo, 'id');
return map;
}});
}),
};
return gitStores;
} //end gitStoresService function
})();
@@ -0,0 +1,26 @@
(function () {
'use strict';
/**
* DESCRIPTION: Stores for account.
*/
angular.module('portal.common.services.model.cache')
.service('loggerStores', loggerStoreService);
function loggerStoreService(stores, Store, LoggerInfo, loggerProvider, Map) {
var loggerStores = {
Loggers: stores.inherit('loggers', function(){
Store.call(this, {
id: 'loggers',
source: loggerProvider.getLoggers,
processGui: function(data) {
return Map.create(data, LoggerInfo, 'logger');
}
});
})
};
return loggerStores;
} //end loggerStopresService function
})();
@@ -0,0 +1,65 @@
(function () {
'use strict';
/**
* DESCRIPTION: Stores for account.
*/
angular.module('portal.common.services.model.cache')
.service('permissionStores', permissionStoresService);
function permissionStoresService(stores, Store, permissionObjects, permissionProvider, triggerManager, Triggers, Map) {
var permissionStores = {
PermissionGroups: stores.inherit('permissionGroups', function () {
Store.call(this, {
id: 'permissionGroups',
source: permissionProvider.getPermissionGroups,
processGui: function (data) {
return Map.create(data, permissionObjects.PermissionGroup, 'id');
}});
}),
AllPermissionGroups: stores.inherit('allPermissionGroups', function () {
Store.call(this, {
id: 'allPermissionGroups',
source: permissionProvider.getAllPermissionGroups,
processGui: function (data) {
return Map.create(data, permissionObjects.PermissionGroup, 'id');
}});
}),
PermissionCategories: stores.inherit('permissionCategories', function () {
Store.call(this, {
id: 'permissionCategories',
source: permissionProvider.getPermissionCategories,
processGui: function (data) {
return Map.create(data, permissionObjects.PermissionCategory, 'id');
}});
})
};
Triggers.listen([Triggers.PERMISSIONS_CHANGED, Triggers.PERMISSIONS_ADDED, Triggers.PERMISSIONS_UPDATED], function(trigger, payload){
var data = payload.resources;
var permGroups = new permissionStores.PermissionGroups();
if (permGroups.isReady()) {
for (var i = 0; i < data.length; i++) {
var permGroup = new permissionObjects.PermissionGroup(data[i]);
permGroups.getBox().data.put(permGroup.id, permGroup);
}
permGroups.getBox().notify();
}
});
Triggers.listen([Triggers.PERMISSIONS_DELETED], function(trigger, payload){
var data = payload.resources;
var permGroups = new permissionStores.PermissionGroups();
if (permGroups.isReady()) {
for (var i = 0; i < data.length; i++) {
var permGroup = new permissionObjects.PermissionGroup(data[i]);
permGroups.getBox().data.removeByKey(permGroup.id, permGroup);
}
permGroups.getBox().notify();
}
});
return permissionStores;
} //end permissionStoresService function
})();
@@ -0,0 +1,33 @@
(function () {
'use strict';
/**
* DESCRIPTION: Stores for resource file.
*/
angular.module('portal.common.services.model.cache')
.service('resourceFileStores', resourceFileStoresService);
function resourceFileStoresService(stores, Store, ResourceFile, fileProvider, Map) {
var resourceFileStores = {
PatchFiles: stores.inherit('patchFiles', function (args) {
Store.call(this, {
id: 'patchFiles',
source: fileProvider.getAllFiles,
processGui: function (data) {
return Map.create(data, ResourceFile, 'id');
}});
}),
Directories: stores.inherit('patchDirectories', function () {
Store.call(this, {
id: 'patchDirectories',
source: fileProvider.getDirectories,
processGui: function (data) {
return data;
}});
}),
};
return resourceFileStores;
} //end patchFileStoresService function
})();
@@ -0,0 +1,130 @@
(function () {
'use strict';
/**
* DESCRIPTION: Stores for account.
*/
angular.module('portal.common.services.model.cache')
.service('scriptStores', scriptStoresService);
function scriptStoresService(stores, Store, scriptObjects, scriptProvider, DropDownItem, Map, Triggers, portalUtils) {
var scriptStores = {
Scripts: stores.inherit('scripts', function(){
Store.call(this, {
id: 'scripts',
source: scriptProvider.getAllScripts,
processGui: function(data) {
return Map.create(data, scriptObjects.Script, 'id');
}
});
}),
ScriptTypes: stores.inherit('scriptTypes', function(){
Store.call(this, {
id: 'scriptTypes',
source: scriptProvider.getScriptType,
processGui: function(data) {
return Map.create(data, DropDownItem, 'id');
}
});
}),
ScheduleFrequencies: stores.inherit('scheduleFrequencies', function(){
Store.call(this, {
id: 'scheduleFrequencies',
source: scriptProvider.getScheduleFrequencies,
processGui: function(data) {
return Map.create(data, DropDownItem, 'id');
}
});
}),
ScriptStatus: stores.inherit('scriptStatus', function(jobId){
Store.call(this, {
id: 'scriptStatus',
source: scriptProvider.getScriptStatus,
params: jobId,
processGui: function(data) {
return Map.create(data, scriptObjects.ScriptStatus, 'id');
}
});
})
};
Triggers.listen([Triggers.SCRIPT_ADDED, Triggers.SCRIPT_UPDATED], function(trigger, payload){
var data = payload.resources;
var scripts = new scriptStores.Scripts();
if (scripts.isReady()) {
for (var i = 0; i < data.length; i++) {
var script = new scriptObjects.Script(data[i]);
scripts.getBox().data.put(script.id, script);
}
scripts.getBox().notify();
}
});
Triggers.listen([Triggers.SCRIPT_DELETED], function(trigger, payload){
var data = payload.resources;
var scripts = new scriptStores.Scripts();
if (scripts.isReady()) {
for (var i = 0; i < data.length; i++) {
var script = new scriptObjects.Script(data[i]);
scripts.getBox().data.removeByKey(script.id, script);
}
scripts.getBox().notify();
}
});
Triggers.listen([Triggers.SCRIPT_SCHEDULE_DELETED], function(trigger, payload){
var data = payload.resources;
var scripts = new scriptStores.Scripts();
var schedule = new scriptObjects.ScriptSchedule(data[0]);
if (scripts.isReady()) {
var scriptBox = scripts.getBox().data.values;
for (var i = 0; i < scriptBox.length; i++) {
if(schedule.script === scriptBox[i].id) {
for (var j = 0; j < scriptBox[i].schedule.length; j++) {
if (schedule.jobId === scriptBox[i].schedule[j].jobId) {
scriptBox[i].schedule.splice(j, 1);
break;
}
}
break;
}
}
scripts.getBox().notify();
}
});
Triggers.listen([Triggers.SCRIPT_COMPLETED], function(trigger, payload) {
if (!payload.resources) {
return;
}
var data = payload.resources;
var scripts = new scriptStores.Scripts();
var script = new scriptObjects.Script(data[1]);
if (scripts.isReady()) {
var scriptsBox = scripts.getBox().data.values;
for (var x = 0; x < scriptsBox.length; x++) {
if (scriptsBox[x].id === script.id) {
scriptsBox[x].schedule = script.schedule;
}
}
scripts.getBox().notify();
}
var scriptName = script.name;
var jobId = data[0];
var statusStr = 'Failed';
for (var j = 0; j < script.schedule.length; j++) {
var sched = script.schedule[j];
if (sched.jobId === jobId && sched.executionStatus === 0) {
statusStr = 'Success';
break;
}
}
portalUtils.toast('Script ' + scriptName +' completed with status of ' + statusStr, ['top', 'left'], 2000);
});
return scriptStores;
} //end scriptStoresService function
})();
@@ -0,0 +1,27 @@
(function () {
'use strict';
/**
* DESCRIPTION: Provides accessors to the cache(cacheService) getting data if
* it doesn't exist, providing promises to the data, and notification when
* the data changes.
*
*/
angular.module('portal.common.services.model.cache')
.service('stores', storesService);
function storesService(Store, $log, portalUtils) {
var stores = {};
return {
inherit: function (id, ChildStore) {
if (angular.isDefined(stores[id])) {
$log.error('Duplicate store with id - ' + id);
} else {
stores[id] = portalUtils.inherit(ChildStore, Store);
return stores[id];
}
}
};
} //end storesService function
})();
@@ -0,0 +1,92 @@
(function () {
'use strict';
/**
* DESCRIPTION: Stores for account.
*/
angular.module('portal.common.services.model.cache')
.service('systemStores', systemStoresService);
function systemStoresService(stores, Store, scriptObjects, systemProvider, Map, EmailTemplate, Triggers) {
var systemStores = {
EnvironmentVariables: stores.inherit('envvars', function(){
Store.call(this, {
id: 'envvars',
source: systemProvider.getAllEnvVars,
processGui: function(data) {
return Map.create(data, scriptObjects.ScriptEnvironmentVariable, 'id');
}
});
}),
SMTPConfig: stores.inherit('smtpConfig', function(){
Store.call(this, {
id: 'smtpConfig',
source: systemProvider.getSmtpConfig,
processGui: function(data) {
return Map.create(data, scriptObjects.ScriptEnvironmentVariable, 'id');
}
});
}),
EmailTemplates: stores.inherit('emailTmpls', function(){
Store.call(this, {
id: 'emailTmpls',
source: systemProvider.getEmailTemplates,
processGui: function(data) {
return Map.create(data, EmailTemplate, 'id');
}
});
}),
};
Triggers.listen([Triggers.EMAIL_TEMPLATE_UPDATED], function(trigger, payload){
var data = payload.resources;
var tmpls = new systemStores.EmailTemplates();
if (tmpls.isReady()) {
for (var i = 0; i < data.length; i++) {
var tmpl = new EmailTemplate(data[i]);
tmpls.getBox().data.put(tmpl.id, tmpl);
}
tmpls.getBox().notify();
}
});
Triggers.listen([Triggers.EMAIL_TEMPLATE_DELETED], function(trigger, payload){
var data = payload.resources;
var tmpls = new systemStores.EmailTemplates();
if (tmpls.isReady()) {
for (var i = 0; i < data.length; i++) {
var tmpl = new EmailTemplate(data[i]);
tmpls.getBox().data.removeByKey(tmpl.id, tmpl);
}
tmpls.getBox().notify();
}
});
Triggers.listen([Triggers.ENV_VARS_ADDED], function(trigger, payload){
var data = payload.resources;
var envvars = new systemStores.EnvironmentVariables();
if (envvars.isReady()) {
for (var i = 0; i < data.length; i++) {
var envvar = new scriptObjects.ScriptEnvironmentVariable(data[i]);
envvars.getBox().data.put(envvar.id, envvar);
}
envvars.getBox().notify();
}
});
Triggers.listen([Triggers.ENV_VARS_DELETED], function(trigger, payload){
var data = payload.resources;
var envvars = new systemStores.EnvironmentVariables();
if (envvars.isReady()) {
for (var i = 0; i < data.length; i++) {
var envvar = new scriptObjects.ScriptEnvironmentVariable(data[i]);
envvars.getBox().data.removeByKey(envvar.id, envvar);
}
envvars.getBox().notify();
}
});
return systemStores;
} //end systemStoresService function
})();
@@ -0,0 +1,76 @@
(function () {
'use strict';
/**
* DESCRIPTION: Defines the restful calls for the account server module.
*/
angular.module('portal.common.services.model.rest')
.factory('accountProvider', accountProviderService);
function accountProviderService(rest, Account) {
var baseUrl = '/account';
return {
isLoggedIn: function () {
return rest.get({
id: baseUrl + '/isLoggedIn.do',
convert: function (data) {
return new Account(data);
}
});
},
getAllUsers: function() {
return rest.get({
id: baseUrl + '/getAll.do',
});
},
/**
* Login.
* @param {type} args password, username
* @returns {undefined}
*/
login: function (username, password) {
return rest.put({
id: baseUrl + '/login.do',
block: true,
data: {username: username, password: password}
});
},
/**
* Logout.
* @param {type}
* @returns {undefined}
*/
logout: function () {
return rest.put({
id: baseUrl + '/logout.do'
});
},
addUser: function(user) {
return rest.put({
id: baseUrl + '/addUser.do',
data: user
});
},
deleteUser: function(user) {
return rest.put({
id: baseUrl + '/deleteUser.do',
data: user
});
},
getRoleData: function(data) {
return rest.put({
id: baseUrl + '/getRoleData.do',
data: {type: data}
});
},
getUserInfo: function(args) {
return rest.get({
id: baseUrl + '/getUserInfo.do',
data: args,
cache: false
});
}
};
} //end accountProviderService function
})();
@@ -0,0 +1,26 @@
(function () {
'use strict';
/**
* DESCRIPTION: Defines the restful calls for the account server module.
*/
angular.module('portal.common.services.model.rest')
.factory('appLogProvider', appLogProviderService);
function appLogProviderService(rest) {
var baseUrl = '/logs';
return {
getAllLogs: function () {
return rest.get({
id: baseUrl + '/getAll.do',
});
},
purgeLogs: function(date) {
return rest.post({
id: baseUrl + '/purge.do',
data: date
});
}
};
} //end configProviderService function
})();
@@ -0,0 +1,33 @@
(function () {
'use strict';
/**
* DESCRIPTION: Defines the restful calls for the account server module.
*/
angular.module('portal.common.services.model.rest')
.factory('configProvider', configProviderService);
function configProviderService(rest, Config) {
var baseUrl = '/config';
return {
getConfiguration: function () {
return rest.get({
id: baseUrl + '/getConfiguration.do',
});
},
getConfigurationValue: function (value) {
return rest.get({
id: baseUrl + '/getConfigurationValue.do',
data: value
});
},
saveConfiguration: function(config) {
return rest.put({
id: baseUrl + '/saveConfiguration.do',
data:config
});
}
};
} //end configProviderService function
})();
@@ -0,0 +1,38 @@
(function () {
'use strict';
/**
* DESCRIPTION: Defines the restful calls for the account server module.
*/
angular.module('portal.common.services.model.rest')
.factory('credentialProvider', credentialProviderService);
function credentialProviderService(rest, Credentials) {
var baseUrl = '/creds';
return {
addCredentials: function (args) {
return rest.put({
id: baseUrl + '/add.do',
data: args,
});
},
getCredentials : function() {
return rest.get({
id: baseUrl + '/get.do'
});
},
deleteCredentials: function(entity) {
return rest.put({
id: baseUrl + '/delete.do',
data: entity
});
},
getCredentialTypes: function() {
return rest.get({
id: baseUrl + '/getCredentialTypes.do'
});
}
};
} //end accountProviderService function
})();
@@ -0,0 +1,22 @@
(function () {
'use strict';
/**
* DESCRIPTION: Defines the restful calls for the file server module.
*/
angular.module('portal.common.services.model.rest')
.factory('fileProvider', fileProviderService);
function fileProviderService(rest) {
var baseUrl = '/file';
return {
deleteFile: function(resourceFile) {
return rest.put({
id: baseUrl + '/delete.do',
data: resourceFile
});
}
};
} //end fileProviderService function
})();
@@ -0,0 +1,39 @@
(function () {
'use strict';
/**
* DESCRIPTION: Defines the restful calls for the git server module.
*/
angular.module('portal.common.services.model.rest')
.factory('gitProvider', gitProviderService);
function gitProviderService(rest, GitInfo) {
var baseUrl = '/git';
return {
addGitRepo: function(gitInfo) {
return rest.put({
id: baseUrl + '/add.do',
data: gitInfo
});
},
getAllRepos : function() {
return rest.get({
id: baseUrl + '/getAll.do'
});
},
deleteRepo: function(entity) {
return rest.put({
id: baseUrl + '/delete.do',
data: entity
});
},
pullRepo: function(entity) {
return rest.put({
id: baseUrl + '/pull.do',
data: entity
});
}
};
} //end gitProviderService function
})();
@@ -0,0 +1,27 @@
(function () {
'use strict';
/**
* DESCRIPTION: Defines the restful calls for the logger provider server module.
*/
angular.module('portal.common.services.model.rest')
.factory('loggerProvider', loggerProviderSerice);
function loggerProviderSerice(rest, Config) {
var baseUrl = '/logger';
return {
getLoggers: function () {
return rest.get({
id: baseUrl + '/getLoggers.do',
});
},
setLoggers: function(loggers) {
return rest.put({
id: baseUrl + '/setLoggers.do',
data: loggers
});
}
};
} //end loggerProviderSerice function
})();
@@ -0,0 +1,42 @@
(function () {
'use strict';
/**
* DESCRIPTION: Defines the restful calls for the permissions server module.
*/
angular.module('portal.common.services.model.rest')
.factory('permissionProvider', permissionProviderService);
function permissionProviderService(rest) {
var baseUrl = '/permissions';
return {
getPermissionGroups: function () {
return rest.get({
id: baseUrl + '/getPermissionGroups.do',
});
},
getAllPermissionGroups: function () {
return rest.get({
id: baseUrl + '/getAll.do',
});
},
getPermissionCategories: function () {
return rest.get({
id: baseUrl + '/getPermissionCategories.do',
});
},
updatePermissions: function (isNew, args) {
return rest.put({
id: baseUrl + (isNew ? '/addPermssionCategory.do' : '/updatePermissionCategory.do'),
data: args
});
},
deletePermissionGroup: function (args) {
return rest.put({
id: baseUrl + '/deletePermissionGroup.do',
data: args
});
}
};
} //end permissionProviderService function
})();
@@ -0,0 +1,177 @@
(function () {
'use strict';
/**
* DESCRIPTION: Describes a server rest request.
* Defines the promise where data is returned.
*/
angular.module('portal.common.services.model.rest')
.factory('Request', requestService);
function requestService($http, $q, $rootScope, $window) {
/**
* Request Object and promise.
* @param {type} requestData {id, params, data}
*/
function Request(args) {
var request = this;
var deferred = $q.defer();
request.id = args.id;
request.params = args.params;
request.data = args.data;
request.process = args.process;
request.cache = args.cache ? true : false;
request.payload = null;
request.block = args.block;
function apply() {
if (request.block) {
$rootScope.loadingBlock = true;
}
//angular.toJson(request.data);
$http({
method: 'POST',
url: Request.baseURI + request.id,
params: request.params,
headers: {'Content-Type': Request.jsonContentType, 'dataType': Request.jsonDataType},
data: request.data,
cache: request.cache
}).then(onSuccess, onError).catch(onError);
return deferred.promise;
}
/**
* Handler for the $http request.
* @param {type} returnData
* @returns {undefined}
*/
function onSuccess(returnData, status, header, config) {
if (returnData.data) {
if (returnData.data.hasOwnProperty('body')) {
doSuccessSequence(returnData.data.body);
} else {
doSuccessSequence(returnData.data);
}
} else {
doErrorSequence(returnData.data, returnData.status);
}
$rootScope.loadingBlock = false;
}
/**
* Handles the sequence of callbacks for the success path.
* @param {type} data
* @returns {undefined}
*/
function doSuccessSequence(data) {
request.payload = data;
if (request.process) {
request.payload = request.process(data);
}
deferred.resolve(request.payload);
}
/**
* Handler for $http request.
* @param {type} data
* @returns {undefined}
*/
function onError(data, status, header, config) {
doErrorSequence(data.data, data.status);
$rootScope.loadingBlock = false;
}
/**
* Handles the sequence of callbacks for the error path.
* @param {type} data
* @returns {undefined}
*/
function doErrorSequence(data, status) {
request.payload = data;
// if we've made a rest call and go to the login page, redirect
if (!data.hasOwnProperty('success') && status !== 400) {
$window.location.reload();
}
deferred.reject(request.payload);
}
/**
* Puts the data on the server.
* @returns {request_L35.requestService.Request}
*/
request.put = function () {
return apply();
};
/**
* Gets data from the server. (could retry in the future).
* @returns {request_L35.requestService.Request}
*/
request.get = function () {
return apply();
};
request.upload = function () {
var promises = [];
var files = request.data;
var params = request.params;
//Angular doesn't support progress, so we use JQUERY instead.
function sendUpload(file) {
var deferred = $q.defer();
var formData = new FormData();
formData.append('file', file.rawFile);
if (params !== undefined) {
$.each(params, function(key, value) {
formData.append(key, value);
});
}
$http({
method: 'POST',
url: Request.baseURI + request.id,
data: formData,
cache: false,
transformRequest: angular.identity,
headers: {'Content-Type': undefined, 'dataType': undefined}
}).then(onUploadSuccess, onUploadError).catch(onUploadError);
function onUploadError(data, status, header, config) {
file.uploadFailed(data.data.message);
deferred.reject(angular.fromJson(data.data));
}
function onUploadSuccess(data, status, header, config) {
var returnData = data.data;
if (returnData.success) {
if (returnData.body.length === 0) {
return;
}
file.uploaded(returnData.body[0], Request.baseURI + '/');
file.response = returnData.body;
deferred.resolve(file);
} else {
file.uploadFailed(returnData.message);
deferred.reject();
}
}
return deferred.promise;
}
//Server only supports a single file.
for (var i = 0; i < files.length; i++) {
promises.push(sendUpload(files[i]));
}
return $q.all(promises);
};
}
Request.registerCache = function (cache) {
$http.defaults.cache = cache;
};
// TEMPORARY: should be unneeded when this file is being served from baseURI
Request.baseURI = '/portal';
Request.jsonContentType = 'application/json; charset=utf-8';
Request.jsonDataType = 'json';
return Request;
} //end requestService function
})();
@@ -0,0 +1,38 @@
(function () {
'use strict';
/**
* DESCRIPTION: Contains wrappers for the request obejct to simplify/force
* the different calls to pick either get/put and facilitate different behavior for each of them.
*/
angular.module('portal.common.services.model.rest', ['ui.router'])
.service('rest', restService);
function restService(Request) {
return {
/**
* Wraps/creates a request that gets data from the server.
* @param {type} request
* @returns {unresolved}
*/
get: function (args) {
return new Request(args).get();
},
/**
* Wraps/creates a request that commits data to the server.
* @param {type} request
* @returns {unresolved}
*/
put: function (args) {
return new Request(args).put();
},
post: function(args) {
return new Request(args).put();
},
upload: function (args) {
return new Request(args).upload();
}
};
} //end restService function
})();
@@ -0,0 +1,64 @@
(function () {
'use strict';
/**
* DESCRIPTION: Defines the restful calls for the account server module.
*/
angular.module('portal.common.services.model.rest')
.factory('scriptProvider', scriptProviderService);
function scriptProviderService(rest, scriptObjects) {
var baseUrl = '/scripts';
return {
runScript: function(script) {
return rest.put({
id: baseUrl + '/runScript.do',
data: script
});
},
addScript: function(script) {
var endPoint = '/addScript.do';
if (script.id !== undefined && script.id !== null) {
endPoint = '/updateScript.do';
}
return rest.put({
id: baseUrl + endPoint,
data: script
});
},
getScriptStatus: function(jobId) {
return rest.put({
id: baseUrl + '/getScriptScheduleStatus.do',
data: jobId
});
},
deleteScript: function(script) {
return rest.put({
id: baseUrl + '/deleteScript.do',
data: script
});
},
deleteScriptSchedule: function(scriptSched) {
return rest.put({
id: baseUrl + '/deleteScriptSchedule.do',
data: scriptSched
});
},
getAllScripts: function() {
return rest.get({
id: baseUrl + '/getAll.do'
});
},
getScheduleFrequencies: function() {
return rest.get({
id: baseUrl + '/getScheduleFrequencies.do'
});
},
getScriptType: function() {
return rest.get({
id: baseUrl + '/getScriptType.do'
});
}
};
} //end scriptProviderService function
})();
@@ -0,0 +1,90 @@
(function () {
'use strict';
/**
* DESCRIPTION: Defines the restful calls for the account server module.
*/
angular.module('portal.common.services.model.rest')
.factory('systemProvider', scriptProviderService);
function scriptProviderService(rest, scriptObjects) {
var baseUrl = '/system';
return {
addEnvVars: function(envVars) {
var endPoint = '/addEnvVars.do';
var arrayItems = [];
if (!angular.isArray(envVars)) {
arrayItems.push(envVars);
} else {
arrayItems = envVars;
}
return rest.put({
id: baseUrl + endPoint,
data: arrayItems
});
},
updateSeed: function(seed) {
var endPoint = '/updateSeed.do';
return rest.put({
id: baseUrl + endPoint,
data: seed
});
},
updateSmtpConfig: function(smtpConf) {
var endPoint = '/updateSmtpConfig.do';
var arrayItems = [];
if (!angular.isArray(smtpConf)) {
arrayItems.push(smtpConf);
} else {
arrayItems = smtpConf;
}
return rest.put({
id: baseUrl + endPoint,
data: arrayItems
});
},
deleteEnvVar: function(envVars) {
var endPoint = '/deleteEnvVars.do';
var arrayItems = [];
if (!angular.isArray(envVars)) {
arrayItems.push(envVars);
} else {
arrayItems = envVars;
}
return rest.put({
id: baseUrl + endPoint,
data: arrayItems
});
},
getAllEnvVars: function() {
return rest.get({
id: baseUrl + '/getAll.do'
});
},
getSmtpConfig: function() {
return rest.get({
id: baseUrl + '/getSmtpConfig.do'
});
},
addEmailTemplate: function(tmpl) {
return rest.get({
id: baseUrl + '/addEmailTemplate.do',
data: tmpl
});
},
getEmailTemplates: function() {
return rest.get({
id: baseUrl + '/getEmailTemplates.do'
});
},
deleteEmailTemplates: function(tmpl) {
return rest.get({
id: baseUrl + '/deleteEmailTemplate.do',
data: tmpl
});
},
};
} //end scriptProviderService function
})();
@@ -0,0 +1,40 @@
angular.module('portal').factory('permissions', permissionFactory);
function permissionFactory($rootScope, $state, portalUtils, $q, cache, accountStores, Triggers) {
Triggers.listen([Triggers.PERMISSIONS_CHANGED], function(trigger, payload){
new accountStores.Account().refresh();
$rootScope.$broadcast('permissionsChanged');
});
var permissions = {
canView: function (attrs) {
var deferred = $q.defer();
//Nothing defined (always true)
if (angular.isDefined(attrs) === false) {
deferred.resolve(true);
} else {
var mCache = cache.request([new accountStores.Account()]).then(function () {
var validRole = verifyRole(mCache, attrs);
deferred.resolve(validRole);
});
}
return deferred.promise;
}
};
/**
* Check that the user is one of the passed in roles
* @param {type} attrs attributes to check against
* @returns {Boolean}
*/
function verifyRole(mCache, attrs) {
var show = true;
if (angular.isDefined(attrs.permission)) {
show = mCache.account.data.hasPermission(attrs.permission);
}
return show;
}
return permissions;
}
@@ -0,0 +1,160 @@
(function () {
'use strict';
/**
* Manages the STOMP connections.
* @type String
*/
angular.module('portal.common.services.triggers').factory('triggerManager', function ($log, Triggers, $rootScope, Map, Request, portalUtils, $mdDialog, $state, cache, $window) {
var subscriptions = new Map();
var stompClient = null;
var allTopics = [];
var showTimeout = true;
var retryCounter = 0;
var useStomp = true;
function reconnect(onSuccess) {
if (stompClient !== null && stompClient.connected) {
stompClient.disconnect();
}
console.log('Reconnecting....');
subscriptions = new Map();
stompClient = null;
stompClient = null;
connect(onSuccess);
}
function connect(onSuccess) {
if (stompClient === null) {
var socket = new SockJS(Request.baseURI + '/ws/stomp');
stompClient = Stomp.over(socket);
// turns off printing out the contents of all messages
stompClient.debug = null;
}
if (!stompClient.connected) {
stompClient.connect({}, function (frame) {
$log.log('Stomp connection success');
portalUtils.call(onSuccess);
retryCounter = 0;
}, function (error) {
// this is called if the connection closes or times out.
// Should we display a notice to the user? auto-reconnect?
$log.log('Stomp connection error: ' + error);
if (retryCounter < 6) {
setTimeout(function() { reconnect(onSuccess); }, 5000);
retryCounter++;
}
else if (showTimeout) {
var modal = $mdDialog.show({
templateUrl: 'common/partials/session-end/session-end.html',
controller: 'SessionEndCtrl',
clickOutsideToClose: false,
escapeToClose: false,
locals: {
modalInstance: {
message: 'Session lost. Please click below to connect',
btnText: 'Connect',
onOkay: function() {
stompClient = null;
retryCounter = 0;
reconnect(onSuccess);
$mdDialog.cancel();
}
}
}
});
}
showTimeout = true;
});
} else {
portalUtils.call(onSuccess);
}
}
function disconnect(callback) {
subscriptions = new Map();
if (stompClient !== null) {
showTimeout = false;
stompClient = null;
} else {
portalUtils.call(callback);
}
}
function stompMsgReceived(message) {
var trigger = angular.fromJson(message.body);
//$log.log('Received Trigger: ' + trigger.type + '\n' + message.body);
processTrigger(trigger);
}
function processTrigger(trigger) {
//This function comes from stomp, which comes in on a non-angular javascript turn.
//That means we need to call apply ourselves. If we are ever in a digest
//cycle at this point in the code, something is wrong
$rootScope.$apply(function () {
Triggers.notify(Triggers[trigger.type], trigger);
});
}
function subscribe() {
if (stompClient === null || stompClient === undefined || !stompClient.connected) {
connect(function () {
subscribe();
});
} else {
for (var x = 0; x < allTopics.length; x++) {
var topic = allTopics[x];
if (!subscriptions.containsKey(topic)) {
var subscription = stompClient.subscribe(topic, stompMsgReceived);
subscription.topic = topic;
subscriptions.put(topic, subscription);
}
}
}
}
function unsubscribe(topic) {
var subscription = subscriptions.get(topic);
if (subscription !== undefined) {
subscription.unsubscribe();
}
subscriptions.removeByKey(topic);
var index = allTopics.indexOf(topic);
if (index > -1) {
allTopics.splice(index, 1);
}
}
function unsubscribeAll() {
for (var i = 0; i < subscriptions.length; i++) {
var sub = subscriptions.values[i];
sub.unsubscribe();
subscriptions.removeByKey(sub.topic);
}
allTopics.length = 0;
}
return {
subscribe: function (topics) {
//unsubscribeAll(); //For now unsubscribe all, eventually want to support listening for more than one.
for (var x = 0; x < topics.length; x++) {
var index = allTopics.indexOf(topics[x]);
if (index < 0) {
allTopics.push(topics[x]);
}
}
connect(function () {
subscribe();
});
},
unsubscribe: unsubscribe,
disconnect: disconnect,
unsubscribeAll: unsubscribeAll
};
});
})();
@@ -0,0 +1,168 @@
(function () {
'use strict';
/**
* DESCRIPTION:
*/
angular.module('portal.common.services.triggers', ['ui.router'])
.factory('Triggers', triggersService);
function triggersService($log, portalUtils, Map) {
function Trigger(id, validatorFn, preCall) {
var trigger = this;
trigger.id = id;
trigger.validate = validatorFn;
if (!angular.isFunction(trigger.validate)) {
trigger.validate = function () {
return true;
};
}
Object.defineProperties(trigger, {
isValid: {
get: trigger.validate
}
});
trigger.preCall = true;
if (angular.isDefined(preCall)) {
trigger.preCall = preCall;
}
}
Trigger.prototype.toString = function () {
return this.id;
};
var triggers = {
APP_LOGS_UPDATED: new Trigger('APP_LOGS_UPDATED', undefined, false),
APP_LOGS_PURGED: new Trigger('APP_LOGS_PURGED', undefined, false),
SCRIPT_COMPLETED: new Trigger('SCRIPT_COMPLETED', undefined, false),
SCRIPT_DELETED: new Trigger('SCRIPT_DELETED', undefined, false),
SCRIPT_ADDED: new Trigger('SCRIPT_ADDED', undefined, false),
SCRIPT_UPDATED: new Trigger('SCRIPT_UPDATED', undefined, false),
SCRIPT_SCHEDULE_DELETED: new Trigger('SCRIPT_SCHEDULE_DELETED', undefined, false),
USER_ADDED: new Trigger('USER_ADDED', undefined, false),
USER_DELETED: new Trigger('USER_DELETED', undefined, false),
HASH_TYPES_CHANGED: new Trigger('HASH_TYPES_CHANGED', undefined, false),
PERMISSIONS_DELETED: new Trigger('PERMISSIONS_DELETED', undefined, false),
PERMISSIONS_CHANGED: new Trigger('PERMISSIONS_CHANGED', undefined, false),
PERMISSIONS_UPDATED: new Trigger('PERMISSIONS_UPDATED', undefined, false),
PERMISSIONS_ADDED: new Trigger('PERMISSIONS_ADDED', undefined, false),
FILE_DELETED: new Trigger('FILE_DELETED', undefined, false),
ENV_VARS_ADDED: new Trigger('ENV_VARS_ADDED', undefined, false),
ENV_VARS_DELETED: new Trigger('ENV_VARS_DELETED', undefined, false),
EMAIL_TEMPLATE_UPDATED: new Trigger('EMAIL_TEMPLATE_UPDATED', undefined, false),
EMAIL_TEMPLATE_DELETED: new Trigger('EMAIL_TEMPLATE_DELETED', undefined, false),
SMTP_CONFIG_UPDATED: new Trigger('SMTP_CONFIG_UPDATED', undefined, false),
SEED_UPDATED: new Trigger('SEED_UPDATED', undefined, false),
};
triggers.Trigger = Trigger;
/**
* Registers to be notified when the passed in triggers are fired.
* @param {type} params {required:array[Trigger],optional:array[Trigger]}
* @param {type} callback
* @returns {cache_L40.listen.cacheAnonym$4|undefined}
*/
triggers.listen = function (params, callback) {
var optional = [];
var ids = [];
if (angular.isArray(params)) {
optional = params.slice();
} else if (params instanceof Trigger) {
optional.push(params);
}
//Warn if data is incorrect.
if (optional.length === 0) {
$log.error('Attempting to listen for triggers without correct parameters');
return;
}
for (var j = 0; j < optional.length; j++) {
ids.push(subscribe(optional[j], callback));
}
return {unlisten: function () {
unsubscribe(ids);
}};
};
/**
* Starting subscriber id for new listeners
* @type Number
*/
var subscriberId = 0;
/**
*
* @type cache_L40.MapMap of listeners.
*/
var subscribersMap = new Map('id', 'trigger');
/**
* Defines a subscriber object.
* @param {type} trigger
* @param {type} callback
* @param {type} id
* @returns {undefined}
*/
function Subscriber(trigger, callback, id) {
var subscriber = this;
subscriber.trigger = trigger;
subscriber.callback = callback;
subscriber.id = id;
}
/**
* Function for managing subscription map.
* @param {type} trigger
* @param {type} callback
* @param {type} now
* @returns {Number}
*/
function subscribe(trigger, callback) {
if (trigger instanceof Trigger) {
subscribersMap.put(subscriberId, new Subscriber(trigger, callback, subscriberId));
return subscriberId++;
} else {
$log.error('Failed to listen on invalid trigger.');
}
}
/**
* Function for itterating over ids and unsubscribing.
* @param {type} ids
* @returns {undefined}
*/
function unsubscribe(ids) {
for (var i = 0; i < ids.length; i++) {
subscribersMap.removeByKey(ids[i]);
}
}
/**
* Notifies cache listeners of an event, propagates the data passed in.
* @param {type} trigger
* @param {type} data
* @returns {undefined}
*/
triggers.notify = function (trigger, data) {
if (trigger instanceof Trigger) {
var subsMap = subscribersMap.getGroup('trigger', trigger);
for (var i = 0; i < subsMap.length; i++) {
var sub = subsMap.values[i];
call(sub.callback, trigger, data);
}
} else {
$log.error('Failed to notify on invalid trigger.');
}
};
function call(callback, trigger, data) {
window.setTimeout(function () {
portalUtils.call(callback, trigger, data);
}, 0);
}
return triggers;
} //end triggersService function
})();
@@ -0,0 +1,276 @@
angular.module('portal.common.services.portalUtils', ['ui.router'])
.service('portalUtils', function ($sce, $window, $mdToast, $mdDialog) {
this.trustAsHtml = function (string){
return $sce.trustAsHtml(string);
};
this.setScopeValue = function(scope, key, value, recurse) {
if (scope === undefined || scope === null) {
return;
}
if (key in scope) {
scope[key] = value;
return;
}
if (recurse) {
this.setScopeValue(scope.$parent, key, value, recurse);
}
};
this.hashSize = function(hash) {
var size = 0, key;
for (key in hash) {
if (hash.hasOwnProperty(key)) {
size++;
}
}
return size;
};
this.stripHtml = function(htmlStr) {
var newStr = htmlStr.replace(/<(?:.|\n)*?>/gm, '');
return newStr;
};
function inArray(array, comparer) {
for (var i = 0; i < array.length; i++) {
if (comparer(array[i])) {
return true;
}
}
return false;
}
/**
* Push a value onto an array if it doesnt exist
*/
this.arrayPushIfNotExist = function(array, element, comparer) {
if (!inArray(array, comparer)) {
array.push(element);
}
};
this.isIE = function() {
var sAgent = $window.navigator.userAgent;
var idx = sAgent.indexOf('MSIE');
// If IE, return version number.
if (idx > 0) {
return true;
}
// If IE 11 then look for Updated user agent string.
else if (sAgent.match(/Trident\/7\./)) {
return true;
}
else {
return false; //It is not IE
}
};
this.confirmBox = function(id, title, msg, showConfirm, returnFunction, newTemplate) {
var template, size;
if(newTemplate !== null && newTemplate !== undefined) {
template = newTemplate;
} else {
template = 'common/partials/templates/confirm-window.tmpl.html';
}
$mdDialog.show({
templateUrl: template,
skipHide: true,
multiple: true,
locals: {
modalInstance: {
btnId: id,
confirmTitle: title,
confirmMessage: msg,
showConfirmMessage: showConfirm
}
},
controller: ['$scope', 'modalInstance' , '$mdDialog', function($scope, modalInstance, $mdDialog) {
$scope.confirmTitle = modalInstance.confirmTitle;
$scope.confirmMessage = [];
if (angular.isArray(modalInstance.confirmMessage)) {
$scope.confirmMessage = modalInstance.confirmMessage;
} else {
$scope.confirmMessage.push(modalInstance.confirmMessage);
}
$scope.showConfirmMessage = modalInstance.showConfirmMessage;
$scope.btnId = modalInstance.btnId;
$scope.data = {
checkbox: false,
confirm: false,
choice: 'merge'
};
$scope.confirm = function() {
$scope.data.confirm = true;
$mdDialog.hide($scope.data);
};
$scope.cancel = function() {
$scope.data.confirm = false;
$mdDialog.hide($scope.data);
};
}]
}).then(function(disabledConfirm) {
returnFunction(disabledConfirm);
});
};
var toastPos = {
bottom: false,
top: false,
left: false,
right: false
};
function validPosition(position) {
return toastPos[position] !== undefined;
}
/**
* Allows for a toast message to be displayed on screen
* @param message: The message to be displayed
* @param position: The Position of the toast box (valid values are ['top'|'bottom'|'left'|'right'])
* @param duration: How long the toast message should be displayed
*/
this.toast = function(message, position, duration) {
toastPos.bottom = false;
toastPos.top = false;
toastPos.left = false;
toastPos.right = false;
if (Array.isArray(position)) {
for (var i = 0; i < position.length; i++) {
if (validPosition(position[i])) {
toastPos[position[i]] = true;
}
}
} else if (validPosition(position)) {
toastPos[position] = true;
}
var toastPosition = angular.extend({}, toastPos);
var pinTo = Object.keys(toastPosition)
.filter(function(pos) { return toastPosition[pos]; })
.join(' ');
$mdToast.show(
$mdToast.simple()
.textContent(message)
.position(pinTo)
.hideDelay(duration)
);
};
/**
* Converts space separated string to title case.
*
* See: http://stackoverflow.com/a/196991/1516011
*
* @param {type} str Any 'space separated string'
* @returns {undefined} returns 'space separated string' as 'Space Separated String'
*/
this.toTitleCase = function (str) {
if (str === null) {
return;
}
return str.replace(/\w\S*/g, function (txt) {
return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
});
};
/**
* Helper function to make calls to possibly undefined functions.
* First argument is the function to call.
* Rest of the arguements get passed to the callee
* @returns {undefined}
*/
this.call = function (callee) {
if (angular.isFunction(callee)) {
var calleeArgs = Array.prototype.slice.call(arguments, 1);
return callee.apply(this, calleeArgs);
}
};
this.createHash = function(array, Constructor, keyField) {
var hash = {};
for (var i in array) {
var obj = new Constructor(array[i]);
hash[obj[keyField]] = obj;
}
return hash;
} ;
/**
* Create an array
*
* @param {type} array An array of server objects;
* @param {type} Constructor A constructor to wrap the given data.
* @returns {Array} A wrapped array of the given type.
*/
this.createArray = function (array, Constructor) {
var objectArray = [];
for (var i in array) {
objectArray.push(new Constructor(array[i]));
}
return objectArray;
};
this.validEmail = function(text) {
var EMAIL_REGEX = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
var test = EMAIL_REGEX.test(text);
return test;
};
/**
* Allows for quick and easy inheritance of a parent class.
* @param {type} sub
* @param {type} parent
* @returns {unresolved}
*/
this.inherit = function (sub, parent) {
sub.prototype = Object.create(parent.prototype); //Available in Chrome (5), FF (4), IE (9), Safari (5).
sub.prototype.constructor = sub;
return sub;
};
this.arrayLength = function(array) {
return Object.keys(array).length;
};
this.createMap = function(data, Constructor, accessor) {
var map = {};
if (angular.isArray(data)) {
for (var i = 0; i < data.length; i++) {
var obj = new Constructor(data[i]);
map[obj[accessor]] = obj;
}
}
return map;
};
/* jshint ignore:start */
this.sortHashTable = function(hash) {
var tmpArray = [];
$.each(hash, function(key, value){
tmpArray[key] = value;
});
tmpArray = tmpArray.sort();
var tmpHash = {};
for (var index in tmpArray) {
tmpHash[index] = tmpArray[index];
}
return tmpHash;
};
/* jshint ignore:end */
});