<commit_before>'use strict';

let angular = require('angular');

module.exports = angular
  .module('spinnaker.applications.read.service', [
    require('exports?"restangular"!imports?_=lodash!restangular'),
    require('../../cluster/cluster.service.js'),
    require('../../task/task.read.service.js'),
    require('../../loadBalancer/loadBalancer.read.service.js'),
    require('../../loadBalancer/loadBalancer.transformer.js'),
    require('../../securityGroup/securityGroup.read.service.js'),
    require('../../cache/infrastructureCaches.js'),
    require('../../scheduler/scheduler.service.js'),
    require('../../delivery/service/execution.service.js'),
    require('../../serverGroup/serverGroup.transformer.js'),
    require('../../pipeline/config/services/pipelineConfigService.js'),
    require('../../utils/rx.js'),
    require('../../utils/lodash.js'),
  ])
  .factory('applicationReader', function ($q, $log, $window,  $rootScope, Restangular, _, clusterService, taskReader,
                                          loadBalancerReader, loadBalancerTransformer, securityGroupReader, scheduler,
                                          pipelineConfigService, rx,
                                          infrastructureCaches, settings, executionService, serverGroupTransformer) {

    function listApplications() {
      return Restangular
        .all('applications')
        .withHttpConfig({cache: true})
        .getList();
    }

    var gateEndpoint = Restangular.withConfig(function(RestangularConfigurer) {

      RestangularConfigurer.addElementTransformer('applications', false, function(application) {

        function refreshApplication() {
          if (application.refreshing) {
            $log.warn('application still reloading, skipping reload');
            return $q.when(null);
          }
          application.refreshing = true;
          application.reloadTasks();
          application.reloadExecutions();
          return getApplication(application.name).then(function (newApplication) {
            if (newApplication && !newApplication.notFound) {
              deepCopyApplication(application, newApplication);
              application.autoRefreshStream.onNext();
              application.autoRefreshHandlers.forEach((handler) => handler.call());
              application.oneTimeRefreshHandlers.forEach((handler) => handler.call());
              application.oneTimeRefreshHandlers = [];
              newApplication = null;
            }
            application.refreshing = false;
          })
          .catch(function(rejection) {
              $log.warn('Error refreshing application:', rejection);
              application.refreshing = false;
          });
        }


        function deregisterAutoRefreshHandler(method) {
          application.autoRefreshHandlers = application.autoRefreshHandlers.filter((handler) => handler !== method);
        }

        function registerOneTimeRefreshHandler(handler) {
          application.oneTimeRefreshHandlers.push(handler);
        }

        function registerAutoRefreshHandler(method, scope) {
          if (scope.$$destroyed) {
            return;
          }
          application.autoRefreshHandlers.push(method);
          scope.$on('$destroy', function () {
            application.autoRefreshHandlers = application.autoRefreshHandlers.filter((handler) => handler !== method);
          });
        }

        function enableAutoRefresh(scope) {
          let dataLoader = scheduler.subscribe(refreshApplication);
          scope.$on('$destroy', () => dataLoader.dispose());
        }

        function reloadTasks(forceReload) {
          if (application.tasksLoading && !forceReload) {
            $log.warn('tasks still loading, skipping reload');
            return $q.when(null);
          }
          application.tasksLoading = true;
          let taskLoader = application.loadAllTasks ?
            taskReader.getTasks(application.name) :
            taskReader.getRunningTasks(application.name);
          return taskLoader
            .then(function(tasks) {
              addTasksToApplication(application, tasks);
              application.taskRefreshStream.onNext();
              application.tasksLoaded = true;
              application.tasksLoading = false;
              application.tasksLoadFailure = false;
            })
            .catch(function(rejection) {
              // Gate will send back a 429 error code (TOO_MANY_REQUESTS) and will be caught here
              // As a quick fix we are just adding an empty list to the
              // application, which will let the user know that no tasks were found for the app.
              addTasksToApplication(application, []);
              $log.warn('Error retrieving [tasks]', rejection);
              application.tasksLoading = false;
              application.tasksLoadFailure = true;
              application.taskRefreshStream.onNext(rejection);
            });
        }

        function reloadExecutions(forceReload) {
          if (application.executionsLoading && !forceReload) {
            $log.warn('executions still loading, skipping reload');
            return $q.when(null);
          }
          application.executionsLoading = true;
          let executionLoader = application.loadAllExecutions ?
            executionService.getExecutions(application.name) :
            executionService.getRunningExecutions(application.name);
          return executionLoader
            .then(function(executions) {
              executionService.transformExecutions(application, executions);
              addExecutionsToApplication(application, executions);
              application.executionsLoaded = true;
              application.executionsLoading = false;
              application.executionsLoadFailure = false;
              application.executionRefreshStream.onNext();
            })
            .catch(function(rejection) {
              // Gate will send back a 429 error code (TOO_MANY_REQUESTS) and will be caught here.
              $log.warn('Error retrieving [executions]', rejection);
              application.executionsLoading = false;
              application.executionsLoadFailure = true;
              application.executionRefreshStream.onNext(rejection);
            });
        }

        function reloadPipelineConfigs() {
          if (application.pipelineConfigsLoading) {
            $log.warn('pipeline configs still loading, skipping reload');
            return $q.when(null);
          }
          application.pipelineConfigsLoading = true;
          let pipelineLoader = pipelineConfigService.getPipelinesForApplication(application.name),
              strategyLoader = pipelineConfigService.getStrategiesForApplication(application.name);
          return $q.all({pipelines: pipelineLoader, strategies: strategyLoader})
            .then((configs) => {
              application.pipelineConfigs = configs.pipelines;
              application.strategyConfigs = configs.strategies;
              application.pipelineConfigsLoaded = true;
              application.pipelineConfigsLoading = false;
              application.pipelineConfigsLoadFailure = false;
              application.pipelineConfigRefreshStream.onNext();
            }).catch(function(rejection) {
              $log.warn('Error retrieving [pipelineConfigs]', rejection);
              application.pipelineConfigsLoading = false;
              application.pipelineConfigsLoadFailure = true;
              application.pipelineConfigRefreshStream.onNext();
            });
        }

        application.registerAutoRefreshHandler = registerAutoRefreshHandler;
        application.deregisterAutoRefreshHandler = deregisterAutoRefreshHandler;
        application.registerOneTimeRefreshHandler = registerOneTimeRefreshHandler;
        application.autoRefreshHandlers = [];
        application.oneTimeRefreshHandlers = [];
        application.refreshImmediately = scheduler.scheduleImmediate;
        application.enableAutoRefresh = enableAutoRefresh;
        application.reloadTasks = reloadTasks;
        application.reloadExecutions = reloadExecutions;
        application.reloadPipelineConfigs = reloadPipelineConfigs;
        application.autoRefreshStream = new rx.Subject();
        application.taskRefreshStream = new rx.Subject();
        application.executionRefreshStream = new rx.Subject();
        application.pipelineConfigRefreshStream = new rx.Subject();

        // These attributes are stored as strings.
        if (application.fromServer) {
          application.attributes.platformHealthOnly = application.attributes.platformHealthOnly === 'true';
          application.attributes.platformHealthOnlyShowOverride = application.attributes.platformHealthOnlyShowOverride === 'true';
        }
        return application;

      });
    });

    function getApplicationEndpoint(application) {
      return gateEndpoint.one('applications', application);
    }

    function addDefaultRegion(application) {
      application.defaultRegions = {};
      var serverGroupProviders = _.pluck(application.serverGroups, 'provider'),
          loadBalancerProviders = _.pluck(application.loadBalancers, 'type'),
          securityGroupProviders = _.pluck(application.securityGroups, 'type');

      var allProviders = _.union(serverGroupProviders, loadBalancerProviders, securityGroupProviders);
      allProviders.forEach((provider) => {
        var fromServerGroups = _.pluck(_.filter(application.serverGroups, {provider: provider}), 'region'),
            fromLoadBalancers = _.pluck(_.filter(application.loadBalancers, {type: provider}), 'region'),
            fromSecurityGroups = _.pluck(_.filter(application.securityGroups, {type: provider}), 'region');
        var allRegions = _.union(fromServerGroups, fromLoadBalancers, fromSecurityGroups);
        if (allRegions.length === 1) {
          application.defaultRegions[provider] = allRegions[0];
        }
      });
    }

    function addDefaultCredentials(application) {
      application.defaultCredentials = {};
      var serverGroupProviders = _.pluck(application.serverGroups, 'provider'),<commit_msg>application.attributes.platformHealthOnly and application.attributes.platformHealthOnlyShowOverride seem to come back as booleans now instead of as strings.<commit_after>'use strict';

let angular = require('angular');

module.exports = angular
  .module('spinnaker.applications.read.service', [
    require('exports?"restangular"!imports?_=lodash!restangular'),
    require('../../cluster/cluster.service.js'),
    require('../../task/task.read.service.js'),
    require('../../loadBalancer/loadBalancer.read.service.js'),
    require('../../loadBalancer/loadBalancer.transformer.js'),
    require('../../securityGroup/securityGroup.read.service.js'),
    require('../../cache/infrastructureCaches.js'),
    require('../../scheduler/scheduler.service.js'),
    require('../../delivery/service/execution.service.js'),
    require('../../serverGroup/serverGroup.transformer.js'),
    require('../../pipeline/config/services/pipelineConfigService.js'),
    require('../../utils/rx.js'),
    require('../../utils/lodash.js'),
  ])
  .factory('applicationReader', function ($q, $log, $window,  $rootScope, Restangular, _, clusterService, taskReader,
                                          loadBalancerReader, loadBalancerTransformer, securityGroupReader, scheduler,
                                          pipelineConfigService, rx,
                                          infrastructureCaches, settings, executionService, serverGroupTransformer) {

    function listApplications() {
      return Restangular
        .all('applications')
        .withHttpConfig({cache: true})
        .getList();
    }

    var gateEndpoint = Restangular.withConfig(function(RestangularConfigurer) {

      RestangularConfigurer.addElementTransformer('applications', false, function(application) {

        function refreshApplication() {
          if (application.refreshing) {
            $log.warn('application still reloading, skipping reload');
            return $q.when(null);
          }
          application.refreshing = true;
          application.reloadTasks();
          application.reloadExecutions();
          return getApplication(application.name).then(function (newApplication) {
            if (newApplication && !newApplication.notFound) {
              deepCopyApplication(application, newApplication);
              application.autoRefreshStream.onNext();
              application.autoRefreshHandlers.forEach((handler) => handler.call());
              application.oneTimeRefreshHandlers.forEach((handler) => handler.call());
              application.oneTimeRefreshHandlers = [];
              newApplication = null;
            }
            application.refreshing = false;
          })
          .catch(function(rejection) {
              $log.warn('Error refreshing application:', rejection);
              application.refreshing = false;
          });
        }


        function deregisterAutoRefreshHandler(method) {
          application.autoRefreshHandlers = application.autoRefreshHandlers.filter((handler) => handler !== method);
        }

        function registerOneTimeRefreshHandler(handler) {
          application.oneTimeRefreshHandlers.push(handler);
        }

        function registerAutoRefreshHandler(method, scope) {
          if (scope.$$destroyed) {
            return;
          }
          application.autoRefreshHandlers.push(method);
          scope.$on('$destroy', function () {
            application.autoRefreshHandlers = application.autoRefreshHandlers.filter((handler) => handler !== method);
          });
        }

        function enableAutoRefresh(scope) {
          let dataLoader = scheduler.subscribe(refreshApplication);
          scope.$on('$destroy', () => dataLoader.dispose());
        }

        function reloadTasks(forceReload) {
          if (application.tasksLoading && !forceReload) {
            $log.warn('tasks still loading, skipping reload');
            return $q.when(null);
          }
          application.tasksLoading = true;
          let taskLoader = application.loadAllTasks ?
            taskReader.getTasks(application.name) :
            taskReader.getRunningTasks(application.name);
          return taskLoader
            .then(function(tasks) {
              addTasksToApplication(application, tasks);
              application.taskRefreshStream.onNext();
              application.tasksLoaded = true;
              application.tasksLoading = false;
              application.tasksLoadFailure = false;
            })
            .catch(function(rejection) {
              // Gate will send back a 429 error code (TOO_MANY_REQUESTS) and will be caught here
              // As a quick fix we are just adding an empty list to the
              // application, which will let the user know that no tasks were found for the app.
              addTasksToApplication(application, []);
              $log.warn('Error retrieving [tasks]', rejection);
              application.tasksLoading = false;
              application.tasksLoadFailure = true;
              application.taskRefreshStream.onNext(rejection);
            });
        }

        function reloadExecutions(forceReload) {
          if (application.executionsLoading && !forceReload) {
            $log.warn('executions still loading, skipping reload');
            return $q.when(null);
          }
          application.executionsLoading = true;
          let executionLoader = application.loadAllExecutions ?
            executionService.getExecutions(application.name) :
            executionService.getRunningExecutions(application.name);
          return executionLoader
            .then(function(executions) {
              executionService.transformExecutions(application, executions);
              addExecutionsToApplication(application, executions);
              application.executionsLoaded = true;
              application.executionsLoading = false;
              application.executionsLoadFailure = false;
              application.executionRefreshStream.onNext();
            })
            .catch(function(rejection) {
              // Gate will send back a 429 error code (TOO_MANY_REQUESTS) and will be caught here.
              $log.warn('Error retrieving [executions]', rejection);
              application.executionsLoading = false;
              application.executionsLoadFailure = true;
              application.executionRefreshStream.onNext(rejection);
            });
        }

        function reloadPipelineConfigs() {
          if (application.pipelineConfigsLoading) {
            $log.warn('pipeline configs still loading, skipping reload');
            return $q.when(null);
          }
          application.pipelineConfigsLoading = true;
          let pipelineLoader = pipelineConfigService.getPipelinesForApplication(application.name),
              strategyLoader = pipelineConfigService.getStrategiesForApplication(application.name);
          return $q.all({pipelines: pipelineLoader, strategies: strategyLoader})
            .then((configs) => {
              application.pipelineConfigs = configs.pipelines;
              application.strategyConfigs = configs.strategies;
              application.pipelineConfigsLoaded = true;
              application.pipelineConfigsLoading = false;
              application.pipelineConfigsLoadFailure = false;
              application.pipelineConfigRefreshStream.onNext();
            }).catch(function(rejection) {
              $log.warn('Error retrieving [pipelineConfigs]', rejection);
              application.pipelineConfigsLoading = false;
              application.pipelineConfigsLoadFailure = true;
              application.pipelineConfigRefreshStream.onNext();
            });
        }

        application.registerAutoRefreshHandler = registerAutoRefreshHandler;
        application.deregisterAutoRefreshHandler = deregisterAutoRefreshHandler;
        application.registerOneTimeRefreshHandler = registerOneTimeRefreshHandler;
        application.autoRefreshHandlers = [];
        application.oneTimeRefreshHandlers = [];
        application.refreshImmediately = scheduler.scheduleImmediate;
        application.enableAutoRefresh = enableAutoRefresh;
        application.reloadTasks = reloadTasks;
        application.reloadExecutions = reloadExecutions;
        application.reloadPipelineConfigs = reloadPipelineConfigs;
        application.autoRefreshStream = new rx.Subject();
        application.taskRefreshStream = new rx.Subject();
        application.executionRefreshStream = new rx.Subject();
        application.pipelineConfigRefreshStream = new rx.Subject();
        return application;
      });
    });

    function getApplicationEndpoint(application) {
      return gateEndpoint.one('applications', application);
    }

    function addDefaultRegion(application) {
      application.defaultRegions = {};
      var serverGroupProviders = _.pluck(application.serverGroups, 'provider'),
          loadBalancerProviders = _.pluck(application.loadBalancers, 'type'),
          securityGroupProviders = _.pluck(application.securityGroups, 'type');

      var allProviders = _.union(serverGroupProviders, loadBalancerProviders, securityGroupProviders);
      allProviders.forEach((provider) => {
        var fromServerGroups = _.pluck(_.filter(application.serverGroups, {provider: provider}), 'region'),
            fromLoadBalancers = _.pluck(_.filter(application.loadBalancers, {type: provider}), 'region'),
            fromSecurityGroups = _.pluck(_.filter(application.securityGroups, {type: provider}), 'region');
        var allRegions = _.union(fromServerGroups, fromLoadBalancers, fromSecurityGroups);
        if (allRegions.length === 1) {
          application.defaultRegions[provider] = allRegions[0];
        }
      });
    }

    function addDefaultCredentials(application) {
      application.defaultCredentials = {};
      var serverGroupProviders = _.pluck(application.serverGroups, 'provider'),
{'fraction_non_alphanumeric': 0.10311071357582985, 'fraction_numerical': 0.000795070562512423, 'mean_word_length': 2.577141841450409, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 17, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 12, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1220941', 'n_tokens_mistral': 4689, 'n_tokens_neox': 4602, 'n_words': 824}