<commit_before>var logger = require('_pr/logger')(module);
var CatalystCronJob = require('_pr/cronjobs/CatalystCronJob');
var AWSProvider = require('_pr/model/classes/masters/cloudprovider/awsCloudProvider.js');
var MasterUtils = require('_pr/lib/utils/masterUtil.js');
var appConfig = require('_pr/config');
var Cryptography = require('_pr/lib/utils/cryptography');
var EC2 = require('_pr/lib/ec2.js');
var instancesDao = require('_pr/model/classes/instance/instance');
var unManagedInstancesDao = require('_pr/model/unmanaged-instance');
var unassignedInstancesModel = require('_pr/model/unassigned-instances');
var async = require('async');
var tagsModel = require('_pr/model/tags');
var instanceLogModel = require('_pr/model/log-trail/instanceLog.js');
var instanceService = require('_pr/services/instanceService');
var socketIo = require('_pr/socket.io').getInstance();
var socketCloudFormationAutoScate = socketIo.of('/cloudFormationAutoScaleGroup');

socketCloudFormationAutoScate.on('connection', function(socket) {
    socket.on('joinCFRoom', function(data) {
        logger.debug('room joined', data);
        socket.join(data.orgId + ':' + data.bgId + ':' + data.projId + ':' + data.envId);
    });

});

var AWSProviderSync = Object.create(CatalystCronJob);
AWSProviderSync.execute = sync;

module.exports = AWSProviderSync;

