<commit_before>'use strict';

define(['angular'], function(angular) {

  var app = angular.module('portal.notifications.controllers ', []);

  app.controller('PortalNotificationController', [ '$scope',
                                                   '$rootScope',
                                                   '$location',
                                                   '$localStorage',
                                                   'NOTIFICATION',
                                                   'SERVICE_LOC',
                                                   'filterFilter',
                                                   'notificationsService',
                                           function($scope,
                                                    $rootScope,
                                                    $location,
                                                    $localStorage,
                                                    NOTIFICATION,
                                                    SERVICE_LOC,
                                                    filterFilter,
                                                    notificationsService){

    var configurePriorityNotificationScope = function(data){
      $scope.priorityNotifications = filterFilter(data, {priority : true});
      if ($scope.priorityNotifications && $scope.priorityNotifications.length > 0) {
        $scope.hasPriorityNotifications = true;
        $('.page-content').addClass('has-priority-nots');
        if($scope.headerCtrl) {
          $scope.headerCtrl.hasPriorityNotifications = true;
        }
      } else {
        $('.page-content').removeClass('has-priority-nots');
        $scope.hasPriorityNotifications = false;
        if($scope.headerCtrl) {
          $scope.headerCtrl.hasPriorityNotifications = false;
        }
      }
    };

    var clearPriorityNotificationFlags = function() {
      $scope.priorityNotifications = [];
      $scope.hasPriorityNotifications = false;
      if($scope.headerCtrl) {
        $scope.headerCtrl.hasPriorityNotifications = false;
      }
      $('.page-content').removeClass('has-priority-nots');
    }

    var successFn = function(data){
      //success state
      $scope.count = data.length;
      $scope.isEmpty = ($scope.count === 0);
      $scope.status = "You have "+ ($scope.isEmpty ? "no " : "") + "notifications";
      $scope.notifications = data;
      if($location.url().indexOf('notifications') === -1) {
        configurePriorityNotificationScope(data);
      } else {
        clearPriorityNotificationFlags();
      }
    };

    var errorFn = function(data){
      //error state (logging of error happens at service layer)
      $scope.count = 0;
      $scope.isEmpty = true;
    };

    var dismissedSuccessFn = function(data) {
      $rootScope.dismissedNotificationIds = data;
    };

    $scope.dismissedCount = function() {
      return $rootScope.dismissedNotificationIds ? $rootScope.dismissedNotificationIds.length : 0;
    }

    $scope.countWithDismissed = function() {
      var count = 0;
      if($rootScope.dismissedNotificationIds && $scope.notifications) {
        for(var i = 0; i < $scope.notifications.length; i++) {
          var curNot = $scope.notifications[i];
          var dismissed = false;
          if(curNot.dismissable) {
            for(var j =0; j < $rootScope.dismissedNotificationIds.length; j++) {
              dismissed = curNot.id === $rootScope.dismissedNotificationIds[j];
              if(dismissed) {
                break;
              }
            }
          }
          if(!dismissed) {
            count++;
          }
        }
      }

      return count;
    }

    $scope.shouldShow = function(notification) {
      var res = $scope.isDismissed(notification);
      return $scope.mode === 'new' ? !res : res;
    }

    $scope.isDismissed = function(notification) {
      for(var i = 0; i < $rootScope.dismissedNotificationIds.length; i++) {
        if(notification.id === $rootScope.dismissedNotificationIds[i]) {
          return true;
        }
      }
      return false;
    };

    $scope.dismiss = function (notification) {
      $rootScope.dismissedNotificationIds.push(notification.id);
      if(SERVICE_LOC.kvURL) { //key value store enabled, we can store dismiss of notifications
        notificationsService.setDismissedNotifications($rootScope.dismissedNotificationIds);
      }
    }

    $scope.undismiss = function(notification) {
      var index = $rootScope.dismissedNotificationIds.indexOf(notification.id);
      if(index !== -1) {
      	$rootScope.dismissedNotificationIds.splice(index,1);
      }
      if(SERVICE_LOC.kvURL) { //key value store enabled, we can store dismiss of notifications
        notificationsService.setDismissedNotifications($rootScope.dismissedNotificationIds);
      }
    }

    $scope.switch = function(mode) {
      $scope.mode = mode;
    }

    var init = function(){
      $scope.mode = 'new';
      $scope.notifications = [];
      $rootScope.dismissedNotificationIds = $rootScope.dismissedNotificationIds || [];
      $scope.count = 0;
      $scope.isEmpty = false;
      $scope.notificationUrl = NOTIFICATION.notificationFullURL;
      $scope.notificationsEnabled = NOTIFICATION.enabled;

      if(NOTIFICATION.enabled && !$rootScope.GuestMode) {
        if(SERVICE_LOC.kvURL && $rootScope.dismissedNotificationIds.length === 0) {
          //key value store enabled, we can store dismiss of notifications
          notificationsService.getDismissedNotificationIds().then(dismissedSuccessFn);
        }
        if(NOTIFICATION.groupFiltering && !$localStorage.disableGroupFilteringForNotifications) {
          notificationsService.getNotificationsByGroups().then(successFn, errorFn);
        } else {
          notificationsService.getAllNotifications().then(successFn, errorFn);
        }

        $scope.$on('$locationChangeStart', function(event) {
          if ($location.url().indexOf('notification') === -1) {
            configurePriorityNotificationScope($scope.notifications);
          } else {
            clearPriorityNotificationFlags();
          }
        });
      }
    }

    init();
  }]);

  return app;

});
<commit_msg>fix npe with notification controller when no notifications are returned from the service (#248)<commit_after>'use strict';

define(['angular'], function(angular) {

  var app = angular.module('portal.notifications.controllers ', []);

  app.controller('PortalNotificationController', [ '$scope',
                                                   '$rootScope',
                                                   '$location',
                                                   '$localStorage',
                                                   'NOTIFICATION',
                                                   'SERVICE_LOC',
                                                   'filterFilter',
                                                   'notificationsService',
                                           function($scope,
                                                    $rootScope,
                                                    $location,
                                                    $localStorage,
                                                    NOTIFICATION,
                                                    SERVICE_LOC,
                                                    filterFilter,
                                                    notificationsService){

    var configurePriorityNotificationScope = function(data){
      $scope.priorityNotifications = filterFilter(data, {priority : true});
      if ($scope.priorityNotifications && $scope.priorityNotifications.length > 0) {
        $scope.hasPriorityNotifications = true;
        $('.page-content').addClass('has-priority-nots');
        if($scope.headerCtrl) {
          $scope.headerCtrl.hasPriorityNotifications = true;
        }
      } else {
        $('.page-content').removeClass('has-priority-nots');
        $scope.hasPriorityNotifications = false;
        if($scope.headerCtrl) {
          $scope.headerCtrl.hasPriorityNotifications = false;
        }
      }
    };

    var clearPriorityNotificationFlags = function() {
      $scope.priorityNotifications = [];
      $scope.hasPriorityNotifications = false;
      if($scope.headerCtrl) {
        $scope.headerCtrl.hasPriorityNotifications = false;
      }
      $('.page-content').removeClass('has-priority-nots');
    }

    var successFn = function(data){
      //success state
      $scope.count = data ? data.length : 0;
      $scope.isEmpty = ($scope.count === 0);
      $scope.status = "You have "+ ($scope.isEmpty ? "no " : "") + "notifications";
      $scope.notifications = data;
      if($location.url().indexOf('notifications') === -1) {
        configurePriorityNotificationScope(data);
      } else {
        clearPriorityNotificationFlags();
      }
    };

    var errorFn = function(data){
      //error state (logging of error happens at service layer)
      $scope.count = 0;
      $scope.isEmpty = true;
    };

    var dismissedSuccessFn = function(data) {
      $rootScope.dismissedNotificationIds = data;
    };

    $scope.dismissedCount = function() {
      return $rootScope.dismissedNotificationIds ? $rootScope.dismissedNotificationIds.length : 0;
    }

    $scope.countWithDismissed = function() {
      var count = 0;
      if($rootScope.dismissedNotificationIds && $scope.notifications) {
        for(var i = 0; i < $scope.notifications.length; i++) {
          var curNot = $scope.notifications[i];
          var dismissed = false;
          if(curNot.dismissable) {
            for(var j =0; j < $rootScope.dismissedNotificationIds.length; j++) {
              dismissed = curNot.id === $rootScope.dismissedNotificationIds[j];
              if(dismissed) {
                break;
              }
            }
          }
          if(!dismissed) {
            count++;
          }
        }
      }

      return count;
    }

    $scope.shouldShow = function(notification) {
      var res = $scope.isDismissed(notification);
      return $scope.mode === 'new' ? !res : res;
    }

    $scope.isDismissed = function(notification) {
      for(var i = 0; i < $rootScope.dismissedNotificationIds.length; i++) {
        if(notification.id === $rootScope.dismissedNotificationIds[i]) {
          return true;
        }
      }
      return false;
    };

    $scope.dismiss = function (notification) {
      $rootScope.dismissedNotificationIds.push(notification.id);
      if(SERVICE_LOC.kvURL) { //key value store enabled, we can store dismiss of notifications
        notificationsService.setDismissedNotifications($rootScope.dismissedNotificationIds);
      }
    }

    $scope.undismiss = function(notification) {
      var index = $rootScope.dismissedNotificationIds.indexOf(notification.id);
      if(index !== -1) {
      	$rootScope.dismissedNotificationIds.splice(index,1);
      }
      if(SERVICE_LOC.kvURL) { //key value store enabled, we can store dismiss of notifications
        notificationsService.setDismissedNotifications($rootScope.dismissedNotificationIds);
      }
    }

    $scope.switch = function(mode) {
      $scope.mode = mode;
    }

    var init = function(){
      $scope.mode = 'new';
      $scope.notifications = [];
      $rootScope.dismissedNotificationIds = $rootScope.dismissedNotificationIds || [];
      $scope.count = 0;
      $scope.isEmpty = false;
      $scope.notificationUrl = NOTIFICATION.notificationFullURL;
      $scope.notificationsEnabled = NOTIFICATION.enabled;

      if(NOTIFICATION.enabled && !$rootScope.GuestMode) {
        if(SERVICE_LOC.kvURL && $rootScope.dismissedNotificationIds.length === 0) {
          //key value store enabled, we can store dismiss of notifications
          notificationsService.getDismissedNotificationIds().then(dismissedSuccessFn);
        }
        if(NOTIFICATION.groupFiltering && !$localStorage.disableGroupFilteringForNotifications) {
          notificationsService.getNotificationsByGroups().then(successFn, errorFn);
        } else {
          notificationsService.getAllNotifications().then(successFn, errorFn);
        }

        $scope.$on('$locationChangeStart', function(event) {
          if ($location.url().indexOf('notification') === -1) {
            configurePriorityNotificationScope($scope.notifications);
          } else {
            clearPriorityNotificationFlags();
          }
        });
      }
    }

    init();
  }]);

  return app;

});
<|endoftext|>


<commit_before>
var API = {

  /**
   @private
  */
  call_: function(httpMethod, service, Id, params, requestBody, contentType) {
    var options =
        {
          "method" : httpMethod
        };

    if (contentType != null) {
      options.contentType = contentType;
    }

    if (requestBody != null) {
      options.payload = requestBody;
    }

    var queryParams = null;
    if (params != null) {
      queryParams = BkperUtils.buildURLParams(params);
    }

    var serviceFullPath = "ledgers";

    if (Id != null) {
      serviceFullPath += "/" + Id
    }

    if (service != null) {
      serviceFullPath += "/" + service;
    }

    if (queryParams != null) {
      serviceFullPath += "?" +queryParams;
    }

    var contentText = API.fetch("bkper","v2", serviceFullPath, options).getContentText();

    return contentText;
  },

  /**
  @private
 */
  fetch: function(apiName, version, path, params) {
    var apiURL = "https://bkper-hrd.appspot.com/_ah/api/" + apiName + "/" + version + "/" + path;

    if (params == null) {
      params = new Object();
    }

    if (params.headers == null) {
      params.headers = new Object();
    }

    try {
      params.headers["x-bkper-app-id"] = APP_ID;
    } catch (error) {
      //APP_ID not defined. Fallback.
      params.headers["x-bkper-app-id"] = "bkper-gas";
    }

    var accessToken = Authorizer_.getAccessToken();
    params.headers.Authorization = "Bearer " + accessToken;
    if (params.contentType == null) {
      params.contentType = "application/json; charset=UTF-8";
    }

  var retries = 0;
  var sleepTime = 1000;
  while (true) {
    try {
      var response = UrlFetchApp.fetch(apiURL, params);
      return response;
    } catch (error) {
      var errorMsg = error + "";
      if (errorMsg.indexOf("code 500") >= 0 || errorMsg.indexOf("Address unavailable") >= 0 || errorMsg.indexOf("Unexpected error") >= 0) {
        Logger.log("Failed to execute: " + retries);
        if (retries > 4) {
          throw error;
        } else {
          Logger.log("Retrying in " + (sleepTime/1000) + " secs...");
          Utilities.sleep(sleepTime);
          sleepTime = sleepTime * 2;
          retries++;
        }
      } else {
        if (errorMsg.indexOf("403") >= 0 || errorMsg.indexOf("forbidden") >= 0) {
          Authorizer_.validateAccessToken();
        }
        throw error;
      }
    }
  }

  },

}

//function getUploadUrl() {
//  var params =
//      {
//        "method" : "get",
//      };
//
//  if (params.headers == null) {
//    params.headers = new Object();
//  }
//  var accessToken = Authorizer_.getAccessToken();
//  params.headers.Authorization = "Bearer " + accessToken;
//
//  var contentText = UrlFetchApp.fetch("https://bkper-hrd.appspot.com/_ah/api/bkper/v1/uploadUrl", params).getContentText();
//
//  var contentObj = JSON.parse(contentText);
//  return contentObj.url;
//}
<commit_msg>Adding optional API_KEY<commit_after>
var API = {

  /**
   @private
  */
  call_: function(httpMethod, service, Id, params, requestBody, contentType) {
    var options =
        {
          "method" : httpMethod
        };

    if (contentType != null) {
      options.contentType = contentType;
    }

    if (requestBody != null) {
      options.payload = requestBody;
    }

    var queryParams = null;

    if (params == null) {
      params = new Object();
    }

    try {
      params.key = APP_KEY;
    } catch (error) {
      //APP_KEY not defined. Fallback.
    }

    queryParams = BkperUtils.buildURLParams(params);

    var serviceFullPath = "ledgers";

    if (Id != null) {
      serviceFullPath += "/" + Id
    }

    if (service != null) {
      serviceFullPath += "/" + service;
    }

    if (queryParams != null && queryParams != "") {
      serviceFullPath += "?" +queryParams;
    }

    var contentText = API.fetch("bkper","v2", serviceFullPath, options).getContentText();

    return contentText;
  },

  /**
  @private
 */
  fetch: function(apiName, version, path, params) {
    var apiURL = "https://bkper-hrd.appspot.com/_ah/api/" + apiName + "/" + version + "/" + path;

    if (params == null) {
      params = new Object();
    }

    if (params.headers == null) {
      params.headers = new Object();
    }

    params.headers["x-bkper-app-id"] = "bkper-gas";

    var accessToken = Authorizer_.getAccessToken();
    params.headers.Authorization = "Bearer " + accessToken;
    if (params.contentType == null) {
      params.contentType = "application/json; charset=UTF-8";
    }

  var retries = 0;
  var sleepTime = 1000;
  while (true) {
    try {
      Logger.log(apiURL)
      var response = UrlFetchApp.fetch(apiURL, params);
      return response;
    } catch (error) {
      var errorMsg = error + "";
      if (errorMsg.indexOf("code 500") >= 0 || errorMsg.indexOf("Address unavailable") >= 0 || errorMsg.indexOf("Unexpected error") >= 0) {
        Logger.log("Failed to execute: " + retries);
        if (retries > 4) {
          throw error;
        } else {
          Logger.log("Retrying in " + (sleepTime/1000) + " secs...");
          Utilities.sleep(sleepTime);
          sleepTime = sleepTime * 2;
          retries++;
        }
      } else {
        if (errorMsg.indexOf("403") >= 0 || errorMsg.indexOf("forbidden") >= 0) {
          Authorizer_.validateAccessToken();
        }
        throw error;
      }
    }
  }

  },

}

//function getUploadUrl() {
//  var params =
//      {
//        "method" : "get",
//      };
//
//  if (params.headers == null) {
//    params.headers = new Object();
//  }
//  var accessToken = Authorizer_.getAccessToken();
//  params.headers.Authorization = "Bearer " + accessToken;
//
//  var contentText = UrlFetchApp.fetch("https://bkper-hrd.appspot.com/_ah/api/bkper/v1/uploadUrl", params).getContentText();
//
//  var contentObj = JSON.parse(contentText);
//  return contentObj.url;
//}
<|endoftext|>


<commit_before>var config = {}
module.exports = config;

config.active_modules = [
    {
        name: 'main',
        route: '/'
    },
    {
        name: 'user',
        route: '/user'
    },
    {
        name: 'form',
        route: '/form'
    }
]

// Margan is used to be logger, visit here to get more info:
// https://github.com/expressjs/morgan
config.logType = 'dev';

config.session = {
    secret: "c-fAr",
    resave: false,
    saveUninitialized: true,
    cookie: {},
    name: 'c-far-session'
}

if(process.env.NODE_ENV === 'production'){
    config.session.cookie.secure = true;
}
    <commit_msg>還沒完工 先不要啟用模組<commit_after>var config = {}
module.exports = config;

config.active_modules = [
    {
        name: 'main',
        route: '/'
    },
    {
        name: 'user',
        route: '/user'
    },
    // {
    //     name: 'form',
    //     route: '/form'
    // }
]

// Margan is used to be logger, visit here to get more info:
// https://github.com/expressjs/morgan
config.logType = 'dev';

config.session = {
    secret: "c-fAr",
    resave: false,
    saveUninitialized: true,
    cookie: {},
    name: 'c-far-session'
}

if(process.env.NODE_ENV === 'production'){
    config.session.cookie.secure = true;
}
    <|endoftext|>


<commit_before>Conductor.Models = Conductor.Models || {}

Conductor.Models.Pool = Backbone.Model.extend({
  urlRoot: Conductor.prefixedPath('/pools')

  initialize: function() {
    this.deployments = new Conductor.Models.Deployments().filter(function(attributes) {
        return attributes.pool.id == this.id;
        });
  }
});

Conductor.Models.Pools = Backbone.Collection.extend({
  model: Backbone.Model.Pool,
  queryParams: {},
  url: function() {
    var path = Conductor.prefixedPath('/pools');
    return Conductor.parameterizedPath(path, this.queryParams);
  }
});

Conductor.Models.Instance = Backbone.Model.extend({
  urlRoot: Conductor.prefixedPath('/instances')
});

Conductor.Models.Instances = Backbone.Collection.extend({
  model: Backbone.Model.Instance,
  queryParams: {},
  url: function() {
    var path = Conductor.prefixedPath('/instances');
    return Conductor.parameterizedPath(path, this.queryParams);
  }
});

Conductor.Models.Deployment = Backbone.Model.extend({
  urlRoot: Conductor.prefixedPath('/deployments'),

  initialize: function() {
    this.instances = new Conductor.Models.Instances();
    this.instances.url = this.urlRoot + '/' + this.id + '/instances';
  }

});

Conductor.Models.Deployments = Backbone.Collection.extend({
  model: Backbone.Model.Deployment,
  queryParams: {},
  url: function() {
    var path = Conductor.prefixedPath('/deployments');
    return Conductor.parameterizedPath(path, this.queryParams);
  }
});

Conductor.Models.Image = Backbone.Model.extend({
  queryParams: {},
  url: function() {
    var path = Conductor.prefixedPath('/images/' + this.id);
    return Conductor.parameterizedPath(path, this.queryParams);
  }
});
<commit_msg>Fixing syntax error in model.js<commit_after>Conductor.Models = Conductor.Models || {}

Conductor.Models.Pool = Backbone.Model.extend({
  urlRoot: Conductor.prefixedPath('/pools'),

  initialize: function() {
    this.deployments = new Conductor.Models.Deployments().filter(function(attributes) {
      return attributes.pool.id == this.id;
    });
  }
});

Conductor.Models.Pools = Backbone.Collection.extend({
  model: Backbone.Model.Pool,
  queryParams: {},
  url: function() {
    var path = Conductor.prefixedPath('/pools');
    return Conductor.parameterizedPath(path, this.queryParams);
  }
});

Conductor.Models.Instance = Backbone.Model.extend({
  urlRoot: Conductor.prefixedPath('/instances')
});

Conductor.Models.Instances = Backbone.Collection.extend({
  model: Backbone.Model.Instance,
  queryParams: {},
  url: function() {
    var path = Conductor.prefixedPath('/instances');
    return Conductor.parameterizedPath(path, this.queryParams);
  }
});

Conductor.Models.Deployment = Backbone.Model.extend({
  urlRoot: Conductor.prefixedPath('/deployments'),

  initialize: function() {
    this.instances = new Conductor.Models.Instances();
    this.instances.url = this.urlRoot + '/' + this.id + '/instances';
  }

});

Conductor.Models.Deployments = Backbone.Collection.extend({
  model: Backbone.Model.Deployment,
  queryParams: {},
  url: function() {
    var path = Conductor.prefixedPath('/deployments');
    return Conductor.parameterizedPath(path, this.queryParams);
  }
});

Conductor.Models.Image = Backbone.Model.extend({
  queryParams: {},
  url: function() {
    var path = Conductor.prefixedPath('/images/' + this.id);
    return Conductor.parameterizedPath(path, this.queryParams);
  }
});
<|endoftext|>


<commit_before>"use strict";function _interopRequireDefault(e){return e&&e.__esModule?e:{default:e}}function DMFetch(e,r,t,o,n){o||(o={}),_config2.default&&_config2.default.dataDomain&&(e=_config2.default.dataDomain+e);var a={};a["X-Requested-With"]="XMLHttpRequest";var u=window.reduxStore.getState().user;if(u&&u.currentTeam&&(a["X-Current-Team"]=u.currentTeam.id),a.Authorization="Bearer as",a["X-Socket-ID"]=u.socketId,a.Accept="application/json","GET"!=r&&t&&(a["Content-Type"]="application/json"),t&&n)throw new Error("Can not have both json and formdata in a request");return t?t=JSON.stringify(t):n instanceof FormData&&(t=n),fetch(e,{method:r,headers:a,credentials:"include",body:t}).then(function(e){return 4==Math.floor(e.status/100)?(document.location="/logout",{}):o.returnResponse?e:o.returnAllData?responseToJson(e):returnDataFromResponse(e)})}function returnDataFromResponse(e){return responseToJson(e).then(function(e){if(e.errors)for(var r=0;r<e.errors.length;r++)(0,_errorModal2.default)(e.errors[r].message);return e.data})}function responseToJson(e){return e.json()}var _errorModal=require("./errorModal"),_errorModal2=_interopRequireDefault(_errorModal),_config=require("../../../../../../../../../resources/assets/react-app/config"),_config2=_interopRequireDefault(_config),Http={get:function(e,r,t,o){return DMFetch(e,"GET",r,t,o)},post:function(e,r,t,o){return DMFetch(e,"POST",r,t,o)},put:function(e,r,t,o){return DMFetch(e,"PUT",r,t,o)},delete:function(e,r,t,o){return DMFetch(e,"DELETE",r,t,o)}};module.exports=Http;<commit_msg>don't redirect to logout<commit_after>"use strict";function _interopRequireDefault(e){return e&&e.__esModule?e:{default:e}}function DMFetch(e,r,t,n,o){n||(n={}),_config2.default&&_config2.default.dataDomain&&(e=_config2.default.dataDomain+e);var a={};a["X-Requested-With"]="XMLHttpRequest";var u=window.reduxStore.getState().user;if(u&&u.currentTeam&&(a["X-Current-Team"]=u.currentTeam.id),a.Authorization="Bearer as",a["X-Socket-ID"]=u.socketId,a.Accept="application/json","GET"!=r&&t&&(a["Content-Type"]="application/json"),t&&o)throw new Error("Can not have both json and formdata in a request");return t?t=JSON.stringify(t):o instanceof FormData&&(t=o),fetch(e,{method:r,headers:a,credentials:"include",body:t}).then(function(e){return 4==Math.floor(e.status/100)?{}:n.returnResponse?e:n.returnAllData?responseToJson(e):returnDataFromResponse(e)})}function returnDataFromResponse(e){return responseToJson(e).then(function(e){if(e.errors)for(var r=0;r<e.errors.length;r++)(0,_errorModal2.default)(e.errors[r].message);return e.data})}function responseToJson(e){return e.json()}var _errorModal=require("./errorModal"),_errorModal2=_interopRequireDefault(_errorModal),_config=require("../../../../../../../../../resources/assets/react-app/config"),_config2=_interopRequireDefault(_config),Http={get:function(e,r,t,n){return DMFetch(e,"GET",r,t,n)},post:function(e,r,t,n){return DMFetch(e,"POST",r,t,n)},put:function(e,r,t,n){return DMFetch(e,"PUT",r,t,n)},delete:function(e,r,t,n){return DMFetch(e,"DELETE",r,t,n)}};module.exports=Http;<|endoftext|>


<commit_before>/* ©Copyright Utrecht University (Department of Information and Computing Sciences) */

var Validator;

(function()
{
    "use strict";

    Validator =
    {
        validate: validate,
        show: show,
        testCycle: testCycle,
        testDuplicateConnection: testDuplicateConnection
    };

    $(document).ready(function()
    {
        // Event handlers.
        $("#validation").on('click', function()
        {
            var errors = validate();
            show(errors);
        });
    });

    function validate()
    {
        var validationReport = []; // an array of objects containing the errors found
        //var unmarkedEndNodes = []; // nodes without children not marked as end node

        // First save the latest changes.
        Main.applyChanges(Main.selectedElement);
        // Checks whether the scenario has a name
        if(Metadata.metaObject.name === null || Metadata.metaObject.name === "")
        {
            validationReport.push(
            {
                message: i18next.t('validator:no_name'),
                level: 'warning',
                jumpToFunction: function() {
                    Metadata.metadataDialog();
                    $('#scenarioName').focus();
                }
            });
        }

        if (Object.keys(Main.trees).length === 0)
        {
            validationReport.push(
            {
                message: i18next.t('validator:empty_scenario'),
                level: 'error',
                jumpToFunction: function() { }
            });
        }

        var numberOfTreesOnLevels = getNumberOfTreesOnLevels(Main.trees);
        var highestLevel = numberOfTreesOnLevels.length - 1; // note that trees with a high level are low on the editor screen
        var hasValidEnd = false; // if the highest level has an end node this becomes true
        var highestLevelHasEnd = false;

        $.each(Main.trees, function(id, tree)
        {
            // Check whether there is exactly one node without parents.
            var startNodeIDs = Main.getStartNodeIDs(tree);

            if (startNodeIDs.length === 0)
            {
                validationReport.push(
                {
                    message: i18next.t('validator:empty_subject', { postProcess: 'sprintf', sprintf: [tree.subject] }),
                    level: 'error',
                    jumpToFunction: function() { Zoom.zoomIn(tree); }
                });
            }
            else
            {
                $.each(startNodeIDs, function(index, startNodeID)
                {
                    // the tree on the first level can start with anything, but the trees following can only start with player nodes
                    if(tree.level !== 0 && Main.nodes[startNodeID].type !== Main.playerType)
                    {
                        validationReport.push(
                        {
                            message: i18next.t('validator:subject_start_type_error',
                                { subject: tree.subject, type: i18next.t('common:' + Main.nodes[startNodeID].type) }),
                            level: 'error',
                            jumpToFunction: function() { Zoom.zoomIn(tree); }
                        });
                    }
                });
            }

            // gets all nodes marked as end node
            var markedEnds = findAllMarkedEnds(tree);

            $.each(markedEnds, function(index, nodeID)
            {
                var connections = tree.plumbInstance.getConnections({ source: nodeID });
                if (connections.length > 0)
                {
                    validationReport.push(
                    {
                        message: i18next.t('validator:end_with_outgoing_connections', { postProcess: 'sprintf', sprintf: [tree.subject] }),
                        level: 'error',
                        jumpToFunction: function() {
                            Zoom.zoomIn(tree);
                            Main.selectNode(nodeID);
                        }
                    });
                }
                else if (tree.level === highestLevel)
                {
                    hasValidEnd = true;
                }
            });

            if (tree.level === highestLevel)
            {
                // gets all nodes without children from the tree
                var deadEnds = findAllDeadEnds(tree);

                if (numberOfTreesOnLevels[tree.level] === 1)
                {
                    $.each(deadEnds, function(index, nodeID)
                    {
                        if (markedEnds.indexOf(nodeID) === -1)
                        { // node is a dead end, but not marked as end node
                            validationReport.push(
                            {
                                message: i18next.t('validator:unmarked_end', { postProcess: 'sprintf', sprintf: [tree.subject] }),
                                level: 'error',
                                jumpToFunction: function() {
                                    Zoom.zoomIn(tree);
                                    Main.selectNode(nodeID);
                                }
                            });
                        }
                        else
                        {
                            highestLevelHasEnd = true;
                        }
                    });
                }
                else
                {
                    $.each(deadEnds, function(index, nodeID)
                    {
                        if (markedEnds.indexOf(nodeID) !== -1)
                        {
                            highestLevelHasEnd = true;
                        }
                    });
                }
            }

            if (tree.subject === "")
            {
                validationReport.push(
                {
                    message: i18next.t('validator:unnamed_subject'),
                    level: 'info',
                    jumpToFunction: function() { Main.selectTree(tree.id); }
                });
            }
        });

        if(numberOfTreesOnLevels[0] !== 1)
        {
            validationReport.push(
            {
                message: i18next.t('validator:first_layer_count'),
                level: 'error',
                jumpToFunction: function() { }
            });
        }

        if(!highestLevelHasEnd)
        { // no single iteration errors, but there is no valid end
            validationReport.push(
            {
                message: i18next.t('validator:no_ending'),
                level: 'error',
                jumpToFunction: function() { }
            });
        }

        if(!hasValidEnd)
        { // no single iteration errors, but there is no valid end
            validationReport.push(
            {
                message: i18next.t('validator:no_valid_ending'),
                level: 'error',
                jumpToFunction: function() { }
            });
        }

        return validationReport; // add highest level unmarked end nodes and return
    }

    function findAllDeadEnds(tree)
    { // finds all nodes without children
        var result = [];

        $.each(tree.nodes, function(index, nodeID) {
            if(!nodeID) {
                return true;
            }

            var connections = tree.plumbInstance.getConnections({ source: nodeID });
            if(connections.length === 0) {
                result.push(nodeID);
            }
        });

        return result;
    }

    function findAllMarkedEnds(tree)
    { // find all nodes that are marked as end
        var result = [];
        $.each(tree.nodes, function(index, nodeID) {
            if(!nodeID) {
                return true;
            }

            if(Main.nodes[nodeID].endNode) {
                result.push(nodeID);
            }
        });

        return result;
    }

    function getNumberOfTreesOnLevels(trees)
    {
        var treesOnLevels = [];
        $.each(trees, function(index, tree)
        {
            if (typeof treesOnLevels[tree.level] == 'undefined')
                treesOnLevels[tree.level] = 0;

            treesOnLevels[tree.level]++;
        });

        return treesOnLevels;
    }

    function show(errors)
    {
        var hasErrors = false;
        $.each(errors, function(index, value)
        {
            hasErrors = hasErrors || value.level === 'error';
        });

        $('#validationReport').empty();
        if (!hasErrors)
        {
            $('#validationReport').append($('<p>').addClass('no-problems').text(i18next.t('validator:no_problems')));
        }
        else
        {
            var table = $('<table>');
            $.each(errors, function(index, e)
            {
                var row = $('<tr>').addClass('level-' + e.level);
                var error = $('<td>').text(i18next.t('validator:' + e.level));
                var message = $('<td>').append($('<span>').text(e.message).on('click', e.jumpToFunction).css('cursor', 'pointer'));
                row.append(error).append(message);
                table.append(row);
            });
            $('#validationReport').append(table);
        }
        $('#draftScreen').hide();
        $('#validationReport').show();
        $('#tabDock').show();
        $("#main").focus();
    }

    // Checks if there is a cycle in the graph.
    function testCycle(currentNode, nodeToFind)
    {
        for(var nodeID in Main.nodes)
            Main.nodes[nodeID].visited = false;

        return testCycleDFS(currentNode, nodeToFind);
    }

    function testCycleDFS(currentNode, nodeToFind)
    {
        if (currentNode === nodeToFind)
            return true;

        Main.nodes[currentNode].visited = true;
        var plumbInstance = Main.getPlumbInstanceByNodeID(currentNode);
        var connections = plumbInstance.getConnections({source: currentNode});
        for (var i = 0; i < connections.length; i++)
            if(!Main.nodes[connections[i].targetId].visited && testCycleDFS(connections[i].targetId, nodeToFind))
                return true;

        return false;
    }

    // Checks if a connection between the node already has been made.
    function testDuplicateConnection(sourceId, targetId)
    {
        var plumbInstance = Main.getPlumbInstanceByNodeID(sourceId);
        return plumbInstance.getConnections({ source: sourceId, target: targetId }).length > 0;
    }

})();
<commit_msg>Improved and fixed validation reporting<commit_after>/* ©Copyright Utrecht University (Department of Information and Computing Sciences) */

var Validator;

(function()
{
    "use strict";

    Validator =
    {
        validate: validate,
        show: show,
        testCycle: testCycle,
        testDuplicateConnection: testDuplicateConnection
    };

    $(document).ready(function()
    {
        // Event handlers.
        $("#validation").on('click', function()
        {
            var errors = validate();
            show(errors);
        });
    });

    function validate()
    {
        var validationReport = []; // an array of objects containing the errors found
        //var unmarkedEndNodes = []; // nodes without children not marked as end node

        // First save the latest changes.
        Main.applyChanges(Main.selectedElement);
        // Checks whether the scenario has a name
        if(Metadata.metaObject.name === null || Metadata.metaObject.name === "")
        {
            validationReport.push(
            {
                message: i18next.t('validator:no_name'),
                level: 'warning',
                jumpToFunction: function() {
                    Metadata.metadataDialog();
                    $('#scenarioName').focus();
                }
            });
        }

        if (Object.keys(Main.trees).length === 0)
        {
            validationReport.push(
            {
                message: i18next.t('validator:empty_scenario'),
                level: 'error',
                jumpToFunction: function() { }
            });
        }

        var numberOfTreesOnLevels = getNumberOfTreesOnLevels(Main.trees);
        var highestLevel = numberOfTreesOnLevels.length - 1; // note that trees with a high level are low on the editor screen
        var hasValidEnd = false; // if the highest level has an end node this becomes true
        var highestLevelHasEnd = false;

        $.each(Main.trees, function(id, tree)
        {
            // Check whether there is exactly one node without parents.
            var startNodeIDs = Main.getStartNodeIDs(tree);

            if (startNodeIDs.length === 0)
            {
                validationReport.push(
                {
                    message: i18next.t('validator:empty_subject', { postProcess: 'sprintf', sprintf: [tree.subject] }),
                    level: 'error',
                    jumpToFunction: function() { Zoom.zoomIn(tree); }
                });
            }
            else
            {
                $.each(startNodeIDs, function(index, startNodeID)
                {
                    // the tree on the first level can start with anything, but the trees following can only start with player nodes
                    if(tree.level !== 0 && Main.nodes[startNodeID].type !== Main.playerType)
                    {
                        validationReport.push(
                        {
                            message: i18next.t('validator:subject_start_type_error',
                                { subject: tree.subject, type: i18next.t('common:' + Main.nodes[startNodeID].type) }),
                            level: 'error',
                            jumpToFunction: function()
                            {
                                Zoom.zoomIn(tree);
                                Main.selectNode(startNodeID);
                            }
                        });
                    }
                });
            }

            // gets all nodes marked as end node
            var markedEnds = findAllMarkedEnds(tree);

            $.each(markedEnds, function(index, nodeID)
            {
                var connections = tree.plumbInstance.getConnections({ source: nodeID });
                if (connections.length > 0)
                {
                    validationReport.push(
                    {
                        message: i18next.t('validator:end_with_outgoing_connections', { postProcess: 'sprintf', sprintf: [tree.subject] }),
                        level: 'error',
                        jumpToFunction: function() {
                            Zoom.zoomIn(tree);
                            Main.selectNode(nodeID);
                        }
                    });
                }
                else if (tree.level === highestLevel)
                {
                    hasValidEnd = true;
                }
            });

            if (tree.level === highestLevel)
            {
                // gets all nodes without children from the tree
                var deadEnds = findAllDeadEnds(tree);

                if (numberOfTreesOnLevels[tree.level] === 1)
                {
                    $.each(deadEnds, function(index, nodeID)
                    {
                        if (markedEnds.indexOf(nodeID) === -1)
                        { // node is a dead end, but not marked as end node
                            validationReport.push(
                            {
                                message: i18next.t('validator:unmarked_end', { postProcess: 'sprintf', sprintf: [tree.subject] }),
                                level: 'error',
                                jumpToFunction: function() {
                                    Zoom.zoomIn(tree);
                                    Main.selectNode(nodeID);
                                }
                            });
                        }
                        else
                        {
                            highestLevelHasEnd = true;
                        }
                    });
                }
                else
                {
                    $.each(deadEnds, function(index, nodeID)
                    {
                        if (markedEnds.indexOf(nodeID) !== -1)
                        {
                            highestLevelHasEnd = true;
                        }
                    });
                }
            }

            if (tree.subject === "")
            {
                validationReport.push(
                {
                    message: i18next.t('validator:unnamed_subject'),
                    level: 'info',
                    jumpToFunction: function() { Main.selectElement(tree.id); }
                });
            }
        });

        if(numberOfTreesOnLevels[0] !== 1)
        {
            validationReport.push(
            {
                message: i18next.t('validator:first_layer_count'),
                level: 'error',
                jumpToFunction: function() { }
            });
        }

        if(!highestLevelHasEnd)
        { // no single iteration errors, but there is no valid end
            validationReport.push(
            {
                message: i18next.t('validator:no_ending'),
                level: 'error',
                jumpToFunction: function() { }
            });
        }

        if(!hasValidEnd)
        { // no single iteration errors, but there is no valid end
            validationReport.push(
            {
                message: i18next.t('validator:no_valid_ending'),
                level: 'error',
                jumpToFunction: function() { }
            });
        }

        return validationReport; // add highest level unmarked end nodes and return
    }

    function findAllDeadEnds(tree)
    { // finds all nodes without children
        var result = [];

        $.each(tree.nodes, function(index, nodeID) {
            if(!nodeID) {
                return true;
            }

            var connections = tree.plumbInstance.getConnections({ source: nodeID });
            if(connections.length === 0) {
                result.push(nodeID);
            }
        });

        return result;
    }

    function findAllMarkedEnds(tree)
    { // find all nodes that are marked as end
        var result = [];
        $.each(tree.nodes, function(index, nodeID) {
            if(!nodeID) {
                return true;
            }

            if(Main.nodes[nodeID].endNode) {
                result.push(nodeID);
            }
        });

        return result;
    }

    function getNumberOfTreesOnLevels(trees)
    {
        var treesOnLevels = [];
        $.each(trees, function(index, tree)
        {
            if (typeof treesOnLevels[tree.level] == 'undefined')
                treesOnLevels[tree.level] = 0;

            treesOnLevels[tree.level]++;
        });

        return treesOnLevels;
    }

    function show(errors)
    {
        var hasErrors = false;
        var hasWarningsOrInfo = false;
        $.each(errors, function(index, value)
        {
            hasErrors = hasErrors || value.level === 'error';
            hasWarningsOrInfo = hasWarningsOrInfo || value.level === 'warning' || value.level === 'info';
        });

        $('#validationReport').empty();
        if (!hasErrors && !hasWarningsOrInfo)
        {
            $('#validationReport').append($('<p>').addClass('no-problems').text(i18next.t('validator:no_problems')));
        }
        else
        {
            var table = $('<table>');
            $.each(errors, function(index, e)
            {
                var row = $('<tr>').addClass('level-' + e.level);
                var error = $('<td>').text(i18next.t('validator:' + e.level));
                var message = $('<td>').append($('<span>').text(e.message).on('click', e.jumpToFunction).css('cursor', 'pointer'));
                row.append(error).append(message);
                table.append(row);
            });
            $('#validationReport').append(table);
        }
        $('#draftScreen').hide();
        $('#validationReport').show();
        $('#tabDock').show();
        $("#main").focus();
    }

    // Checks if there is a cycle in the graph.
    function testCycle(currentNode, nodeToFind)
    {
        for(var nodeID in Main.nodes)
            Main.nodes[nodeID].visited = false;

        return testCycleDFS(currentNode, nodeToFind);
    }

    function testCycleDFS(currentNode, nodeToFind)
    {
        if (currentNode === nodeToFind)
            return true;

        Main.nodes[currentNode].visited = true;
        var plumbInstance = Main.getPlumbInstanceByNodeID(currentNode);
        var connections = plumbInstance.getConnections({source: currentNode});
        for (var i = 0; i < connections.length; i++)
            if(!Main.nodes[connections[i].targetId].visited && testCycleDFS(connections[i].targetId, nodeToFind))
                return true;

        return false;
    }

    // Checks if a connection between the node already has been made.
    function testDuplicateConnection(sourceId, targetId)
    {
        var plumbInstance = Main.getPlumbInstanceByNodeID(sourceId);
        return plumbInstance.getConnections({ source: sourceId, target: targetId }).length > 0;
    }

})();
<|endoftext|>


<commit_before>module.exports = UMDFormatter;

var AMDFormatter = require("./amd");
var util         = require("../../util");
var t            = require("../../types");
var _            = require("lodash");

function UMDFormatter(file) {
  this.file = file;
  this.ids  = {};
}

util.inherits(UMDFormatter, AMDFormatter);

UMDFormatter.prototype.transform = function (ast) {
  var program = ast.program;
  var body    = program.body;

  // build an array of module names

  var names = [];
  _.each(this.ids, function (id, name) {
    names.push(t.literal(name));
  });

  // factory

  var ids  = _.values(this.ids);
  var args = [t.identifier("exports")].concat(ids);

  var factory = t.functionExpression(null, args, t.blockStatement(body));

  // runner

  var moduleName = this.getModuleName();

  var runner = util.template("umd-runner-body", {
    AMD_ARGUMENTS: [t.literal(moduleName), t.arrayExpression([t.literal("exports")].concat(names))],

    COMMON_ARGUMENTS: names.map(function (name) {
      return t.callExpression(t.identifier("require"), [name]);
    })
  });

  //

  var call = t.callExpression(runner, [factory]);
  program.body = [t.expressionStatement(call)];
};
<commit_msg>make umd module formatter inherit amd constructor<commit_after>module.exports = UMDFormatter;

var AMDFormatter = require("./amd");
var util         = require("../../util");
var t            = require("../../types");
var _            = require("lodash");

function UMDFormatter() {
  AMDFormatter.apply(this, arguments);
}

util.inherits(UMDFormatter, AMDFormatter);

UMDFormatter.prototype.transform = function (ast) {
  var program = ast.program;
  var body    = program.body;

  // build an array of module names

  var names = [];
  _.each(this.ids, function (id, name) {
    names.push(t.literal(name));
  });

  // factory

  var ids  = _.values(this.ids);
  var args = [t.identifier("exports")].concat(ids);

  var factory = t.functionExpression(null, args, t.blockStatement(body));

  // runner

  var moduleName = this.getModuleName();

  var runner = util.template("umd-runner-body", {
    AMD_ARGUMENTS: [t.literal(moduleName), t.arrayExpression([t.literal("exports")].concat(names))],

    COMMON_ARGUMENTS: names.map(function (name) {
      return t.callExpression(t.identifier("require"), [name]);
    })
  });

  //

  var call = t.callExpression(runner, [factory]);
  program.body = [t.expressionStatement(call)];
};
<|endoftext|>


<commit_before>/*global define*/
define([
        '../Core/createGuid',
        '../Core/DeveloperError',
        './CzmlDefaults'
       ], function(
        createGuid,
        DeveloperError,
        CzmlDefaults) {
    "use strict";

    function processCzmlPacket(packet, dynamicObjectCollection, updatedObjects, updatedObjectsHash, updaterFunctions, sourceUri) {
        var objectId = packet.id;
        if (typeof objectId === 'undefined') {
            objectId = createGuid();
        }

        if (packet['delete']) {
            dynamicObjectCollection.removeObject(packet.id);
        } else {
            var object = dynamicObjectCollection.getOrCreateObject(objectId);
            for ( var i = updaterFunctions.length - 1; i > -1; i--) {
                if (updaterFunctions[i](object, packet, dynamicObjectCollection, sourceUri) && typeof updatedObjectsHash[objectId] === 'undefined') {
                    updatedObjectsHash[objectId] = true;
                    updatedObjects.push(object);
                }
            }
        }
    }

    /**
     * Processes the provided CZML, creating or updating DynamicObject instances for each
     * corresponding CZML identifier.
     * @exports processCzml
     *
     * @param {Object} czml The parsed CZML object to be processed.
     * @param {DynamicObjectCollection} dynamicObjectCollection The collection to create or updated objects within.
     * @param {String} [sourceUri] The uri of the file where the CZML originated from.  If provided, relative uri look-ups will use this as their base.
     * @param {Array} [updaterFunctions=CzmlDefaults.updaters] The array of updated functions to use for processing.  If left undefined, all standard CZML data is processed.
     *
     * @exception {DeveloperError} czml is required.
     * @exception {DeveloperError} dynamicObjectCollection is required.
     *
     * @returns An array containing all DynamicObject instances that were created or updated.
     *
     * @example
     * var url = 'http://someUrl.com/myCzmlFile.czml';
     * var dynamicObjectCollection = new DynamicObjectCollection();
     * loadJson(url).then(function(czml) {
     *     processCzml(czml, dynamicObjectCollection, url);
     * });
     */
    var processCzml = function(czml, dynamicObjectCollection, sourceUri, updaterFunctions) {
        if (typeof czml === 'undefined') {
            throw new DeveloperError('czml is required.');
        }
        if (typeof dynamicObjectCollection === 'undefined') {
            throw new DeveloperError('dynamicObjectCollection is required.');
        }

        var updatedObjects = [];
        var updatedObjectsHash = {};
        updaterFunctions = typeof updaterFunctions !== 'undefined' ? updaterFunctions : CzmlDefaults.updaters;

        if (Array.isArray(czml)) {
            for ( var i = 0, len = czml.length; i < len; i++) {
                processCzmlPacket(czml[i], dynamicObjectCollection, updatedObjects, updatedObjectsHash, updaterFunctions, sourceUri);
            }
        } else {
            processCzmlPacket(czml, dynamicObjectCollection, updatedObjects, updatedObjectsHash, updaterFunctions, sourceUri);
        }

        if (updatedObjects.length > 0) {
            dynamicObjectCollection.objectPropertiesChanged.raiseEvent(dynamicObjectCollection, updatedObjects);
        }

        return updatedObjects;
    };

    return processCzml;
});
<commit_msg>Changes after review.<commit_after>/*global define*/
define([
        '../Core/createGuid',
        '../Core/DeveloperError',
        './CzmlDefaults'
       ], function(
        createGuid,
        DeveloperError,
        CzmlDefaults) {
    "use strict";

    function processCzmlPacket(packet, dynamicObjectCollection, updatedObjects, updatedObjectsHash, updaterFunctions, sourceUri) {
        var objectId = packet.id;
        if (typeof objectId === 'undefined') {
            objectId = createGuid();
        }

        if (packet['delete'] === true) {
            dynamicObjectCollection.removeObject(packet.id);
        } else {
            var object = dynamicObjectCollection.getOrCreateObject(objectId);
            for ( var i = updaterFunctions.length - 1; i > -1; i--) {
                if (updaterFunctions[i](object, packet, dynamicObjectCollection, sourceUri) && typeof updatedObjectsHash[objectId] === 'undefined') {
                    updatedObjectsHash[objectId] = true;
                    updatedObjects.push(object);
                }
            }
        }
    }

    /**
     * Processes the provided CZML, creating or updating DynamicObject instances for each
     * corresponding CZML identifier.
     * @exports processCzml
     *
     * @param {Object} czml The parsed CZML object to be processed.
     * @param {DynamicObjectCollection} dynamicObjectCollection The collection to create or updated objects within.
     * @param {String} [sourceUri] The uri of the file where the CZML originated from.  If provided, relative uri look-ups will use this as their base.
     * @param {Array} [updaterFunctions=CzmlDefaults.updaters] The array of updated functions to use for processing.  If left undefined, all standard CZML data is processed.
     *
     * @exception {DeveloperError} czml is required.
     * @exception {DeveloperError} dynamicObjectCollection is required.
     *
     * @returns An array containing all DynamicObject instances that were created or updated.
     *
     * @example
     * var url = 'http://someUrl.com/myCzmlFile.czml';
     * var dynamicObjectCollection = new DynamicObjectCollection();
     * loadJson(url).then(function(czml) {
     *     processCzml(czml, dynamicObjectCollection, url);
     * });
     */
    var processCzml = function(czml, dynamicObjectCollection, sourceUri, updaterFunctions) {
        if (typeof czml === 'undefined') {
            throw new DeveloperError('czml is required.');
        }
        if (typeof dynamicObjectCollection === 'undefined') {
            throw new DeveloperError('dynamicObjectCollection is required.');
        }

        var updatedObjects = [];
        var updatedObjectsHash = {};
        updaterFunctions = typeof updaterFunctions !== 'undefined' ? updaterFunctions : CzmlDefaults.updaters;

        if (Array.isArray(czml)) {
            for ( var i = 0, len = czml.length; i < len; i++) {
                processCzmlPacket(czml[i], dynamicObjectCollection, updatedObjects, updatedObjectsHash, updaterFunctions, sourceUri);
            }
        } else {
            processCzmlPacket(czml, dynamicObjectCollection, updatedObjects, updatedObjectsHash, updaterFunctions, sourceUri);
        }

        if (updatedObjects.length > 0) {
            dynamicObjectCollection.objectPropertiesChanged.raiseEvent(dynamicObjectCollection, updatedObjects);
        }

        return updatedObjects;
    };

    return processCzml;
});
<|endoftext|>


<commit_before>import {divideURL} from '../utils/utils';
import CatalogueFactory from '../catalogue-factory/CatalogueDataObjectFactory';
import persistenceManager from '../persistence/PersistenceManager';

class RuntimeCatalogue {

    constructor(runtimeFactory) {
        if (!runtimeFactory) throw Error('The catalogue needs the runtimeFactory');

        let _this = this;
        _this._factory = new CatalogueFactory(false, undefined);
        _this.httpRequest = runtimeFactory.createHttpRequest();
    }

    /**
     * Get a Catalogue Data Object (Descriptor) from a URL, and construct it using the provided function
     * @param {String} descriptorURL - e.g. mydomain.com/.well-known/hyperty/MyHyperty
     * @param {function} createFunc - e.g. _createHyperty
     * @returns {Promise}
     */
    getDescriptor(descriptorURL, createFunc) {
        let _this = this;
        // console.log("getDescriptor", descriptorURL);

        return new Promise(function (resolve, reject) {

            _this.httpRequest.get(descriptorURL + "/version").then(function (result) {
                if (persistenceManager.getVersion(descriptorURL) >= result) {
                    // return saved version
                    console.log("returning saved version:", persistenceManager.get(descriptorURL));
                    resolve(createFunc(_this, persistenceManager.get(descriptorURL)))
                } else {
                    // request the json
                    _this.httpRequest.get(descriptorURL).then(function (result) {
                        result = JSON.parse(result);

                        if (result["ERROR"]) {
                            // TODO handle error properly
                            reject(result);
                        } else {
                            // console.log("creating descriptor based on: ", result);
                            let descriptor = createFunc(_this, result);
                            persistenceManager.set(descriptorURL, descriptor.version, result);
                            // console.log("created descriptor object:", hyperty);
                            resolve(descriptor);
                        }
                    });
                }
            });
        });
    }

    /**
     * Get HypertyDescriptor
     * @param hypertyURL - e.g. mydomain.com/.well-known/hyperty/MyHyperty
     * @returns {Promise}
     */
    getHypertyDescriptor(hypertyURL) {
        let _this = this;
        return _this.getDescriptor(hypertyURL, _this._createHyperty)
    }

    /**
     * Get StubDescriptor
     * @param stubURL - e.g. mydomain.com/.well-known/protostub/MyProtostub
     * @returns {Promise}
     */
    getStubDescriptor(stubURL) {
        let _this = this;
        return _this.getDescriptor(runtimeURL, _this._createStub)
    }

    /**
     * Get RuntimeDescriptor
     * @param runtimeURL - e.g. mydomain.com/.well-known/runtime/MyRuntime
     * @returns {Promise}
     */
    getRuntimeDescriptor(runtimeURL) {
        let _this = this;
        return _this.getDescriptor(runtimeURL, _this._createRuntimeDescriptor)
    }

    /**
     * Get DataSchemaDescriptor
     * @param dataSchemaURL - e.g. mydomain.com/.well-known/dataschema/MyDataSchema
     * @returns {Promise}
     */
    getDataSchemaDescriptor(dataSchemaURL) {
        let _this = this;
        return _this.getDescriptor(runtimeURL, _this._createDataSchema)
    }

    /**
     * Get IDPProxyDescriptor
     * @param idpProxyURL - e.g. mydomain.com/.well-known/idp-proxy/MyProxy
     * @returns {Promise}
     */
    getIdpProxyDescriptor(idpProxyURL) {
        let _this = this;
        return _this.getDescriptor(runtimeURL, _this._createIdpProxy)
    }

    /**
     * Create HypertyDescriptor based on raw object that contains its attributes
     * @param _this
     * @param rawHyperty
     * @returns {HypertyDescriptor}
     */
    _createHyperty(_this, rawHyperty) {
        // create the descriptor
        let hyperty = _this._factory.createHypertyDescriptorObject(
            rawHyperty["cguid"],
            rawHyperty["version"],
            rawHyperty["objectName"],
            rawHyperty["description"],
            rawHyperty["language"],
            rawHyperty["sourcePackageURL"],
            rawHyperty["type"] || rawHyperty["hypertyType"],
            rawHyperty["dataObjects"]
        );

        // optional fields
        hyperty.configuration = rawHyperty["configuration"];
        hyperty.constraints = rawHyperty["constraints"];
        hyperty.messageSchema = rawHyperty["messageSchema"];
        hyperty.policies = rawHyperty["policies"];
        hyperty.signature = rawHyperty["signature"];

        // parse and attach sourcePackage
        let sourcePackage = rawHyperty["sourcePackage"];
        if (sourcePackage) {
            // console.log("hyperty has sourcePackage:", sourcePackage);
            hyperty.sourcePackage = _this._createSourcePackage(_this, sourcePackage);
        }

        return hyperty;
    }

    /**
     * Create ProtocolStubDescriptor based on raw object that contains its attributes
     * @param _this
     * @param rawStub
     * @returns {ProtocolStubDescriptor}
     */
    _createStub(_this, rawStub) {
        // console.log("creating stub descriptor based on: ", rawStub);

        // create the descriptor
        let stub = _this._factory.createProtoStubDescriptorObject(
            rawStub["cguid"],
            rawStub["version"],
            rawStub["objectName"],
            rawStub["description"],
            rawStub["language"],
            rawStub["sourcePackageURL"],
            rawStub["messageSchemas"],
            rawStub["configuration"],
            rawStub["constraints"]
        );

        // optional fields
        stub.signature = rawStub["signature"];

        // parse and attach the sourcePackage
        let sourcePackage = rawStub["sourcePackage"];
        if (sourcePackage) {
            sourcePackage = _this._createSourcePackage(_this, sourcePackage);
            stub.sourcePackage = sourcePackage;
        }

        return stub;
    }

    /**
     * Create HypertyRuntimeDescriptor based on raw object that contains its attributes
     * @param _this
     * @param rawRuntime
     * @returns {HypertyRuntimeDescriptor}
     */
    _createRuntimeDescriptor(_this, rawRuntime) {
        // parse capabilities first
        try {
            rawRuntime["hypertyCapabilities"] = JSON.parse(rawRuntime["hypertyCapabilities"]);
            rawRuntime["protocolCapabilities"] = JSON.parse(rawRuntime["protocolCapabilities"]);
        } catch (e) {
            // already json object
        }
        console.log("creating runtime descriptor based on: ", rawRuntime);

        // create the descriptor
        let runtime = _this._factory.createHypertyRuntimeDescriptorObject(
            rawRuntime["cguid"],
            rawRuntime["version"],
            rawRuntime["objectName"],
            rawRuntime["description"],
            rawRuntime["language"],
            rawRuntime["sourcePackageURL"],
            rawRuntime["type"] || rawRuntime["runtimeType"],
            rawRuntime["hypertyCapabilities"],
            rawRuntime["protocolCapabilities"]
        );

        // optional fields
        runtime.signature = rawRuntime["signature"];

        // parse and attach sourcePackage
        let sourcePackage = rawRuntime["sourcePackage"];
        if (sourcePackage) {
            // console.log("runtime has sourcePackage:", sourcePackage);
            runtime.sourcePackage = _this._createSourcePackage(_this, sourcePackage);
        }
        return runtime;
    }

    /**
     * Create DataObjectSchema based on raw object that contains its attributes
     * @param _this
     * @param rawSchema
     * @returns {DataObjectSchema}
     */
    _createDataSchema(_this, rawSchema) {
        console.log("creating dataSchema based on: ", rawSchema);

        // FIXME: accessControlPolicy field not needed?
        // create the descriptor
        let dataSchema = _this._factory.createDataObjectSchema(
            rawSchema["cguid"],
            rawSchema["version"],
            rawSchema["objectName"],
            rawSchema["description"],
            rawSchema["language"],
            rawSchema["sourcePackageURL"]
        );

        // optional fields
        dataSchema.signature = rawSchema["signature"];

        // parse and attach sourcePackage
        let sourcePackage = rawSchema["sourcePackage"];
        if (sourcePackage) {
            // console.log("dataSchema has sourcePackage:", sourcePackage);
            dataSchema.sourcePackage = _this._createSourcePackage(_this, sourcePackage);
        }

        console.log("created dataSchema descriptor object:", dataSchema);
        return dataSchema;
    }

    /**
     * Create ProtocolStubDescriptor based on raw object that contains its attributes
     * @param _this
     * @param rawProxy
     * @returns {ProtocolStubDescriptor}
     */
    _createIdpProxy(_this, rawProxy) {
        // console.log("creating idpproxy descriptor based on: ", rawProxy);

        // create the descriptor
        let idpproxy = _this._factory.createProtoStubDescriptorObject(
            rawProxy["cguid"],
            rawProxy["version"],
            rawProxy["objectName"],
            rawProxy["description"],
            rawProxy["language"],
            rawProxy["sourcePackageURL"],
            rawProxy["messageSchemas"],
            rawProxy["configuration"],
            rawProxy["constraints"]
        );

        // optional fields
        idpproxy.signature = rawProxy["signature"];

        // parse and attach the sourcePackage
        let sourcePackage = rawProxy["sourcePackage"];
        if (sourcePackage) {
            sourcePackage = _this._createSourcePackage(_this, sourcePackage);
            idpproxy.sourcePackage = sourcePackage;
        }

        return idpproxy;
    }

    _createSourcePackage(_this, sp) {
        //console.log("creating sourcePackage. factory:", factory, ", raw package:", sp);
        try {
            sp = JSON.parse(sp);
        } catch (e) {
            console.log("parsing sourcePackage failed. already parsed? -> ", sp);
        }

        // check encoding
        if (sp["encoding"] === "base64") {
            sp["sourceCode"] = atob(sp["sourceCode"]);
        }

        let sourcePackage = _this.factory.createSourcePackage(sp["sourceCodeClassname"], sp["sourceCode"]);
        if (sp["encoding"])
            sourcePackage.encoding = sp["encoding"];

        if (sp["signature"])
            sourcePackage.signature = sp["signature"];

        return sourcePackage;
    }

    /**
     * Get source Package from a URL
     * @param sourcePackageURL - e.g. mydomain.com/.well-known/hyperty/MyHyperty/sourcePackage
     * @returns {Promise}
     */
    getSourcePackageFromURL(sourcePackageURL) {
        let _this = this;

        //console.log("getting sourcePackage from:", sourcePackageURL);

        return new Promise(function (resolve, reject) {
            _this.httpRequest.get(sourcePackageURL).then(function (result) {
                //console.log("got raw sourcePackage:", result);
                if (result["ERROR"]) {
                    // TODO handle error properly
                    reject(result);
                } else {
                    result = JSON.parse(result);
                    let sourcePackage = _this._createSourcePackage(_this, result);
                    resolve(sourcePackage);
                }
            }).catch(function (reason) {
                reject(reason);
            });

        });

    }

    /**
     * Returns the sourceCode of a given descriptor
     * @param {CatalogueDataObject} descriptor - Catalogue Object that was retrieved using e.g. getHypertyDescriptor()
     * @returns {Promise}
     */
    getSourceCodeFromDescriptor(descriptor) {
        let _this = this;
        return new Promise(function (resolve, reject) {
            if (descriptor.sourcePackage) {
                //console.log("descriptor has sourcePackage");
                //console.log("returning sourceCode:", descriptor.sourcePackage.sourceCode);
                resolve(descriptor.sourcePackage.sourceCode);
            } else {
                if (persistenceManager.getVersion(descriptor.sourcePackageURL + "/sourceCode") >= descriptor.version) {
                    console.log("returning cached version from persistence manager");
                    resolve(persistenceManager.get(descriptor.sourcePackageURL + "/sourceCode"));
                } else {
                    _this.httpRequest.get(descriptor.sourcePackageURL + "/sourceCode").then(function (sourceCode) {
                        if (sourceCode["ERROR"]) {
                            // TODO handle error properly
                            reject(sourceCode);
                        } else {
                            persistenceManager.set(descriptor.sourcePackageURL + "/sourceCode", descriptor.version, sourceCode);
                            resolve(sourceCode);
                        }
                    });
                }
            }
        });
    }

    set runtimeURL(runtimeURL) {
        let _this = this;
        _this._runtimeURL = runtimeURL;
    }

    get runtimeURL() {
        let _this = this;
        return _this._runtimeURL;
    }

    deleteFromPM(url) {
        persistenceManager.delete(url);
    }

}

export default RuntimeCatalogue;
<commit_msg>added warning to getSourcePackageURL of RuntimeCatalogue<commit_after>import {divideURL} from '../utils/utils';
import CatalogueFactory from '../catalogue-factory/CatalogueDataObjectFactory';
import persistenceManager from '../persistence/PersistenceManager';

class RuntimeCatalogue {

    constructor(runtimeFactory) {
        if (!runtimeFactory) throw Error('The catalogue needs the runtimeFactory');

        let _this = this;
        _this._factory = new CatalogueFactory(false, undefined);
        _this.httpRequest = runtimeFactory.createHttpRequest();
    }

    /**
     * Get a Catalogue Data Object (Descriptor) from a URL, and construct it using the provided function
     * @param {String} descriptorURL - e.g. mydomain.com/.well-known/hyperty/MyHyperty
     * @param {function} createFunc - e.g. _createHyperty
     * @returns {Promise}
     */
    getDescriptor(descriptorURL, createFunc) {
        let _this = this;
        // console.log("getDescriptor", descriptorURL);

        return new Promise(function (resolve, reject) {

            _this.httpRequest.get(descriptorURL + "/version").then(function (result) {
                if (persistenceManager.getVersion(descriptorURL) >= result) {
                    // return saved version
                    console.log("returning saved version:", persistenceManager.get(descriptorURL));
                    resolve(createFunc(_this, persistenceManager.get(descriptorURL)))
                } else {
                    // request the json
                    _this.httpRequest.get(descriptorURL).then(function (result) {
                        result = JSON.parse(result);

                        if (result["ERROR"]) {
                            // TODO handle error properly
                            reject(result);
                        } else {
                            // console.log("creating descriptor based on: ", result);
                            let descriptor = createFunc(_this, result);
                            persistenceManager.set(descriptorURL, descriptor.version, result);
                            // console.log("created descriptor object:", hyperty);
                            resolve(descriptor);
                        }
                    });
                }
            });
        });
    }

    /**
     * Get HypertyDescriptor
     * @param hypertyURL - e.g. mydomain.com/.well-known/hyperty/MyHyperty
     * @returns {Promise}
     */
    getHypertyDescriptor(hypertyURL) {
        let _this = this;
        return _this.getDescriptor(hypertyURL, _this._createHyperty)
    }

    /**
     * Get StubDescriptor
     * @param stubURL - e.g. mydomain.com/.well-known/protostub/MyProtostub
     * @returns {Promise}
     */
    getStubDescriptor(stubURL) {
        let _this = this;
        return _this.getDescriptor(runtimeURL, _this._createStub)
    }

    /**
     * Get RuntimeDescriptor
     * @param runtimeURL - e.g. mydomain.com/.well-known/runtime/MyRuntime
     * @returns {Promise}
     */
    getRuntimeDescriptor(runtimeURL) {
        let _this = this;
        return _this.getDescriptor(runtimeURL, _this._createRuntimeDescriptor)
    }

    /**
     * Get DataSchemaDescriptor
     * @param dataSchemaURL - e.g. mydomain.com/.well-known/dataschema/MyDataSchema
     * @returns {Promise}
     */
    getDataSchemaDescriptor(dataSchemaURL) {
        let _this = this;
        return _this.getDescriptor(runtimeURL, _this._createDataSchema)
    }

    /**
     * Get IDPProxyDescriptor
     * @param idpProxyURL - e.g. mydomain.com/.well-known/idp-proxy/MyProxy
     * @returns {Promise}
     */
    getIdpProxyDescriptor(idpProxyURL) {
        let _this = this;
        return _this.getDescriptor(runtimeURL, _this._createIdpProxy)
    }

    /**
     * Create HypertyDescriptor based on raw object that contains its attributes
     * @param _this
     * @param rawHyperty
     * @returns {HypertyDescriptor}
     */
    _createHyperty(_this, rawHyperty) {
        // create the descriptor
        let hyperty = _this._factory.createHypertyDescriptorObject(
            rawHyperty["cguid"],
            rawHyperty["version"],
            rawHyperty["objectName"],
            rawHyperty["description"],
            rawHyperty["language"],
            rawHyperty["sourcePackageURL"],
            rawHyperty["type"] || rawHyperty["hypertyType"],
            rawHyperty["dataObjects"]
        );

        // optional fields
        hyperty.configuration = rawHyperty["configuration"];
        hyperty.constraints = rawHyperty["constraints"];
        hyperty.messageSchema = rawHyperty["messageSchema"];
        hyperty.policies = rawHyperty["policies"];
        hyperty.signature = rawHyperty["signature"];

        // parse and attach sourcePackage
        let sourcePackage = rawHyperty["sourcePackage"];
        if (sourcePackage) {
            // console.log("hyperty has sourcePackage:", sourcePackage);
            hyperty.sourcePackage = _this._createSourcePackage(_this, sourcePackage);
        }

        return hyperty;
    }

    /**
     * Create ProtocolStubDescriptor based on raw object that contains its attributes
     * @param _this
     * @param rawStub
     * @returns {ProtocolStubDescriptor}
     */
    _createStub(_this, rawStub) {
        // console.log("creating stub descriptor based on: ", rawStub);

        // create the descriptor
        let stub = _this._factory.createProtoStubDescriptorObject(
            rawStub["cguid"],
            rawStub["version"],
            rawStub["objectName"],
            rawStub["description"],
            rawStub["language"],
            rawStub["sourcePackageURL"],
            rawStub["messageSchemas"],
            rawStub["configuration"],
            rawStub["constraints"]
        );

        // optional fields
        stub.signature = rawStub["signature"];

        // parse and attach the sourcePackage
        let sourcePackage = rawStub["sourcePackage"];
        if (sourcePackage) {
            sourcePackage = _this._createSourcePackage(_this, sourcePackage);
            stub.sourcePackage = sourcePackage;
        }

        return stub;
    }

    /**
     * Create HypertyRuntimeDescriptor based on raw object that contains its attributes
     * @param _this
     * @param rawRuntime
     * @returns {HypertyRuntimeDescriptor}
     */
    _createRuntimeDescriptor(_this, rawRuntime) {
        // parse capabilities first
        try {
            rawRuntime["hypertyCapabilities"] = JSON.parse(rawRuntime["hypertyCapabilities"]);
            rawRuntime["protocolCapabilities"] = JSON.parse(rawRuntime["protocolCapabilities"]);
        } catch (e) {
            // already json object
        }
        console.log("creating runtime descriptor based on: ", rawRuntime);

        // create the descriptor
        let runtime = _this._factory.createHypertyRuntimeDescriptorObject(
            rawRuntime["cguid"],
            rawRuntime["version"],
            rawRuntime["objectName"],
            rawRuntime["description"],
            rawRuntime["language"],
            rawRuntime["sourcePackageURL"],
            rawRuntime["type"] || rawRuntime["runtimeType"],
            rawRuntime["hypertyCapabilities"],
            rawRuntime["protocolCapabilities"]
        );

        // optional fields
        runtime.signature = rawRuntime["signature"];

        // parse and attach sourcePackage
        let sourcePackage = rawRuntime["sourcePackage"];
        if (sourcePackage) {
            // console.log("runtime has sourcePackage:", sourcePackage);
            runtime.sourcePackage = _this._createSourcePackage(_this, sourcePackage);
        }
        return runtime;
    }

    /**
     * Create DataObjectSchema based on raw object that contains its attributes
     * @param _this
     * @param rawSchema
     * @returns {DataObjectSchema}
     */
    _createDataSchema(_this, rawSchema) {
        console.log("creating dataSchema based on: ", rawSchema);

        // FIXME: accessControlPolicy field not needed?
        // create the descriptor
        let dataSchema = _this._factory.createDataObjectSchema(
            rawSchema["cguid"],
            rawSchema["version"],
            rawSchema["objectName"],
            rawSchema["description"],
            rawSchema["language"],
            rawSchema["sourcePackageURL"]
        );

        // optional fields
        dataSchema.signature = rawSchema["signature"];

        // parse and attach sourcePackage
        let sourcePackage = rawSchema["sourcePackage"];
        if (sourcePackage) {
            // console.log("dataSchema has sourcePackage:", sourcePackage);
            dataSchema.sourcePackage = _this._createSourcePackage(_this, sourcePackage);
        }

        console.log("created dataSchema descriptor object:", dataSchema);
        return dataSchema;
    }

    /**
     * Create ProtocolStubDescriptor based on raw object that contains its attributes
     * @param _this
     * @param rawProxy
     * @returns {ProtocolStubDescriptor}
     */
    _createIdpProxy(_this, rawProxy) {
        // console.log("creating idpproxy descriptor based on: ", rawProxy);

        // create the descriptor
        let idpproxy = _this._factory.createProtoStubDescriptorObject(
            rawProxy["cguid"],
            rawProxy["version"],
            rawProxy["objectName"],
            rawProxy["description"],
            rawProxy["language"],
            rawProxy["sourcePackageURL"],
            rawProxy["messageSchemas"],
            rawProxy["configuration"],
            rawProxy["constraints"]
        );

        // optional fields
        idpproxy.signature = rawProxy["signature"];

        // parse and attach the sourcePackage
        let sourcePackage = rawProxy["sourcePackage"];
        if (sourcePackage) {
            sourcePackage = _this._createSourcePackage(_this, sourcePackage);
            idpproxy.sourcePackage = sourcePackage;
        }

        return idpproxy;
    }

    _createSourcePackage(_this, sp) {
        //console.log("creating sourcePackage. factory:", factory, ", raw package:", sp);
        try {
            sp = JSON.parse(sp);
        } catch (e) {
            console.log("parsing sourcePackage failed. already parsed? -> ", sp);
        }

        // check encoding
        if (sp["encoding"] === "base64") {
            sp["sourceCode"] = atob(sp["sourceCode"]);
        }

        let sourcePackage = _this.factory.createSourcePackage(sp["sourceCodeClassname"], sp["sourceCode"]);
        if (sp["encoding"])
            sourcePackage.encoding = sp["encoding"];

        if (sp["signature"])
            sourcePackage.signature = sp["signature"];

        return sourcePackage;
    }

    /**
     * Get source Package from a URL
     * @param sourcePackageURL - e.g. mydomain.com/.well-known/hyperty/MyHyperty/sourcePackage
     * @returns {Promise}
     */
    getSourcePackageFromURL(sourcePackageURL) {
        let _this = this;

        console.log("getting sourcePackage from:", sourcePackageURL);
        console.warn("-------------------------------------------------------------------------------------------");
        console.warn("ATTENTION: This function may fail if the sourceCode of the the sourcePackage is very large!");
        console.warn("-------------------------------------------------------------------------------------------");

        return new Promise(function (resolve, reject) {
            _this.httpRequest.get(sourcePackageURL).then(function (result) {
                //console.log("got raw sourcePackage:", result);
                if (result["ERROR"]) {
                    // TODO handle error properly
                    reject(result);
                } else {
                    result = JSON.parse(result);
                    let sourcePackage = _this._createSourcePackage(_this, result);
                    resolve(sourcePackage);
                }
            }).catch(function (reason) {
                reject(reason);
            });

        });

    }

    /**
     * Returns the sourceCode of a given descriptor
     * @param {CatalogueDataObject} descriptor - Catalogue Object that was retrieved using e.g. getHypertyDescriptor()
     * @returns {Promise}
     */
    getSourceCodeFromDescriptor(descriptor) {
        let _this = this;
        return new Promise(function (resolve, reject) {
            if (descriptor.sourcePackage) {
                //console.log("descriptor has sourcePackage");
                //console.log("returning sourceCode:", descriptor.sourcePackage.sourceCode);
                resolve(descriptor.sourcePackage.sourceCode);
            } else {
                if (persistenceManager.getVersion(descriptor.sourcePackageURL + "/sourceCode") >= descriptor.version) {
                    console.log("returning cached version from persistence manager");
                    resolve(persistenceManager.get(descriptor.sourcePackageURL + "/sourceCode"));
                } else {
                    _this.httpRequest.get(descriptor.sourcePackageURL + "/sourceCode").then(function (sourceCode) {
                        if (sourceCode["ERROR"]) {
                            // TODO handle error properly
                            reject(sourceCode);
                        } else {
                            persistenceManager.set(descriptor.sourcePackageURL + "/sourceCode", descriptor.version, sourceCode);
                            resolve(sourceCode);
                        }
                    });
                }
            }
        });
    }

    set runtimeURL(runtimeURL) {
        let _this = this;
        _this._runtimeURL = runtimeURL;
    }

    get runtimeURL() {
        let _this = this;
        return _this._runtimeURL;
    }

    deleteFromPM(url) {
        persistenceManager.delete(url);
    }

}

export default RuntimeCatalogue;
<|endoftext|>