// @TODO To be refactored (High Priority)
function sync() {
    var orgs = MasterUtils.getAllActiveOrg(function(err, orgs) {
        if (err) {
            logger.error('Unable to fetch orgs ==>', err);
            return;
        }
        if (!(orgs && orgs.length)) {
            logger.warn('No org found');
            return;
        }
        for (var i = 0; i < orgs.length; i++) {
            (function(org) {
                AWSProvider.getAWSProvidersByOrgId(org._id, function(err, providers) {
                    if (err) {
                        logger.error("Unable to get aws providers :", err);
                        return;
                    }
                    for (var j = 0; j < providers.length; j++) {
                        (function(provider) {
                            unassignedInstancesModel.getUnAssignedInstancesByProviderId(provider._id,
                                function(err, unassignedInstances) {
                                    if (err) {
                                        logger.error('Unable to fetch unassigned Instances by provider', err);
                                        return;
                                    }
                                    unManagedInstancesDao.getByOrgProviderId({
                                        orgId: org.rowid,
                                        providerId: provider._id,
                                        isDeleted: false
                                    }, function(err, unManagedInstances) {
                                        if (err) {
                                            logger.error('Unable to fetch Unmanaged Instances by org,provider', err);
                                            return;
                                        }
                                        instancesDao.getByOrgProviderId({
                                            orgId: org.rowid,
                                            providerId: provider._id,
                                            isDeleted: false
                                        }, function(err, instances) {
                                            if (err) {
                                                logger.error('Unable to fetch instance by org,provider', err);
                                                return;
                                            }
                                            tagsModel.getTagsByProviderId(provider._id, function(err, tagDetails) {
                                                if (err) {
                                                    logger.error("Unable to get tags", err);
                                                    return;
                                                }
                                                var projectTag = null;
                                                var environmentTag = null;
                                                // @TODO enum to be used to compare against project and env
                                                for (var z = 0; z < tagDetails.length; z++) {
                                                    if (('catalystEntityType' in tagDetails[z]) &&
                                                        tagDetails[z].catalystEntityType == 'project') {
                                                        projectTag = tagDetails[z];
                                                    } else if (('catalystEntityType' in tagDetails[z]) &&
                                                        tagDetails[z].catalystEntityType == 'environment') {
                                                        environmentTag = tagDetails[z];
                                                    }
                                                }

                                                var cryptoConfig = appConfig.cryptoSettings;
                                                var cryptography = new Cryptography(cryptoConfig.algorithm, cryptoConfig.password);

                                                var ec2Config;
                                                if (provider.isDefault) {
                                                    ec2Config = {
                                                        "isDefault": true
                                                    };
                                                } else {
                                                    var cryptoConfig = appConfig.cryptoSettings;
                                                    var cryptography = new Cryptography(cryptoConfig.algorithm,
                                                        cryptoConfig.password);

                                                    var decryptedAccessKey = cryptography.decryptText(provider.accessKey,
                                                        cryptoConfig.decryptionEncoding, cryptoConfig.encryptionEncoding);
                                                    var decryptedSecretKey = cryptography.decryptText(provider.secretKey,
                                                        cryptoConfig.decryptionEncoding, cryptoConfig.encryptionEncoding);

                                                    ec2Config = {
                                                        "access_key": decryptedAccessKey,
                                                        "secret_key": decryptedSecretKey
                                                    };
                                                }

                                                var regionCount = 0;
                                                var regions = appConfig.aws.regions;

                                                for (var k = 0; k < regions.length; k++) {
                                                    (function(region) {
                                                        ec2Config.region = region;
                                                        var ec2 = new EC2(ec2Config);
                                                        ec2.describeInstances(null, function(err, awsRes) {
                                                            regionCount++;
                                                            if (err) {
                                                                logger.error("Unable to fetch instances from aws", err);
                                                                return;
                                                            }
                                                            var reservations = awsRes.Reservations;
                                                            logger.debug('res==> ', reservations.length, ' region==> ', region);

                                                            for (var l = 0; l < reservations.length; l++) {

                                                                if (reservations[l].Instances && reservations[l].Instances.length) {
                                                                    //instances = reservations[k].Instances;
                                                                    var awsInstances = reservations[l].Instances;
                                                                    for (var m = 0; m < awsInstances.length; m++) {

                                                                        var found = false;
                                                                        var foundInUnManaged = false;
                                                                        var addedToUnmanaged = false;
                                                                        var foundInUnassigned = false;

                                                                        var tags = awsInstances[m].Tags;
                                                                        var tagInfo = {};
                                                                        for (var i = 0; i < tags.length; i++) {
                                                                            var jsonData = tags[i];
                                                                            tagInfo[jsonData.Key] = jsonData.Value;
                                                                        }

                                                                        var catalystProjectId = null;
                                                                        var catalystProjectName = null;
                                                                        var catalystEnvironmentId = null;
                                                                        var catalystEnvironmentName = null;

                                                                        if (projectTag && environmentTag && (awsInstances[m].State.Name !== 'terminated') && (projectTag.name in tagInfo) && (environmentTag.name in tagInfo)) {

                                                                            for (var y = 0; y < projectTag.catalystEntityMapping.length; y++) {
                                                                                if (projectTag.catalystEntityMapping[y].tagValue == tagInfo[projectTag.name]) {
                                                                                catalystProjectId = projectTag.catalystEntityMapping[y].catalystEntityId;
                                                                                catalystProjectName = projectTag.catalystEntityMapping[y].catalystEntityName;
                                                                                break;
                                                                                }
                                                                            }
                                                                            for (var y = 0; y < environmentTag.catalystEntityMapping.length; y++) {
                                                                                if (environmentTag.catalystEntityMapping[y].tagValue == tagInfo[environmentTag.name]) {
                                                                                catalystEnvironmentId = environmentTag.catalystEntityMapping[y].catalystEntityId;
                                                                                catalystEnvironmentName = environmentTag.catalystEntityMapping[y].catalystEntityName;
                                                                                break;
                                                                                }
                                                                            }

                                                                        }

                                                                        var assignmentFound = false;
                                                                        if (catalystProjectId && catalystEnvironmentId) {
                                                                            assignmentFound = true;
                                                                        }

                                                                        for (var n = 0; n < instances.length; n++) {
                                                                            if (instances[n].platformId === awsInstances[m].InstanceId) {
                                                                                instances[n].instanceState = awsInstances[m].State.Name;

                                                                                if (instances[n].instanceState === 'terminated') {
                                                                                removeTerminateInstance(instances[n]._id, instances[n].instanceState, 'managed');
                                                                                } else {
                                                                                if (instances[n].instanceState === 'running') {
                                                                                instances[n].instanceIP = awsInstances[m].PublicIpAddress || awsInstances[m].PrivateIpAddress;
                                                                                }

                                                                                if (assignmentFound) {
                                                                                instances[n].environmentName = catalystEnvironmentName;
                                                                                }

                                                                                instances[n].orgName = org.orgname;
                                                                                instances[n].tags = tagInfo;
                                                                                instances[n].save();
                                                                                found = true;

                                                                                //sending socket event
                                                                                socketCloudFormationAutoScate.to(instances[n].orgId + ':' + instances[n].bgId + ':' + instances[n].projectId + ':' + instances[n].envId).emit('instanceStateChanged', instances[n]);

                                                                                instances.splice(n, 1);
                                                                                break;
                                                                                }
                                                                            } else if (instances[n].instanceState === 'terminated') {
                                                                                removeTerminateInstance(instances[n]._id, 'managed');
                                                                            }
                                                                        }

                                                                        if (!found) {
                                                                            for (var n = 0; n < unManagedInstances.length; n++) {
                                                                                if ((unManagedInstances[n].platformId === awsInstances[m].InstanceId) && !assignmentFound) {
                                                                                unManagedInstances[n].remove();
                                                                                } else if (unManagedInstances[n].platformId === awsInstances[m].InstanceId) {
                                                                                unManagedInstances[n].state = awsInstances[m].State.Name;
                                                                                if (unManagedInstances[n].state === 'terminated') {
                                                                                removeTerminateInstance(unManagedInstances[n]._id, unManagedInstances[n].state, 'assigned');
                                                                                } else {
                                                                                if (unManagedInstances[n].state === 'running') {
                                                                                unManagedInstances[n].ip = awsInstances[m].PublicIpAddress || awsInstances[m].PrivateIpAddress;
                                                                                }
                                                                                unManagedInstances[n].projectId = catalystProjectId;
                                                                                unManagedInstances[n].projectName = catalystProjectName;
                                                                                unManagedInstances[n].environmentId = catalystEnvironmentId;
                                                                                unManagedInstances[n].environmentName = catalystEnvironmentName;

                                                                                unManagedInstances[n].tags = tagInfo;
                                                                                unManagedInstances[n].save();
                                                                                }

                                                                                foundInUnManaged = true;
                                                                                unManagedInstances.splice(n, 1);
                                                                                break;
                                                                                } else if (unManagedInstances[n].state === 'terminated') {
                                                                                removeTerminateInstance(unManagedInstances[n]._id, 'assigned');
                                                                                }
                                                                            }
                                                                        }

                                                                        if (!found && !foundInUnManaged) { //making entry in unmanaged database
                                                                            var os = 'linux';

                                                                            if (awsInstances[m].State.Name !== 'terminated' && assignmentFound) {

                                                                                if (awsInstances[m].Platform && awsInstances[m].Platform === 'windows') {
                                                                                os = 'windows';
                                                                                }

                                                                                unManagedInstancesDao.createNew({
                                                                                orgId: org.rowid,
                                                                                orgName: org.orgname,
                                                                                providerId: provider._id,
                                                                                projectId: catalystProjectId,
                                                                                projectName: catalystProjectName,
                                                                                environmentId: catalystEnvironmentId,
                                                                                environmentName: catalystEnvironmentName,
                                                                                providerType: 'aws',
                                                                                providerData: {
                                                                                region: region
                                                                                },
                                                                                platformId: awsInstances[m].InstanceId,
                                                                                ip: awsInstances[m].PublicIpAddress || awsInstances[m].PrivateIpAddress,
                                                                                os: os,
                                                                                state: awsInstances[m].State.Name,
                                                                                tags: tagInfo
                                                                                });

                                                                                addedToUnmanaged = true;
                                                                            }

                                                                        }

                                                                        if (!found && !foundInUnManaged && !addedToUnmanaged) {
                                                                            for (var n = 0; n < unassignedInstances.length; n++) {
                                                                                if (unassignedInstances[n].platformId === awsInstances[m].InstanceId) {
                                                                                unassignedInstances[n].state = awsInstances[m].State.Name;
                                                                                if (unassignedInstances[n].state === 'terminated') {
                                                                                unassignedInstances[n].remove();
                                                                                } else {
                                                                                if (unassignedInstances[n].state === 'running') {
                                                                                unassignedInstances[n].instanceIP = awsInstances[m].PublicIpAddress || awsInstances[m].PrivateIpAddress;
                                                                                }

                                                                                if (projectTag && (projectTag.name in tagInfo))
                                                                                unassignedInstances[n].projectTag = tagInfo[projectTag.name];

                                                                                if (environmentTag && (environmentTag.name in tagInfo))
                                                                                unassignedInstances[n].environmentTag = tagInfo[environmentTag.name];

                                                                                unassignedInstances[n].tags = tagInfo;
                                                                                unassignedInstances[n].save();
                                                                                }

                                                                                foundInUnassigned = true;
                                                                                unassignedInstances.splice(n, 1);
                                                                                break;
                                                                                }
                                                                            }

                                                                        } else if (addedToUnmanaged) {
                                                                            unassignedInstancesModel.deleteByPlatformAndProviderId(provider._id,
                                                                                awsInstances[m].InstanceId);
                                                                        }

                                                                        if (!found && !foundInUnManaged && !addedToUnmanaged && !foundInUnassigned) {
                                                                            var os = 'linux';
                                                                            if (awsInstances[m].Platform && awsInstances[m].Platform === 'windows') {
                                                                                os = 'windows';
                                                                            }

                                                                            var newUnassignedInstance = {
                                                                                orgId: org.rowid,
                                                                                providerId: provider._id,
                                                                                providerType: 'aws',
                                                                                providerData: {
                                                                                region: region
                                                                                },
                                                                                platformId: awsInstances[m].InstanceId,
                                                                                ip: awsInstances[m].PublicIpAddress || awsInstances[m].PrivateIpAddress,
                                                                                os: os,
                                                                                state: awsInstances[m].State.Name,
                                                                                tags: tagInfo
                                                                            };

                                                                            if (projectTag && (projectTag.name in tagInfo))
                                                                                newUnassignedInstance.projectTag = tagInfo[projectTag.name];

                                                                            if (environmentTag && (environmentTag.name in tagInfo))
                                                                                newUnassignedInstance.environmentTag = tagInfo[environmentTag.name];

                                                                            saveAndUpdateInstance(newUnassignedInstance);
                                                                        }
                                                                    }
                                                                }
                                                            }

                                                            if (regionCount === regions.length) {
                                                                fetchComplete();
                                                            }

                                                        });
                                                    })(regions[k].region);
                                                }

                                                function fetchComplete() {
                                                    for (var p = 0; p < instances.length; p++) {
                                                        instances[p].instanceState = "terminated";
                                                        socketCloudFormationAutoScate.to(instances[p].orgId + ':' + instances[p].bgId + ':' + instances[p].projectId + ':' + instances[p].envId).emit('instanceStateChanged', instances[p]);
                                                        instances[p].save();
                                                    }
                                                    for (var r = 0; r < unManagedInstances.length; r++) {
                                                        unManagedInstances[r].remove();
                                                    }
                                                }
                                            });

                                        });
                                    });
                                });
                        })(providers[j]);
                    }
                });
            })(orgs[i])
        }
    });
}

function removeTerminateInstance(instanceId, key) {
    if (key === 'managed') {
        instancesDao.removeTerminatedInstanceById(instanceId, function(err, data) {
            if (err) {
                logger.error(err);
                return;
            } else {
                instanceLogModel.removeByInstanceId(instanceId, function(err, removed) {
                    if (err) {
                        logger.error("Failed to remove instance Log: ", err);
                    }
                });
                return;
            }
        });
    } else if (key === 'assigned') {
        unManagedInstancesDao.removeInstanceById(instanceId, function(err, data) {
            if (err) {
                logger.error(err);
                return;
            } else {
                instanceLogModel.removeByInstanceId(instanceId, function(err, removed) {
                    if (err) {
                        logger.error("Failed to remove instance Log: ", err);
                    }
                });
                return;
            }

        });
    }
};

function saveAndUpdateInstance(instance) {
    unassignedInstancesModel.getByProviderIdAndPlatformId(instance.providerId, instance.platformId, function(err, data) {
        if (err) {
            logger.error(" Instance fetching Failed >> ", err);
            return;
        } else if (data === null) {
            unassignedInstancesModel.createNew(instance, function(err, instancedata) {
                if (err) {
                    logger.error(" Instance creation Failed >> ", err);
                    return;
                } else {
                    return;
                }
            });
        } else {
            unassignedInstancesModel.updateInstanceStatus(instance, function(err, updateInstanceData) {
                if (err) {
                    logger.error(" Instance update Failed >> ", err);
                    return;
                } else {
                    return;
                }
            });
        }
    });
}
<commit_msg> Removing instance logs for terminated managed and assigned instances<commit_after>var logger = require('_pr/logger')(module);
var CatalystCronJob = require('_pr/cronjobs/CatalystCronJob');
var AWSProvider = require('_pr/model/classes/masters/cloudprovider/awsCloudProvider.js');
var MasterUtils = require('_pr/lib/utils/masterUtil.js');
var appConfig = require('_pr/config');
var Cryptography = require('_pr/lib/utils/cryptography');
var EC2 = require('_pr/lib/ec2.js');
var instancesDao = require('_pr/model/classes/instance/instance');
var unManagedInstancesDao = require('_pr/model/unmanaged-instance');
var unassignedInstancesModel = require('_pr/model/unassigned-instances');
var async = require('async');
var tagsModel = require('_pr/model/tags');
var instanceLogModel = require('_pr/model/log-trail/instanceLog.js');
var instanceService = require('_pr/services/instanceService');
var socketIo = require('_pr/socket.io').getInstance();
var socketCloudFormationAutoScate = socketIo.of('/cloudFormationAutoScaleGroup');

socketCloudFormationAutoScate.on('connection', function(socket) {
    socket.on('joinCFRoom', function(data) {
        logger.debug('room joined', data);
        socket.join(data.orgId + ':' + data.bgId + ':' + data.projId + ':' + data.envId);
    });

});

var AWSProviderSync = Object.create(CatalystCronJob);
AWSProviderSync.execute = sync;

module.exports = AWSProviderSync;

// @TODO To be refactored (High Priority)
function sync() {
    var orgs = MasterUtils.getAllActiveOrg(function(err, orgs) {
        if (err) {
            logger.error('Unable to fetch orgs ==>', err);
            return;
        }
        if (!(orgs && orgs.length)) {
            logger.warn('No org found');
            return;
        }
        for (var i = 0; i < orgs.length; i++) {
            (function(org) {
                AWSProvider.getAWSProvidersByOrgId(org._id, function(err, providers) {
                    if (err) {
                        logger.error("Unable to get aws providers :", err);
                        return;
                    }
                    for (var j = 0; j < providers.length; j++) {
                        (function(provider) {
                            unassignedInstancesModel.getUnAssignedInstancesByProviderId(provider._id,
                                function(err, unassignedInstances) {
                                    if (err) {
                                        logger.error('Unable to fetch unassigned Instances by provider', err);
                                        return;
                                    }
                                    unManagedInstancesDao.getByOrgProviderId({
                                        orgId: org.rowid,
                                        providerId: provider._id,
                                        isDeleted: false
                                    }, function(err, unManagedInstances) {
                                        if (err) {
                                            logger.error('Unable to fetch Unmanaged Instances by org,provider', err);
                                            return;
                                        }
                                        instancesDao.getByOrgProviderId({
                                            orgId: org.rowid,
                                            providerId: provider._id,
                                            isDeleted: false
                                        }, function(err, instances) {
                                            if (err) {
                                                logger.error('Unable to fetch instance by org,provider', err);
                                                return;
                                            }
                                            tagsModel.getTagsByProviderId(provider._id, function(err, tagDetails) {
                                                if (err) {
                                                    logger.error("Unable to get tags", err);
                                                    return;
                                                }
                                                var projectTag = null;
                                                var environmentTag = null;
                                                // @TODO enum to be used to compare against project and env
                                                for (var z = 0; z < tagDetails.length; z++) {
                                                    if (('catalystEntityType' in tagDetails[z]) &&
                                                        tagDetails[z].catalystEntityType == 'project') {
                                                        projectTag = tagDetails[z];
                                                    } else if (('catalystEntityType' in tagDetails[z]) &&
                                                        tagDetails[z].catalystEntityType == 'environment') {
                                                        environmentTag = tagDetails[z];
                                                    }
                                                }

                                                var cryptoConfig = appConfig.cryptoSettings;
                                                var cryptography = new Cryptography(cryptoConfig.algorithm, cryptoConfig.password);

                                                var ec2Config;
                                                if (provider.isDefault) {
                                                    ec2Config = {
                                                        "isDefault": true
                                                    };
                                                } else {
                                                    var cryptoConfig = appConfig.cryptoSettings;
                                                    var cryptography = new Cryptography(cryptoConfig.algorithm,
                                                        cryptoConfig.password);

                                                    var decryptedAccessKey = cryptography.decryptText(provider.accessKey,
                                                        cryptoConfig.decryptionEncoding, cryptoConfig.encryptionEncoding);
                                                    var decryptedSecretKey = cryptography.decryptText(provider.secretKey,
                                                        cryptoConfig.decryptionEncoding, cryptoConfig.encryptionEncoding);

                                                    ec2Config = {
                                                        "access_key": decryptedAccessKey,
                                                        "secret_key": decryptedSecretKey
                                                    };
                                                }

                                                var regionCount = 0;
                                                var regions = appConfig.aws.regions;

                                                for (var k = 0; k < regions.length; k++) {
                                                    (function(region) {
                                                        ec2Config.region = region;
                                                        var ec2 = new EC2(ec2Config);
                                                        ec2.describeInstances(null, function(err, awsRes) {
                                                            regionCount++;
                                                            if (err) {
                                                                logger.error("Unable to fetch instances from aws", err);
                                                                return;
                                                            }
                                                            var reservations = awsRes.Reservations;
                                                            logger.debug('res==> ', reservations.length, ' region==> ', region);

                                                            for (var l = 0; l < reservations.length; l++) {

                                                                if (reservations[l].Instances && reservations[l].Instances.length) {
                                                                    //instances = reservations[k].Instances;
                                                                    var awsInstances = reservations[l].Instances;
                                                                    for (var m = 0; m < awsInstances.length; m++) {

                                                                        var found = false;
                                                                        var foundInUnManaged = false;
                                                                        var addedToUnmanaged = false;
                                                                        var foundInUnassigned = false;

                                                                        var tags = awsInstances[m].Tags;
                                                                        var tagInfo = {};
                                                                        for (var i = 0; i < tags.length; i++) {
                                                                            var jsonData = tags[i];
                                                                            tagInfo[jsonData.Key] = jsonData.Value;
                                                                        }

                                                                        var catalystProjectId = null;
                                                                        var catalystProjectName = null;
                                                                        var catalystEnvironmentId = null;
                                                                        var catalystEnvironmentName = null;

                                                                        if (projectTag && environmentTag && (awsInstances[m].State.Name !== 'terminated') && (projectTag.name in tagInfo) && (environmentTag.name in tagInfo)) {

                                                                            for (var y = 0; y < projectTag.catalystEntityMapping.length; y++) {
                                                                                if (projectTag.catalystEntityMapping[y].tagValue == tagInfo[projectTag.name]) {
                                                                                catalystProjectId = projectTag.catalystEntityMapping[y].catalystEntityId;
                                                                                catalystProjectName = projectTag.catalystEntityMapping[y].catalystEntityName;
                                                                                break;
                                                                                }
                                                                            }
                                                                            for (var y = 0; y < environmentTag.catalystEntityMapping.length; y++) {
                                                                                if (environmentTag.catalystEntityMapping[y].tagValue == tagInfo[environmentTag.name]) {
                                                                                catalystEnvironmentId = environmentTag.catalystEntityMapping[y].catalystEntityId;
                                                                                catalystEnvironmentName = environmentTag.catalystEntityMapping[y].catalystEntityName;
                                                                                break;
                                                                                }
                                                                            }

                                                                        }

                                                                        var assignmentFound = false;
                                                                        if (catalystProjectId && catalystEnvironmentId) {
                                                                            assignmentFound = true;
                                                                        }

                                                                        for (var n = 0; n < instances.length; n++) {
                                                                            if (instances[n].platformId === awsInstances[m].InstanceId) {
                                                                                instances[n].instanceState = awsInstances[m].State.Name;

                                                                                if (instances[n].instanceState === 'terminated') {
                                                                                removeTerminateInstance(instances[n]._id, instances[n].instanceState, 'managed');
                                                                                } else {
                                                                                if (instances[n].instanceState === 'running') {
                                                                                instances[n].instanceIP = awsInstances[m].PublicIpAddress || awsInstances[m].PrivateIpAddress;
                                                                                }

                                                                                if (assignmentFound) {
                                                                                instances[n].environmentName = catalystEnvironmentName;
                                                                                }

                                                                                instances[n].orgName = org.orgname;
                                                                                instances[n].tags = tagInfo;
                                                                                instances[n].save();
                                                                                found = true;

                                                                                //sending socket event
                                                                                socketCloudFormationAutoScate.to(instances[n].orgId + ':' + instances[n].bgId + ':' + instances[n].projectId + ':' + instances[n].envId).emit('instanceStateChanged', instances[n]);

                                                                                instances.splice(n, 1);
                                                                                break;
                                                                                }
                                                                            } else if (instances[n].instanceState === 'terminated') {
                                                                                removeTerminateInstance(instances[n]._id, 'managed');
                                                                            }
                                                                        }

                                                                        if (!found) {
                                                                            for (var n = 0; n < unManagedInstances.length; n++) {
                                                                                if ((unManagedInstances[n].platformId === awsInstances[m].InstanceId) && !assignmentFound) {
                                                                                unManagedInstances[n].remove();
                                                                                } else if (unManagedInstances[n].platformId === awsInstances[m].InstanceId) {
                                                                                unManagedInstances[n].state = awsInstances[m].State.Name;
                                                                                if (unManagedInstances[n].state === 'terminated') {
                                                                                removeTerminateInstance(unManagedInstances[n]._id, unManagedInstances[n].state, 'assigned');
                                                                                } else {
                                                                                if (unManagedInstances[n].state === 'running') {
                                                                                unManagedInstances[n].ip = awsInstances[m].PublicIpAddress || awsInstances[m].PrivateIpAddress;
                                                                                }
                                                                                unManagedInstances[n].projectId = catalystProjectId;
                                                                                unManagedInstances[n].projectName = catalystProjectName;
                                                                                unManagedInstances[n].environmentId = catalystEnvironmentId;
                                                                                unManagedInstances[n].environmentName = catalystEnvironmentName;

                                                                                unManagedInstances[n].tags = tagInfo;
                                                                                unManagedInstances[n].save();
                                                                                }

                                                                                foundInUnManaged = true;
                                                                                unManagedInstances.splice(n, 1);
                                                                                break;
                                                                                } else if (unManagedInstances[n].state === 'terminated') {
                                                                                removeTerminateInstance(unManagedInstances[n]._id, 'assigned');
                                                                                }
                                                                            }
                                                                        }

                                                                        if (!found && !foundInUnManaged) { //making entry in unmanaged database
                                                                            var os = 'linux';

                                                                            if (awsInstances[m].State.Name !== 'terminated' && assignmentFound) {

                                                                                if (awsInstances[m].Platform && awsInstances[m].Platform === 'windows') {
                                                                                os = 'windows';
                                                                                }

                                                                                unManagedInstancesDao.createNew({
                                                                                orgId: org.rowid,
                                                                                orgName: org.orgname,
                                                                                providerId: provider._id,
                                                                                projectId: catalystProjectId,
                                                                                projectName: catalystProjectName,
                                                                                environmentId: catalystEnvironmentId,
                                                                                environmentName: catalystEnvironmentName,
                                                                                providerType: 'aws',
                                                                                providerData: {
                                                                                region: region
                                                                                },
                                                                                platformId: awsInstances[m].InstanceId,
                                                                                ip: awsInstances[m].PublicIpAddress || awsInstances[m].PrivateIpAddress,
                                                                                os: os,
                                                                                state: awsInstances[m].State.Name,
                                                                                tags: tagInfo
                                                                                });

                                                                                addedToUnmanaged = true;
                                                                            }

                                                                        }

                                                                        if (!found && !foundInUnManaged && !addedToUnmanaged) {
                                                                            for (var n = 0; n < unassignedInstances.length; n++) {
                                                                                if (unassignedInstances[n].platformId === awsInstances[m].InstanceId) {
                                                                                unassignedInstances[n].state = awsInstances[m].State.Name;
                                                                                if (unassignedInstances[n].state === 'terminated') {
                                                                                unassignedInstances[n].remove();
                                                                                } else {
                                                                                if (unassignedInstances[n].state === 'running') {
                                                                                unassignedInstances[n].instanceIP = awsInstances[m].PublicIpAddress || awsInstances[m].PrivateIpAddress;
                                                                                }

                                                                                if (projectTag && (projectTag.name in tagInfo))
                                                                                unassignedInstances[n].projectTag = tagInfo[projectTag.name];

                                                                                if (environmentTag && (environmentTag.name in tagInfo))
                                                                                unassignedInstances[n].environmentTag = tagInfo[environmentTag.name];

                                                                                unassignedInstances[n].tags = tagInfo;
                                                                                unassignedInstances[n].save();
                                                                                }

                                                                                foundInUnassigned = true;
                                                                                unassignedInstances.splice(n, 1);
                                                                                break;
                                                                                }
                                                                            }

                                                                        } else if (addedToUnmanaged) {
                                                                            unassignedInstancesModel.deleteByPlatformAndProviderId(provider._id,
                                                                                awsInstances[m].InstanceId);
                                                                        }

                                                                        if (!found && !foundInUnManaged && !addedToUnmanaged && !foundInUnassigned) {
                                                                            var os = 'linux';
                                                                            if (awsInstances[m].Platform && awsInstances[m].Platform === 'windows') {
                                                                                os = 'windows';
                                                                            }

                                                                            var newUnassignedInstance = {
                                                                                orgId: org.rowid,
                                                                                providerId: provider._id,
                                                                                providerType: 'aws',
                                                                                providerData: {
                                                                                region: region
                                                                                },
                                                                                platformId: awsInstances[m].InstanceId,
                                                                                ip: awsInstances[m].PublicIpAddress || awsInstances[m].PrivateIpAddress,
                                                                                os: os,
                                                                                state: awsInstances[m].State.Name,
                                                                                tags: tagInfo
                                                                            };

                                                                            if (projectTag && (projectTag.name in tagInfo))
                                                                                newUnassignedInstance.projectTag = tagInfo[projectTag.name];

                                                                            if (environmentTag && (environmentTag.name in tagInfo))
                                                                                newUnassignedInstance.environmentTag = tagInfo[environmentTag.name];

                                                                            saveAndUpdateInstance(newUnassignedInstance);
                                                                        }
                                                                    }
                                                                }
                                                            }

                                                            if (regionCount === regions.length) {
                                                                fetchComplete();
                                                            }

                                                        });
                                                    })(regions[k].region);
                                                }

                                                function fetchComplete() {
                                                    for (var p = 0; p < instances.length; p++) {
                                                        instances[p].instanceState = "terminated";
                                                        socketCloudFormationAutoScate.to(instances[p].orgId + ':' + instances[p].bgId + ':' + instances[p].projectId + ':' + instances[p].envId).emit('instanceStateChanged', instances[p]);
                                                        instances[p].save();
                                                    }
                                                    for (var r = 0; r < unManagedInstances.length; r++) {
                                                        unManagedInstances[r].remove();
                                                    }
                                                }
                                            });

                                        });
                                    });
                                });
                        })(providers[j]);
                    }
                });
            })(orgs[i])
        }
    });
}

function removeTerminateInstance(instanceId, key) {
    if (key === 'managed') {
        instanceLogModel.removeByInstanceId(instanceId, function(err, removed) {
            if (err) {
                logger.error("Failed to remove instance Log: ", err);
            }
        });
        instancesDao.removeTerminatedInstanceById(instanceId, function(err, data) {
            if (err) {
                logger.error(err);
                return;
            }
        });
    } else if (key === 'assigned') {
        instanceLogModel.removeByInstanceId(instanceId, function(err, removed) {
            if (err) {
                logger.error("Failed to remove instance Log: ", err);
            }
        });
        unManagedInstancesDao.removeInstanceById(instanceId, function(err, data) {
            if (err) {
                logger.error(err);
                return;
            }

        });
    }
};

function saveAndUpdateInstance(instance) {
    unassignedInstancesModel.getByProviderIdAndPlatformId(instance.providerId, instance.platformId, function(err, data) {
        if (err) {
            logger.error(" Instance fetching Failed >> ", err);
            return;
        } else if (data === null) {
            unassignedInstancesModel.createNew(instance, function(err, instancedata) {
                if (err) {
                    logger.error(" Instance creation Failed >> ", err);
                    return;
                } else {
                    return;
                }
            });
        } else {
            unassignedInstancesModel.updateInstanceStatus(instance, function(err, updateInstanceData) {
                if (err) {
                    logger.error(" Instance update Failed >> ", err);
                    return;
                } else {
                    return;
                }
            });
        }
    });
}
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2014 Adobe Systems Incorporated. All rights reserved.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 *
 */

define(function (require, exports) {
    "use strict";

    var Promise = require("bluebird"),
        adapterPS = require("adapter/ps"),
        global = require("./global");

    /**
     * Logs an event entry in Headlights for Photoshop
     * Will not log anything in debug builds
     *
     * NOTE: This is an Adobe-private API that must not be used by third-party
     * developers!
     *
     * @private
     * @param {string} category
     * @param {string} subcategory
     * @param {string} event
     *
     * @return {Promise}
     */
    var logEvent = function (category, subcategory, event) {
        if (global.debug) {
            return Promise.resolve();
        } else {
            return adapterPS.logHeadlightsEvent(category, subcategory, event);
        }
    };

    exports.logEvent = logEvent;
});
<commit_msg>converts "event" to string in headlights<commit_after>/*
 * Copyright (c) 2014 Adobe Systems Incorporated. All rights reserved.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 *
 */

define(function (require, exports) {
    "use strict";

    var Promise = require("bluebird"),
        adapterPS = require("adapter/ps"),
        global = require("./global");

    /**
     * Logs an event entry in Headlights for Photoshop
     * Will not log anything in debug builds
     *
     * NOTE: This is an Adobe-private API that must not be used by third-party
     * developers!
     *
     * @private
     * @param {string} category
     * @param {string} subcategory
     * @param {string} event
     *
     * @return {Promise}
     */
    var logEvent = function (category, subcategory, event) {
        if (global.debug) {
            return Promise.resolve();
        } else {
            return adapterPS.logHeadlightsEvent(category, subcategory, String(event));
        }
    };

    exports.logEvent = logEvent;
});
<|endoftext|>


<commit_before>// Returns fragment that emits direct data for specified object
// Optional filtering of some records is possible via `options.filter`

'use strict';

var ensureCallable = require('es5-ext/object/valid-callable')
  , ensureString   = require('es5-ext/object/validate-stringifiable-value')
  , escape         = require('es5-ext/reg-exp/escape')
  , memoize        = require('memoizee')
  , Fragment       = require('data-fragment')

  , driver = require('mano').dbDriver;

var getKeyPathFilter = function (keyPath) {
	var matches = RegExp.prototype.test.bind(new RegExp('^[a-z0-9][a-z0-9A-Z]*/' +
		escape(keyPath) + '(?:/.+|$)'));
	return function (data) { return matches(data.id); };
};

module.exports = memoize(function (storageName) {
	var storage = driver.getStorage(ensureString(storageName));
	return memoize(function (ownerId/*, options*/) {
		var fragment, options = Object(arguments[1]), filter, index, customFilter, keyPathFilter;

		ownerId = ensureString(ownerId);
		if (options.filter != null) customFilter = ensureCallable(options.filter);
		index = ownerId.indexOf('/');
		if (index !== -1) {
			keyPathFilter = getKeyPathFilter(ownerId.slice(index + 1));
			ownerId = ownerId.slice(0, index);
		}
		if (keyPathFilter) {
			if (customFilter) {
				filter = function (data) { return keyPathFilter(data) && customFilter(data); };
			} else {
				filter = keyPathFilter;
			}
		} else if (customFilter) {
			filter = customFilter;
		}
		fragment = new Fragment();
		fragment.promise = storage.getObject(ownerId)(function (data) {
			data.forEach(function (data) {
				if (!filter || filter(data)) fragment.update(data.id, data.data);
			});
		});
		storage.on('owner:' + ownerId, function (event) {
			if (event.type !== 'direct') return;
			if (!filter || filter(event)) fragment.update(event.id, event.data);
		});
		return fragment;
	}, { primitive: true });
}, { primitive: true });
<commit_msg>Support any storage resolution<commit_after>// Returns fragment that emits direct data for specified object
// Optional filtering of some records is possible via `options.filter`

'use strict';

var ensureCallable = require('es5-ext/object/valid-callable')
  , ensureString   = require('es5-ext/object/validate-stringifiable-value')
  , escape         = require('es5-ext/reg-exp/escape')
  , memoize        = require('memoizee')
  , Fragment       = require('data-fragment')
  , anyIdToStorage = require('../utils/any-id-to-storage')

  , driver = require('mano').dbDriver;

var getKeyPathFilter = function (keyPath) {
	var matches = RegExp.prototype.test.bind(new RegExp('^[a-z0-9][a-z0-9A-Z]*/' +
		escape(keyPath) + '(?:/.+|$)'));
	return function (data) { return matches(data.id); };
};

module.exports = memoize(function (storageName) {
	var storage;
	if (storageName != null) storage = driver.getStorage(storageName);
	return memoize(function (ownerId/*, options*/) {
		var fragment, options = Object(arguments[1]), filter, index, customFilter, keyPathFilter
		  , promise, setupListener;

		ownerId = ensureString(ownerId);
		if (options.filter != null) customFilter = ensureCallable(options.filter);
		index = ownerId.indexOf('/');
		if (index !== -1) {
			keyPathFilter = getKeyPathFilter(ownerId.slice(index + 1));
			ownerId = ownerId.slice(0, index);
		}
		if (keyPathFilter) {
			if (customFilter) {
				filter = function (data) { return keyPathFilter(data) && customFilter(data); };
			} else {
				filter = keyPathFilter;
			}
		} else if (customFilter) {
			filter = customFilter;
		}
		fragment = new Fragment();
		setupListener = function (storage) {
			storage.on('owner:' + ownerId, function (event) {
				if (event.type !== 'direct') return;
				if (!filter || filter(event)) fragment.update(event.id, event.data);
			});
		};
		if (storage) {
			promise = storage.getObject(ownerId);
			setupListener(storage);
		} else {
			promise = anyIdToStorage(ownerId)(function (storage) {
				setupListener(storage);
				return storage.getObject(ownerId);
			});
		}
		fragment.promise = promise(function (data) {
			data.forEach(function (data) {
				if (!filter || filter(data)) fragment.update(data.id, data.data);
			});
		});
		return fragment;
	}, { primitive: true });
}, { primitive: true, resolvers: [function (storageName) {
	if (storageName == null) return '';
	return ensureString(storageName);
}] });
<|endoftext|>


<commit_before>/* *** Code Inconsistent with Rappid Distribution ***
 * J.Fear - Aug. 2015
 * The following functions differs from the Rappid release. These functions did not exist in the Rappid Library.
 * 		joint.shapes.basic.Intention: Is the superclass for all added nodes (goals, subgoals, tasks, resources).
 * 		joint.shapes.basic.Goal: Goal node.
 * 		joint.shapes.basic.Task: Task node.
 * 		joint.shapes.basic.Softgoal: Softgoal node.
 * 		joint.shapes.basic.Resource: Resource node.
 * 		joint.dia.Actorlink: Link between actors.
 * 		joint.shapes.basic.Actor: Actor node.
 *
 */

joint.dia.BloomingGraph = joint.dia.Graph.extend({
    defaults: joint.util.deepSupplement({
        type: 'goalmodel.Graph',
        maxAbsTime: 100,
        absTimePtsArr: [],
        // TODO: Name with correct type of constraints
        constraints: new ConstraintCollection([]),
    }, joint.dia.Graph.prototype.defaults),

    /**
     * @returns Array of all IntentionBBMs in the graph
     */
    getIntentions: function () {
        return this.getElements().filter(element => element instanceof joint.shapes.basic.Intention)
            .map(intentionCell => intentionCell.get('intention'));
    },

    /**
     * Returns the cell associated with the id parameter
     * There should be a 1 to 1 mapping of ids to cells
     *
     * @param {String} id
     * @returns Cell
     */
    getCellById: function (id) {
        var cell = this.getCells().filter(cell => cell.get('id') == id);
        if (cell.length == 1) {
            return cell[0]
        }
        return null;
    },

})

joint.shapes.basic.Intention = joint.shapes.basic.Generic.extend({
    // Changed satvalue to text
    markup: '<g class="rotatable"><g class="scalable"><rect class="outer"/></g><text class="satvalue"/><text class="funcvalue"/><text class="name"/></g>',
    defaults: joint.util.deepSupplement({
        type: "basic.Intention",
        size: {
            width: 100,
            height: 60
        },
        attrs: {
            ".outer": {
                width: 100,
                height: 60
            },
            // Navie: Changed the initial value of satvalue
            ".satvalue": {
                'stroke': '#000000',
                'stroke-width': 0.5,
                'font-size': 12,
                'text-anchor': 'middle',
                'value': 'none'
            },
            ".funcvalue": {
                'text': "",
                'ref-y': '0.75',
                'ref-x': '0.08',
                'fill': 'black',
                'font-size': 16
            },
            ".name": {
                'fill': 'black',
                'ref-y': '0.5',
                'ref-x': '0.5',
                'font-size': 10,
                'x-alignment': 'middle',
                'y-alignment': 'middle'
            },
        },
        intention: null,
    }, joint.dia.Element.prototype.defaults)
});

joint.shapes.basic.Goal = joint.shapes.basic.Intention.extend({
    defaults: joint.util.deepSupplement({
        type: "basic.Goal",
        attrs: {
            ".outer": {
                rx: 20,
                ry: 20,
                stroke: 'black',
                fill: '#FFCC66',
            },
            ".satvalue": {
                'ref-x': '0.75',
                'ref-y': '0.75'
            },
            ".name": {
                'text': 'Goal',
            }
        }
    }, joint.shapes.basic.Intention.prototype.defaults),
    changeToOriginalColour: function () {
        this.attr({ '.outer': { 'fill': '#FFCC66' } });
    }
});

joint.shapes.basic.Task = joint.shapes.basic.Intention.extend({
    markup: '<g class="rotatable"><g class="scalable"><path class="outer"/></g><text class="satvalue"/><text class="funcvalue"/><text class="name"/></g>',
    defaults: joint.util.deepSupplement({
        type: "basic.Task",
        attrs: {
            ".outer": {

                refD: 'M 0 30 L 20 0 L 80 0 L 100 30 L 80 60 L 20 60 z',
                fill: '#92E3B1',
                stroke: 'black',
                'stroke-width': 1
            },
            ".satvalue": {
                'ref-y': '0.75',
                'ref-x': '0.8',
            },
            ".funcvalue": {
                'ref-y': '0.75',
                'ref-x': '0.2',
            },
            ".name": {
                'text': 'Task',
            }
        }
    }, joint.shapes.basic.Intention.prototype.defaults),
    changeToOriginalColour: function () {
        this.attr({ '.outer': { 'fill': '#92E3B1' } });
    }
});

joint.shapes.basic.Softgoal = joint.shapes.basic.Intention.extend({
    markup: '<g class="rotatable"><g class="scalable"><path class="outer"/></g><text class="satvalue"/><text class="funcvalue"/><text class="name"/></g>',
    defaults: joint.util.deepSupplement({
        type: "basic.Softgoal",
        attrs: {
            ".outer": {
                refD: 'M 0 30 Q 5 0 45 15 Q 55 18 65 15 Q 95 5 100 25 L 100 40 Q 100 60 80 60 L 75, 60 Q 66 59 55 56 Q 45 52 35 56 Q 25 57 15 58 L 10 58 Q 0 53 0 35 z',
                stroke: 'black',
                fill: '#FF984F',
            },
            ".satvalue": {
                'ref-y': '0.75',
                'ref-x': '0.76'
            },
            ".funcvalue": {
                'ref-y': '0.75',
                'ref-x': '0.2',
            },
            ".name": {
                'text': 'Soft Goal',
            }
        }
    }, joint.shapes.basic.Intention.prototype.defaults),
    changeToOriginalColour: function () {
        this.attr({ '.outer': { 'fill': '#FF984F' } });
    }
});

joint.shapes.basic.Resource = joint.shapes.basic.Intention.extend({
    defaults: joint.util.deepSupplement({
        type: "basic.Resource",
        attrs: {
            ".outer": {
                stroke: 'black',
                fill: '#92C2FE',
            },
            ".satvalue": {
                transform: "translate(80, 45)",
            },
            ".name": {
                'text': 'Resource',
            }
        }
    }, joint.shapes.basic.Intention.prototype.defaults),
    changeToOriginalColour: function () {
        this.attr({ '.outer': { 'fill': '#92C2FE' } });
    }
});

joint.shapes.basic.CellLink = joint.dia.Link.extend({
    // In initialize, everytime the target is changed, the code updates it
    initialize: function () {
        this.on('change:target', this.updateLinkPointers, this);
        this.on('change:source', this.updateLinkPointers, this);
    },
    defaults: joint.util.deepSupplement({
        type: 'basic.CellLink',
        link: null,
    }),

    /**
     * This function checks the updated target/source to determine if the link is still valid
     * And updates the CellLink type and LinkBBM linkType accordingly
     */
    updateLinkPointers: function () {
        var target = this.getTargetElement();
        var source = this.getSourceElement();
        if ((target !== null && source !== null)) {
            if (((source.get('type') === 'basic.Actor') && (target.get('type') !== 'basic.Actor')) || ((source.get('type') !== 'basic.Actor') && (target.get('type') === 'basic.Actor'))) {
                this.get('link').set('displayType', 'error');
                this.label(0, { position: 0.5, attrs: { text: { text: 'error' } } });
            } else if (source.get('type') === "basic.Actor") {
                this.get('link').set('displayType', 'Actor');
                this.get('link').set('linkType', 'is-a');
                this.label(0, { position: 0.5, attrs: { text: { text: this.get('link').get('linkType') } } });
            }
            else {
                this.get('link').set('displayType', 'element'); //TODO: Should this be set to 'link'?
                this.get('link').set('linkType', 'and');
                this.label(0, { position: 0.5, attrs: { text: { text: this.get('link').get('linkType') } } });
            }
        }
    },

    /**
     * Checks if LinkBBM can have a valid absolute relationship
     *
     * @returns Boolean
     */
    isValidAbsoluteRelationship: function () {
        // If relationship is of type evolving and has a target and source, return true
        if (this.get('link').get('linkType') == 'NBD' || this.get('link').get('linkType') == 'NBT' || this.get('link').get('postType') != null) {
            return (this.get('source') != null && this.get('target') != null);
        }
        return false;
    },
});

joint.shapes.basic.Actor = joint.shapes.basic.Generic.extend({
    markup: '<g class="scalable"><rect class = "outer"/></g><circle class="label"/><path class="line"/><text class = "name"/>',

    defaults: joint.util.deepSupplement({
        type: "basic.Actor",
        size: {
            width: 120,
            height: 120
        },
        attrs: {
            ".label": {
                r: 30,
                cx: 20,
                cy: 20,
                fill: '#FFFFA4',
                stroke: '#000000'
            },
            ".outer": {
                width: 100,
                height: 60,
                rx: 10,
                ry: 10,
                fill: '#EBFFEA', //'#CCFFCC',
                stroke: '#000000',
                'stroke-dasharray': '5 2'
            },

            ".name": {
                'text': 'Actor',
                'fill': 'black',
                'ref-y': '0.5',
                'ref-x': '0.5',
                'ref': '.label',
                'font-size': 10,
                'x-alignment': 'middle',
                'y-alignment': 'middle'
            },
            ".line": {
            }
        },
        actor: null,
    }, joint.dia.Element.prototype.defaults),
    changeToOriginalColour: function () {
        this.attr({ '.outer': { 'fill': '#EBFFEA' } });
    },
});<commit_msg>Improved shape of soft goal peanut<commit_after>/* *** Code Inconsistent with Rappid Distribution ***
 * J.Fear - Aug. 2015
 * The following functions differs from the Rappid release. These functions did not exist in the Rappid Library.
 * 		joint.shapes.basic.Intention: Is the superclass for all added nodes (goals, subgoals, tasks, resources).
 * 		joint.shapes.basic.Goal: Goal node.
 * 		joint.shapes.basic.Task: Task node.
 * 		joint.shapes.basic.Softgoal: Softgoal node.
 * 		joint.shapes.basic.Resource: Resource node.
 * 		joint.dia.Actorlink: Link between actors.
 * 		joint.shapes.basic.Actor: Actor node.
 *
 */

joint.dia.BloomingGraph = joint.dia.Graph.extend({
    defaults: joint.util.deepSupplement({
        type: 'goalmodel.Graph',
        maxAbsTime: 100,
        absTimePtsArr: [],
        // TODO: Name with correct type of constraints
        constraints: new ConstraintCollection([]),
    }, joint.dia.Graph.prototype.defaults),

    /**
     * @returns Array of all IntentionBBMs in the graph
     */
    getIntentions: function () {
        return this.getElements().filter(element => element instanceof joint.shapes.basic.Intention)
            .map(intentionCell => intentionCell.get('intention'));
    },

    /**
     * Returns the cell associated with the id parameter
     * There should be a 1 to 1 mapping of ids to cells
     *
     * @param {String} id
     * @returns Cell
     */
    getCellById: function (id) {
        var cell = this.getCells().filter(cell => cell.get('id') == id);
        if (cell.length == 1) {
            return cell[0]
        }
        return null;
    },

})

joint.shapes.basic.Intention = joint.shapes.basic.Generic.extend({
    // Changed satvalue to text
    markup: '<g class="rotatable"><g class="scalable"><rect class="outer"/></g><text class="satvalue"/><text class="funcvalue"/><text class="name"/></g>',
    defaults: joint.util.deepSupplement({
        type: "basic.Intention",
        size: {
            width: 100,
            height: 60
        },
        attrs: {
            ".outer": {
                width: 100,
                height: 60
            },
            // Navie: Changed the initial value of satvalue
            ".satvalue": {
                'stroke': '#000000',
                'stroke-width': 0.5,
                'font-size': 12,
                'text-anchor': 'middle',
                'value': 'none'
            },
            ".funcvalue": {
                'text': "",
                'ref-y': '0.75',
                'ref-x': '0.08',
                'fill': 'black',
                'font-size': 16
            },
            ".name": {
                'fill': 'black',
                'ref-y': '0.5',
                'ref-x': '0.5',
                'font-size': 10,
                'x-alignment': 'middle',
                'y-alignment': 'middle'
            },
        },
        intention: null,
    }, joint.dia.Element.prototype.defaults)
});

joint.shapes.basic.Goal = joint.shapes.basic.Intention.extend({
    defaults: joint.util.deepSupplement({
        type: "basic.Goal",
        attrs: {
            ".outer": {
                rx: 20,
                ry: 20,
                stroke: 'black',
                fill: '#FFCC66',
            },
            ".satvalue": {
                'ref-x': '0.75',
                'ref-y': '0.75'
            },
            ".name": {
                'text': 'Goal',
            }
        }
    }, joint.shapes.basic.Intention.prototype.defaults),
    changeToOriginalColour: function () {
        this.attr({ '.outer': { 'fill': '#FFCC66' } });
    }
});

joint.shapes.basic.Task = joint.shapes.basic.Intention.extend({
    markup: '<g class="rotatable"><g class="scalable"><path class="outer"/></g><text class="satvalue"/><text class="funcvalue"/><text class="name"/></g>',
    defaults: joint.util.deepSupplement({
        type: "basic.Task",
        attrs: {
            ".outer": {

                refD: 'M 0 30 L 20 0 L 80 0 L 100 30 L 80 60 L 20 60 z',
                fill: '#92E3B1',
                stroke: 'black',
                'stroke-width': 1
            },
            ".satvalue": {
                'ref-y': '0.75',
                'ref-x': '0.8',
            },
            ".funcvalue": {
                'ref-y': '0.75',
                'ref-x': '0.2',
            },
            ".name": {
                'text': 'Task',
            }
        }
    }, joint.shapes.basic.Intention.prototype.defaults),
    changeToOriginalColour: function () {
        this.attr({ '.outer': { 'fill': '#92E3B1' } });
    }
});

joint.shapes.basic.Softgoal = joint.shapes.basic.Intention.extend({
    markup: '<g class="rotatable"><g class="scalable"><path class="outer"/></g><text class="satvalue"/><text class="funcvalue"/><text class="name"/></g>',
    defaults: joint.util.deepSupplement({
        type: "basic.Softgoal",
        attrs: {
            ".outer": {
                refD: 'M113.447 101.566 C 77.274 104.408,54.279 137.289,54.279 186.169 C 54.279 255.277,75.723 284.606,122.983 280.136 C 133.561 279.135,140.929 276.657,154.063 269.682 C 177.358 257.311,191.303 256.031,212.469 264.323 C 226.654 269.879,253.330 276.729,272.478 279.733 C 276.925 280.430,298.167 280.099,303.178 279.254 C 332.287 274.345,347.591 254.688,350.106 218.979 C 350.384 215.029,350.611 199.115,350.611 183.616 L 350.611 155.434 349.373 150.547 C 338.978 109.541,306.910 97.327,256.479 115.166 C 237.996 121.704,234.295 122.664,223.350 123.753 C 209.690 125.113,197.527 122.720,178.549 114.940 C 152.968 104.453,131.870 100.119,113.447 101.566',
                stroke: 'black',
                fill: '#FF984F',
            },
            ".satvalue": {
                'ref-y': '0.75',
                'ref-x': '0.76'
            },
            ".funcvalue": {
                'ref-y': '0.75',
                'ref-x': '0.2',
            },
            ".name": {
                'text': 'Soft Goal',
            }
        }
    }, joint.shapes.basic.Intention.prototype.defaults),
    changeToOriginalColour: function () {
        this.attr({ '.outer': { 'fill': '#FF984F' } });
    }
});

joint.shapes.basic.Resource = joint.shapes.basic.Intention.extend({
    defaults: joint.util.deepSupplement({
        type: "basic.Resource",
        attrs: {
            ".outer": {
                stroke: 'black',
                fill: '#92C2FE',
            },
            ".satvalue": {
                transform: "translate(80, 45)",
            },
            ".name": {
                'text': 'Resource',
            }
        }
    }, joint.shapes.basic.Intention.prototype.defaults),
    changeToOriginalColour: function () {
        this.attr({ '.outer': { 'fill': '#92C2FE' } });
    }
});

joint.shapes.basic.CellLink = joint.dia.Link.extend({
    // In initialize, everytime the target is changed, the code updates it
    initialize: function () {
        this.on('change:target', this.updateLinkPointers, this);
        this.on('change:source', this.updateLinkPointers, this);
    },
    defaults: joint.util.deepSupplement({
        type: 'basic.CellLink',
        link: null,
    }),

    /**
     * This function checks the updated target/source to determine if the link is still valid
     * And updates the CellLink type and LinkBBM linkType accordingly
     */
    updateLinkPointers: function () {
        var target = this.getTargetElement();
        var source = this.getSourceElement();
        if ((target !== null && source !== null)) {
            if (((source.get('type') === 'basic.Actor') && (target.get('type') !== 'basic.Actor')) || ((source.get('type') !== 'basic.Actor') && (target.get('type') === 'basic.Actor'))) {
                this.get('link').set('displayType', 'error');
                this.label(0, { position: 0.5, attrs: { text: { text: 'error' } } });
            } else if (source.get('type') === "basic.Actor") {
                this.get('link').set('displayType', 'Actor');
                this.get('link').set('linkType', 'is-a');
                this.label(0, { position: 0.5, attrs: { text: { text: this.get('link').get('linkType') } } });
            }
            else {
                this.get('link').set('displayType', 'element'); //TODO: Should this be set to 'link'?
                this.get('link').set('linkType', 'and');
                this.label(0, { position: 0.5, attrs: { text: { text: this.get('link').get('linkType') } } });
            }
        }
    },

    /**
     * Checks if LinkBBM can have a valid absolute relationship
     *
     * @returns Boolean
     */
    isValidAbsoluteRelationship: function () {
        // If relationship is of type evolving and has a target and source, return true
        if (this.get('link').get('linkType') == 'NBD' || this.get('link').get('linkType') == 'NBT' || this.get('link').get('postType') != null) {
            return (this.get('source') != null && this.get('target') != null);
        }
        return false;
    },
});

joint.shapes.basic.Actor = joint.shapes.basic.Generic.extend({
    markup: '<g class="scalable"><rect class = "outer"/></g><circle class="label"/><path class="line"/><text class = "name"/>',

    defaults: joint.util.deepSupplement({
        type: "basic.Actor",
        size: {
            width: 120,
            height: 120
        },
        attrs: {
            ".label": {
                r: 30,
                cx: 20,
                cy: 20,
                fill: '#FFFFA4',
                stroke: '#000000'
            },
            ".outer": {
                width: 100,
                height: 60,
                rx: 10,
                ry: 10,
                fill: '#EBFFEA', //'#CCFFCC',
                stroke: '#000000',
                'stroke-dasharray': '5 2'
            },

            ".name": {
                'text': 'Actor',
                'fill': 'black',
                'ref-y': '0.5',
                'ref-x': '0.5',
                'ref': '.label',
                'font-size': 10,
                'x-alignment': 'middle',
                'y-alignment': 'middle'
            },
            ".line": {
            }
        },
        actor: null,
    }, joint.dia.Element.prototype.defaults),
    changeToOriginalColour: function () {
        this.attr({ '.outer': { 'fill': '#EBFFEA' } });
    },
});<|endoftext|>