<commit_before>/* Copyright (C) 2016 Canonical Ltd. */

var module = module;

(function (exports) {
  'use strict';

  var jujulib = exports.jujulib;

  /**
    Romulus plans service client.

    Provides access to the Romulus plans API.
  */

  var plansAPIVersion = 'v2';

  /**
    Initializer.

    @function plans
    @param url {String} The URL of the Romulus plans instance, including
      scheme and port, and excluding the API version.
    @param bakery {Object} A bakery object for communicating with the plans
      instance.
    @returns {Object} A client object for making Romulus plans API calls.
  */
  function plans(url, bakery) {
    // Store the API URL (including version) handling missing trailing slash.
    this.url = url.replace(/\/?$/, '/') + plansAPIVersion;
    this.bakery = bakery;
  };

  plans.prototype = {
    /**
      Get a plan authorization to deploy a charm.

      @public authorizePlan
      @param uuid {String} The UUID of the model the charm is being deployed
        on.
      @param charmUrl {String} URL of the charm being deployed.
      @param applicationName {String} name of the application.
      @param planUrl {String} The URL of the plan being deployed.
      @param budget {String} The budget name for allocation.
      @param limit {String} The numeric limit for allocation.
      @param callback {Function} A callback to handle errors or accept the
        data from the request. Must accept an error message or null as its
        first parameter and an authorization object as its second.
    */
    authorizePlan: function(uuid, charmUrl, applicationName, planUrl, budget,
        limit, callback) {
      var url = this.url + '/plan/authorize';
      var payload = {
        'env-uuid': uuid,
        'charm-url': charmUrl,
        'service-name': applicationName,
        'plan-url': planUrl,
        'budget': budget,
        'limit': limit
      }
      return jujulib._makeRequest(this.bakery, url, 'POST', payload, callback);
    },

    /**
      Lists available plans for the given charm.

      @public listPlansForCharm
      @param charmUrl {String} A fully qualified charm URL, with or without
        the "cs:" schema.
      @param callback {Function} A callback to handle errors or accept the
        data from the request. Must accept an error message or null as its
        first parameter and a list of plans as its second. Each plan includes
        the following fields:
          - url: the plan URL, like "canonical-landscape/24-7";
          - price: the price for this plan;
          - description: a text describing the plan;
          - createdAt: a date object with the plan creation time;
          - yaml: the YAML content for the plan
            (not really useful in this context).
    */
    listPlansForCharm: function(charmUrl, callback) {
      var handler = function(error, plans) {
        if (error !== null) {
          callback(error, null);
          return;
        }
        callback(null, plans.map(_handlePlan));
      };
      if (charmUrl.substring(0, 3) !== 'cs:') {
        charmUrl = 'cs:' + charmUrl;
      }
      var url = this.url + '/charm?charm-url=' + charmUrl;
      return jujulib._makeRequest(this.bakery, url, 'GET', null, handler);
    },

    /**
      Finds the currently active plan for the given model and application.

      @public showActivePlan
      @param modelUUID {String} The model UUID.
      @param applicationName {String} The name of the application.
      @param callback {Function} A callback to handle errors or accept the
        data from the request. Must accept an error message or null as its
        first parameter the currently active plan as its second argument, and a
        list of available plans as its third. Each plan includes the following
        fields:
          - url: the plan URL, like "canonical-landscape/24-7";
          - price: the price for this plan;
          - description: a text describing the plan;
          - createdAt: a date object with the plan creation time;
          - yaml: the YAML content for the plan
            (not really useful in this context).
    */
    showActivePlan: function(modelUUID, applicationName, callback) {
      var handler = function(error, response) {
        if (error !== null) {
          callback(error, null, []);
          return;
        }
        var availablePlans = response['available-plans'];
        var plans = Object.keys(availablePlans).map(function(key) {
          return _handlePlan(availablePlans[key]);
        });
        var current = availablePlans[response['current-plan']];
        callback(null, _handlePlan(current), plans);
      };
      var url = this.url + '/plan/model/' + modelUUID +
        '/service/' + applicationName;
      return jujulib._makeRequest(this.bakery, url, 'GET', null, handler);
    },

    /**
      Lists a user's budgets.

      @public listBudgets
      @param callback {Function} A callback to handle errors or accept the
        data from the request. Must accept an error message or null as its
        first parameter and an object of budget data as its second, containing
        the following data:
          - budgets: an array of budgets;
          - total: an object container then summary of all budgets.
    */
    listBudgets: function(callback) {
      var handler = function(error, data) {
        if (error !== null) {
          callback(error, null);
          return;
        }
        callback(null, data);
      };
      var url = this.url + '/budget';
      return jujulib._makeRequest(this.bakery, url, 'GET', null, handler);
    },

    /**
      Create a new budget for the authorised user.

      @public createBudget
      @param budget {String} The budget name.
      @param limit {String} The numeric limit.
      @param callback {Function} A callback to handle errors or accept the
        data from the request. Must accept an error message or null as its
        first parameter and an authorization object as its second.
    */
    createBudget: function(budget, limit, callback) {
      var url = this.url + '/budget';
      var payload = {
        'budget': budget,
        'limit': limit
      }
      return jujulib._makeRequest(this.bakery, url, 'POST', payload, callback);
    },

    /**
      Changes the budget to the new limit.

      @method updateBudget
      @param budgetId {String} The budget name
      @param limit {String} The new budget value (numeric).
      @param callback {Function} A callback to handle errors or accept the
        data from the request. Must accept an error message or null as its
        first parameter and an authorization object as its second.
    */
    updateBudget: function(budgetId, limit, callback) {
      const url = `${this.url}/budget/${budgetId}`;
      const payload = { limit };
      return jujulib._makeRequest(this.bakery, url, 'PATCH', payload, callback);
    },

    /**
      Removes a budget associated with the currently logged in user.

      @method removeBudget
      @param budgetId {String} The budget name
      @param callback {Function} A callback to handle errors or accept the
        data from the request. Must accept an error message or null as its
        first parameter and an authorization object as its second.
    */
    removeBudget: function(budgetId, callback) {
      const url = `${this.url}/budget/${budgetId}`;
      return jujulib._makeRequest(this.bakery, url, 'DELETE', null, callback);
    },

    /**
      Adds a budget allocation to an application.

      @method createAllocation
      @param budgetId {String} The budget name
      @param application {String} The application to set this allocation on.
      @param model {String} The model uuid
      @param limit {String} The limit for the allocation (numeric).
      @param callback {Function} A callback to handle errors or accept the
        data from the request. Must accept an error message or null as its
        first parameter and an authorization object as its second.
    */
    createAllocation: function(budgetId, application, model, limit, callback) {
      const url = `${this.url}/budget/${budgetId}/allocation`;
      const payload = { services: [application], model, limit };
      return jujulib._makeRequest(this.bakery, url, 'POST', payload, callback);
    },

    /**
      Changes an allocation for an application

      @method updateAllocation
      @param model {String} The model uuid.
      @param app {String} the application name.
      @param limit {String} The limit for the allocation (numeric).
      @param callback {Function} A callback to handle errors or accept the
        data from the request. Must accept an error message or null as its
        first parameter and an authorization object as its second.
    */
    updateAllocation: function(model, app, limit, callback) {
      const url = `${this.url}/model/${model}/service/${app}/allocation`;
      const payload = { limit };
      return jujulib._makeRequest(this.bakery, url, 'PATCH', payload, callback);
    },

    /**
      Removes the allocation from the service

      @method removeAllocation
      @param {String} app The application name.
      @param {String} model The model uuid
      @param callback {Function} A callback to handle errors or accept the
        data from the request. Must accept an error message or null as its
        first parameter and an authorization object as its second.
    */
    removeAllocation: function(app, model, callback) {
      const url = `${this.url}/environment/${model}/service/${app}/allocation`;
      return jujulib._makeRequest(this.bakery, url, 'DELETE', null, callback);
    },

    /**
      Get the details for a budget.

      @public showBudget
      @param budget {String} A buget name.
      @param callback {Function} A callback to handle errors or accept the
        data from the request. Must accept an error message or null as its
        first parameter and an object of budget data as its second, containing
        the following data:
          - limit: the budget limit;
          - total: an object container then summary of all budgets;
          - allocations: an array of allocation details.
    */
    showBudget: function(budget, callback) {
      var handler = function(error, data) {
        if (error !== null) {
          callback(error, null);
          return;
        }
        callback(null, data);
      };
      var url = this.url + '/budget/' + budget;
      return jujulib._makeRequest(this.bakery, url, 'GET', null, handler);
    },

    /**
      Create a new profile and credit limit for the authorised user.

      @public createProfile
      @param user {String} The user's name.
      @param limit {String} The numeric limit.
      @param defaultBudget {String} The default budget name.
      @param defaultLimit {String} The numeric limit for the default budget.
      @param callback {Function} A callback to handle errors or accept the
        data from the request. Must accept an error message or null as its
        first parameter and an authorization object as its second.
    */
    createProfile: function(
      user, limit, defaultBudget, defaultLimit, callback) {
      var url = this.url + '/profile';
      var payload = {
        'user': user,
        'limit': limit,
        'default-budget': defaultBudget,
        'default-budget-limit': defaultLimit
      }
      return jujulib._makeRequest(this.bakery, url, 'POST', payload, callback);
    },

    /**
      Updates the users credit limit.

      @method updateCreditLimit
      @param {String} user The user's name.
      @param {String} limit The numeric limit.
      @param {Function} callback A callback to handle errors or accept the
        data from the request. Must accept an error message or null as its
        first parameter and an authorization object as its second.
    */
    updateCreditLimit: function(user, limit, callback) {
      const url = `${this.url}/profile/${user}`;
      const payload = { update: { limit } };
      return jujulib._makeRequest(this.bakery, url, 'PATCH', payload, callback);
    },

    /**
      Updates the users default budget

      @method updateDefaultBudget
      @param {String} defaultBudget The default budgets name.
      @param {Function} callback A callback to handle errors or accept the
        data from the request. Must accept an error message or null as its
        first parameter and an authorization object as its second.
    */
    updateDefaultBudget: function(defaultBudget, callback) {
      const url = `${this.url}/profile`;
      const payload = { update: { 'default-budget': defaultBudget } };
      return jujulib._makeRequest(this.bakery, url, 'PATCH', payload, callback);
    }

  };

  /**
    Handles plan response data.

    @public _handlePlan
    @param plan {Object} The plan data returned by the plan service. It
      includes at least the following fields:
        - url: the plan URL, like "canonical-landscape/24-7";
        - price: the price for this plan;
        - description: a text describing the plan;
        - created-on: the creation time string, like "2016-06-08T15:54:13Z";
        - plan: the YAML content for the plan.
    @return {Object} A JavaScript friendly representation of a plan.
  */
  var _handlePlan = function(plan) {
    var milliseconds = Date.parse(plan['created-on']);
    return {
      url: plan.url,
      price: plan.price,
      description: plan.description,
      createdAt: new Date(milliseconds),
      yaml: plan.plan
    };
  };

  // Populate the library with the API client and supported version.
  jujulib.plans = plans;
  jujulib.plansAPIVersion = plansAPIVersion;

}((module && module.exports) ? module.exports : this));
<commit_msg>De-es6ify the code<commit_after>/* Copyright (C) 2016 Canonical Ltd. */

var module = module;

(function (exports) {
  'use strict';

  var jujulib = exports.jujulib;

  /**
    Romulus plans service client.

    Provides access to the Romulus plans API.
  */

  var plansAPIVersion = 'v2';

  /**
    Initializer.

    @function plans
    @param url {String} The URL of the Romulus plans instance, including
      scheme and port, and excluding the API version.
    @param bakery {Object} A bakery object for communicating with the plans
      instance.
    @returns {Object} A client object for making Romulus plans API calls.
  */
  function plans(url, bakery) {
    // Store the API URL (including version) handling missing trailing slash.
    this.url = url.replace(/\/?$/, '/') + plansAPIVersion;
    this.bakery = bakery;
  };

  plans.prototype = {
    /**
      Get a plan authorization to deploy a charm.

      @public authorizePlan
      @param uuid {String} The UUID of the model the charm is being deployed
        on.
      @param charmUrl {String} URL of the charm being deployed.
      @param applicationName {String} name of the application.
      @param planUrl {String} The URL of the plan being deployed.
      @param budget {String} The budget name for allocation.
      @param limit {String} The numeric limit for allocation.
      @param callback {Function} A callback to handle errors or accept the
        data from the request. Must accept an error message or null as its
        first parameter and an authorization object as its second.
    */
    authorizePlan: function(uuid, charmUrl, applicationName, planUrl, budget,
        limit, callback) {
      var url = this.url + '/plan/authorize';
      var payload = {
        'env-uuid': uuid,
        'charm-url': charmUrl,
        'service-name': applicationName,
        'plan-url': planUrl,
        'budget': budget,
        'limit': limit
      }
      return jujulib._makeRequest(this.bakery, url, 'POST', payload, callback);
    },

    /**
      Lists available plans for the given charm.

      @public listPlansForCharm
      @param charmUrl {String} A fully qualified charm URL, with or without
        the "cs:" schema.
      @param callback {Function} A callback to handle errors or accept the
        data from the request. Must accept an error message or null as its
        first parameter and a list of plans as its second. Each plan includes
        the following fields:
          - url: the plan URL, like "canonical-landscape/24-7";
          - price: the price for this plan;
          - description: a text describing the plan;
          - createdAt: a date object with the plan creation time;
          - yaml: the YAML content for the plan
            (not really useful in this context).
    */
    listPlansForCharm: function(charmUrl, callback) {
      var handler = function(error, plans) {
        if (error !== null) {
          callback(error, null);
          return;
        }
        callback(null, plans.map(_handlePlan));
      };
      if (charmUrl.substring(0, 3) !== 'cs:') {
        charmUrl = 'cs:' + charmUrl;
      }
      var url = this.url + '/charm?charm-url=' + charmUrl;
      return jujulib._makeRequest(this.bakery, url, 'GET', null, handler);
    },

    /**
      Finds the currently active plan for the given model and application.

      @public showActivePlan
      @param modelUUID {String} The model UUID.
      @param applicationName {String} The name of the application.
      @param callback {Function} A callback to handle errors or accept the
        data from the request. Must accept an error message or null as its
        first parameter the currently active plan as its second argument, and a
        list of available plans as its third. Each plan includes the following
        fields:
          - url: the plan URL, like "canonical-landscape/24-7";
          - price: the price for this plan;
          - description: a text describing the plan;
          - createdAt: a date object with the plan creation time;
          - yaml: the YAML content for the plan
            (not really useful in this context).
    */
    showActivePlan: function(modelUUID, applicationName, callback) {
      var handler = function(error, response) {
        if (error !== null) {
          callback(error, null, []);
          return;
        }
        var availablePlans = response['available-plans'];
        var plans = Object.keys(availablePlans).map(function(key) {
          return _handlePlan(availablePlans[key]);
        });
        var current = availablePlans[response['current-plan']];
        callback(null, _handlePlan(current), plans);
      };
      var url = this.url + '/plan/model/' + modelUUID +
        '/service/' + applicationName;
      return jujulib._makeRequest(this.bakery, url, 'GET', null, handler);
    },

    /**
      Lists a user's budgets.

      @public listBudgets
      @param callback {Function} A callback to handle errors or accept the
        data from the request. Must accept an error message or null as its
        first parameter and an object of budget data as its second, containing
        the following data:
          - budgets: an array of budgets;
          - total: an object container then summary of all budgets.
    */
    listBudgets: function(callback) {
      var handler = function(error, data) {
        if (error !== null) {
          callback(error, null);
          return;
        }
        callback(null, data);
      };
      var url = this.url + '/budget';
      return jujulib._makeRequest(this.bakery, url, 'GET', null, handler);
    },

    /**
      Create a new budget for the authorised user.

      @public createBudget
      @param budget {String} The budget name.
      @param limit {String} The numeric limit.
      @param callback {Function} A callback to handle errors or accept the
        data from the request. Must accept an error message or null as its
        first parameter and an authorization object as its second.
    */
    createBudget: function(budget, limit, callback) {
      var url = this.url + '/budget';
      var payload = {
        'budget': budget,
        'limit': limit
      }
      return jujulib._makeRequest(this.bakery, url, 'POST', payload, callback);
    },

    /**
      Changes the budget to the new limit.

      @method updateBudget
      @param budgetId {String} The budget name
      @param limit {String} The new budget value (numeric).
      @param callback {Function} A callback to handle errors or accept the
        data from the request. Must accept an error message or null as its
        first parameter and an authorization object as its second.
    */
    updateBudget: function(budgetId, limit, callback) {
      var url = this.url + '/budget/' + budgetId;
      var payload = { limit: limit };
      return jujulib._makeRequest(this.bakery, url, 'PATCH', payload, callback);
    },

    /**
      Removes a budget associated with the currently logged in user.

      @method removeBudget
      @param budgetId {String} The budget name
      @param callback {Function} A callback to handle errors or accept the
        data from the request. Must accept an error message or null as its
        first parameter and an authorization object as its second.
    */
    removeBudget: function(budgetId, callback) {
      var url = this.url + '/budget/' + budgetId;
      return jujulib._makeRequest(this.bakery, url, 'DELETE', null, callback);
    },

    /**
      Adds a budget allocation to an application.

      @method createAllocation
      @param budgetId {String} The budget name
      @param application {String} The application to set this allocation on.
      @param model {String} The model uuid
      @param limit {String} The limit for the allocation (numeric).
      @param callback {Function} A callback to handle errors or accept the
        data from the request. Must accept an error message or null as its
        first parameter and an authorization object as its second.
    */
    createAllocation: function(budgetId, application, model, limit, callback) {
      var url = this.url + '/budget/' + budgetId + '/allocation';
      var payload = {
        services: [application],
        model: model,
        limit: limit
      };
      return jujulib._makeRequest(this.bakery, url, 'POST', payload, callback);
    },

    /**
      Changes an allocation for an application

      @method updateAllocation
      @param model {String} The model uuid.
      @param app {String} the application name.
      @param limit {String} The limit for the allocation (numeric).
      @param callback {Function} A callback to handle errors or accept the
        data from the request. Must accept an error message or null as its
        first parameter and an authorization object as its second.
    */
    updateAllocation: function(model, app, limit, callback) {
      var url = this.url + '/model/' + model +
        '/service/' + app + '/allocation';
      var payload = { limit: limit };
      return jujulib._makeRequest(this.bakery, url, 'PATCH', payload, callback);
    },

    /**
      Removes the allocation from the service

      @method removeAllocation
      @param {String} app The application name.
      @param {String} model The model uuid
      @param callback {Function} A callback to handle errors or accept the
        data from the request. Must accept an error message or null as its
        first parameter and an authorization object as its second.
    */
    removeAllocation: function(app, model, callback) {
      var url = this.url + '/environment/' + model +
        '/service/' + app + '/allocation';
      return jujulib._makeRequest(this.bakery, url, 'DELETE', null, callback);
    },

    /**
      Get the details for a budget.

      @public showBudget
      @param budget {String} A buget name.
      @param callback {Function} A callback to handle errors or accept the
        data from the request. Must accept an error message or null as its
        first parameter and an object of budget data as its second, containing
        the following data:
          - limit: the budget limit;
          - total: an object container then summary of all budgets;
          - allocations: an array of allocation details.
    */
    showBudget: function(budget, callback) {
      var handler = function(error, data) {
        if (error !== null) {
          callback(error, null);
          return;
        }
        callback(null, data);
      };
      var url = this.url + '/budget/' + budget;
      return jujulib._makeRequest(this.bakery, url, 'GET', null, handler);
    },

    /**
      Create a new profile and credit limit for the authorised user.

      @public createProfile
      @param user {String} The user's name.
      @param limit {String} The numeric limit.
      @param defaultBudget {String} The default budget name.
      @param defaultLimit {String} The numeric limit for the default budget.
      @param callback {Function} A callback to handle errors or accept the
        data from the request. Must accept an error message or null as its
        first parameter and an authorization object as its second.
    */
    createProfile: function(
      user, limit, defaultBudget, defaultLimit, callback) {
      var url = this.url + '/profile';
      var payload = {
        'user': user,
        'limit': limit,
        'default-budget': defaultBudget,
        'default-budget-limit': defaultLimit
      }
      return jujulib._makeRequest(this.bakery, url, 'POST', payload, callback);
    },

    /**
      Updates the users credit limit.

      @method updateCreditLimit
      @param {String} user The user's name.
      @param {String} limit The numeric limit.
      @param {Function} callback A callback to handle errors or accept the
        data from the request. Must accept an error message or null as its
        first parameter and an authorization object as its second.
    */
    updateCreditLimit: function(user, limit, callback) {
      var url = this.url + '/profile/' + user;
      var payload = { update: { limit: limit } };
      return jujulib._makeRequest(this.bakery, url, 'PATCH', payload, callback);
    },

    /**
      Updates the users default budget

      @method updateDefaultBudget
      @param {String} defaultBudget The default budgets name.
      @param {Function} callback A callback to handle errors or accept the
        data from the request. Must accept an error message or null as its
        first parameter and an authorization object as its second.
    */
    updateDefaultBudget: function(defaultBudget, callback) {
      var url = this.url + '/profile';
      var payload = { update: { 'default-budget': defaultBudget } };
      return jujulib._makeRequest(this.bakery, url, 'PATCH', payload, callback);
    }

  };

  /**
    Handles plan response data.

    @public _handlePlan
    @param plan {Object} The plan data returned by the plan service. It
      includes at least the following fields:
        - url: the plan URL, like "canonical-landscape/24-7";
        - price: the price for this plan;
        - description: a text describing the plan;
        - created-on: the creation time string, like "2016-06-08T15:54:13Z";
        - plan: the YAML content for the plan.
    @return {Object} A JavaScript friendly representation of a plan.
  */
  var _handlePlan = function(plan) {
    var milliseconds = Date.parse(plan['created-on']);
    return {
      url: plan.url,
      price: plan.price,
      description: plan.description,
      createdAt: new Date(milliseconds),
      yaml: plan.plan
    };
  };

  // Populate the library with the API client and supported version.
  jujulib.plans = plans;
  jujulib.plansAPIVersion = plansAPIVersion;

}((module && module.exports) ? module.exports : this));
<|endoftext|>


<commit_before>	'use strict'

$("#Bouton2050").click(function(e){
	if(document.getElementById("scenar1").value==1){

	}
	if(document.getElementById("scenar2").value==2){

	}
	if(document.getElementById("scenar3").value==3){

	}
	if(document.getElementById("scenar4").value==4){

	}
});

$("#scenar1").click(function(e){
	$("#BateauRougeGrosJ1").fadeOut("slow");
	$("#BateauRougePetitJ1").fadeIn("slow");
	$("#BateauBleuClairJ1").fadeOut("slow");
	$("#BateauRoseJ1").fadeOut("slow");
	$("#BateauBleuFonceJ1").fadeIn("slow");
	$("#BateauNoirJ1").fadeOut("slow");

});

$("#scenar2").click(function(e){
	$("#BateauRougeGrosJ1").fadeIn("slow");
	$("#BateauRougePetitJ1").fadeOut("slow");
	$("#BateauBleuClairJ1").fadeOut("slow");
	$("#BateauRoseJ1").fadeOut("slow");
	$("#BateauBleuFonceJ1").fadeOut("slow");
	$("#BateauNoirJ1").fadeIn("slow");
});

$("#scenar3").click(function(e){
	$("#BateauRougeGrosJ1").fadeIn("slow");
	$("#BateauRougePetitJ1").fadeIn("slow");
	$("#BateauBleuClairJ1").fadeOut("slow");
	$("#BateauRoseJ1").fadeOut("slow");
	$("#BateauBleuFonceJ1").fadeIn("slow");
	$("#BateauNoirJ1").fadeIn("slow");
});

$("#scenar4").click(function(e){
	$("#BateauRougeGrosJ1").fadeIn("slow");
	$("#BateauRougePetitJ1").fadeIn("slow");
	$("#BateauBleuClairJ1").fadeIn("slow");
	$("#BateauRoseJ1").fadeIn("slow");
	$("#BateauBleuFonceJ1").fadeIn("slow");
	$("#BateauNoirJ1").fadeIn("slow");
});

/*
$("#barreJ1").mouseup(function(e){
	if (document.getElementById("barreJ1").value==0){
		$("#BateauRougeGrosJ1").fadeOut("slow");
		$("#BateauRougePetitJ1").fadeOut("slow");
		$("#BateauBleuClairJ1").fadeOut("slow");
		$("#BateauRoseJ1").fadeOut("slow");
		$("#BateauBleuFonceJ1").fadeOut("slow");
		$("#BateauNoirJ1").fadeOut("slow");

		$("#MerluJ1-1").fadeIn("slow");
		$("#MerluJ1-2").fadeIn("slow");
		$("#MerluJ1-3").fadeIn("slow");
		$("#ColinJ1-1").fadeIn("slow");
		$("#ColinJ1-2").fadeIn("slow");
		$("#HomardJ1-1").fadeIn("slow");
		$("#HomardJ1-2").fadeIn("slow");
		$("#HomardJ1-3").fadeIn("slow");
		$("#PoissonJ1-1").fadeIn("slow");
		$("#PoissonJ1-2").fadeIn("slow");
	}

	else if (document.getElementById("barreJ1").value==1){
		$("#BateauRougeGrosJ1").fadeOut("slow");
		$("#BateauRougePetitJ1").fadeIn("slow");
		$("#BateauBleuClairJ1").fadeOut("slow");
		$("#BateauRoseJ1").fadeOut("slow");
		$("#BateauBleuFonceJ1").fadeOut("slow");
		$("#BateauNoirJ1").fadeOut("slow");

		$("#MerluJ1-1").fadeIn("slow");
		$("#MerluJ1-2").fadeIn("slow");
		$("#MerluJ1-3").fadeIn("slow");
		$("#ColinJ1-1").fadeOut("slow");
		$("#ColinJ1-2").fadeIn("slow");
		$("#HomardJ1-1").fadeIn("slow");
		$("#HomardJ1-2").fadeIn("slow");
		$("#HomardJ1-3").fadeIn("slow");
		$("#PoissonJ1-1").fadeIn("slow");
		$("#PoissonJ1-2").fadeIn("slow");
	}

	else if (document.getElementById("barreJ1").value==2){
		$("#BateauRougeGrosJ1").fadeIn("slow");
		$("#BateauRougePetitJ1").fadeIn("slow");
		$("#BateauBleuClairJ1").fadeOut("slow");
		$("#BateauRoseJ1").fadeOut("slow");
		$("#BateauBleuFonceJ1").fadeOut("slow");
		$("#BateauNoirJ1").fadeOut("slow");

		$("#MerluJ1-1").fadeIn("slow");
		$("#MerluJ1-2").fadeIn("slow");
		$("#MerluJ1-3").fadeIn("slow");
		$("#ColinJ1-1").fadeOut("slow");
		$("#ColinJ1-2").fadeIn("slow");
		$("#HomardJ1-1").fadeIn("slow");
		$("#HomardJ1-2").fadeIn("slow");
		$("#HomardJ1-3").fadeIn("slow");
		$("#PoissonJ1-1").fadeOut("slow");
		$("#PoissonJ1-2").fadeIn("slow");
	}

	else if (document.getElementById("barreJ1").value==3){
		$("#BateauRougeGrosJ1").fadeIn("slow");
		$("#BateauRougePetitJ1").fadeIn("slow");
		$("#BateauBleuClairJ1").fadeOut("slow");
		$("#BateauRoseJ1").fadeIn("slow");
		$("#BateauBleuFonceJ1").fadeOut("slow");
		$("#BateauNoirJ1").fadeOut("slow");

		$("#MerluJ1-1").fadeOut("slow");
		$("#MerluJ1-2").fadeIn("slow");
		$("#MerluJ1-3").fadeIn("slow");
		$("#ColinJ1-1").fadeOut("slow");
		$("#ColinJ1-2").fadeIn("slow");
		$("#HomardJ1-1").fadeOut("slow");
		$("#HomardJ1-2").fadeIn("slow");
		$("#HomardJ1-3").fadeIn("slow");
		$("#PoissonJ1-1").fadeOut("slow");
		$("#PoissonJ1-2").fadeIn("slow");
	}

	else if (document.getElementById("barreJ1").value==4){
		$("#BateauRougeGrosJ1").fadeIn("slow");
		$("#BateauRougePetitJ1").fadeIn("slow");
		$("#BateauBleuClairJ1").fadeOut("slow");
		$("#BateauRoseJ1").fadeIn("slow");
		$("#BateauBleuFonceJ1").fadeIn("slow");
		$("#BateauNoirJ1").fadeOut("slow");

		$("#MerluJ1-1").fadeOut("slow");
		$("#MerluJ1-2").fadeOut("slow");
		$("#MerluJ1-3").fadeIn("slow");
		$("#ColinJ1-1").fadeOut("slow");
		$("#ColinJ1-2").fadeIn("slow");
		$("#HomardJ1-1").fadeOut("slow");
		$("#HomardJ1-2").fadeOut("slow");
		$("#HomardJ1-3").fadeIn("slow");
		$("#PoissonJ1-1").fadeOut("slow");
		$("#PoissonJ1-2").fadeIn("slow");
	}

	else if (document.getElementById("barreJ1").value==5){
		$("#BateauRougeGrosJ1").fadeIn("slow");
		$("#BateauRougePetitJ1").fadeIn("slow");
		$("#BateauBleuClairJ1").fadeOut("slow");
		$("#BateauRoseJ1").fadeIn("slow");
		$("#BateauBleuFonceJ1").fadeIn("slow");
		$("#BateauNoirJ1").fadeIn("slow");

		$("#MerluJ1-1").fadeOut("slow");
		$("#MerluJ1-2").fadeOut("slow");
		$("#MerluJ1-3").fadeOut("slow");
		$("#ColinJ1-1").fadeOut("slow");
		$("#ColinJ1-2").fadeIn("slow");
		$("#HomardJ1-1").fadeOut("slow");
		$("#HomardJ1-2").fadeOut("slow");
		$("#HomardJ1-3").fadeIn("slow");
		$("#PoissonJ1-1").fadeOut("slow");
		$("#PoissonJ1-2").fadeOut("slow");
	}

	else if (document.getElementById("barreJ1").value==6){
		$("#BateauRougeGrosJ1").fadeIn("slow");
		$("#BateauRougePetitJ1").fadeIn("slow");
		$("#BateauBleuClairJ1").fadeIn("slow");
		$("#BateauRoseJ1").fadeIn("slow");
		$("#BateauBleuFonceJ1").fadeIn("slow");
		$("#BateauNoirJ1").fadeIn("slow");

		$("#MerluJ1-1").fadeOut("slow");
		$("#MerluJ1-2").fadeOut("slow");
		$("#MerluJ1-3").fadeOut("slow");
		$("#ColinJ1-1").fadeOut("slow");
		$("#ColinJ1-2").fadeOut("slow");
		$("#HomardJ1-1").fadeOut("slow");
		$("#HomardJ1-2").fadeOut("slow");
		$("#HomardJ1-3").fadeOut("slow");
		$("#PoissonJ1-1").fadeOut("slow");
		$("#PoissonJ1-2").fadeOut("slow");
	}
});
*/<commit_msg>Ajout bouton 2050<commit_after>	'use strict'

$("#Bouton2050").click(function(e){
	if(document.getElementById("scenar1").checked){
		$("#HomardJ2-1").fadeIn("slow");
		$("#HomardJ2-2").fadeIn("slow");
		$("#HomardJ2-3").fadeIn("slow");
		$("#HomardJ2-4").fadeIn("slow");

		$("#MerluJ2-1").fadeIn("slow");
		$("#MerluJ2-2").fadeIn("slow");
		$("#MerluJ2-3").fadeIn("slow");
		$("#MerluJ2-4").fadeIn("slow");

		$("#SoleJ2-1").fadeIn("slow");
		$("#SoleJ2-2").fadeIn("slow");
		$("#SoleJ2-3").fadeIn("slow");
		$("#SoleJ2-4").fadeOut("slow");

		$("#solea").style.transform = 'scale(' + 1.1 + ')';
		$("#homarda").style.transform = 'scale(' + 0.3 + ')';
		$("#merlua").style.transform = 'scale(' + 0 + ')';
	}
	if(document.getElementById("scenar2").checked){
		$("#HomardJ2-1").fadeIn("slow");
		$("#HomardJ2-2").fadeIn("slow");
		$("#HomardJ2-3").fadeIn("slow");
		$("#HomardJ2-4").fadeIn("slow");

		$("#MerluJ2-1").fadeIn("slow");
		$("#MerluJ2-2").fadeIn("slow");
		$("#MerluJ2-3").fadeIn("slow");
		$("#MerluJ2-4").fadeIn("slow");

		$("#SoleJ2-1").fadeIn("slow");
		$("#SoleJ2-2").fadeIn("slow");
		$("#SoleJ2-3").fadeIn("slow");
		$("#SoleJ2-4").fadeOut("slow");

		$("#solea").style.transform = 'scale(' + 1.05 + ')';
		$("#homarda").style.transform = 'scale(' + 0.95 + ')';
		$("#merlua").style.transform = 'scale(' + 0 + ')';
	}
	if(document.getElementById("scenar3").checked){
		$("#HomardJ2-1").fadeIn("slow");
		$("#HomardJ2-2").fadeIn("slow");
		$("#HomardJ2-3").fadeIn("slow");
		$("#HomardJ2-4").fadeIn("slow");

		$("#MerluJ2-1").fadeIn("slow");
		$("#MerluJ2-2").fadeIn("slow");
		$("#MerluJ2-3").fadeIn("slow");
		$("#MerluJ2-4").fadeOut("slow");

		$("#SoleJ2-1").fadeIn("slow");
		$("#SoleJ2-2").fadeIn("slow");
		$("#SoleJ2-3").fadeIn("slow");
		$("#SoleJ2-4").fadeOut("slow");

		$("#solea").style.transform = 'scale(' + 0.90 + ')';
		$("#homarda").style.transform = 'scale(' + 0.2 + ')';
		$("#merlua").style.transform = 'scale(' + 0 + ')';

	}
	if(document.getElementById("scenar4").checked){
		$("#HomardJ2-1").fadeIn("slow");
		$("#HomardJ2-2").fadeIn("slow");
		$("#HomardJ2-3").fadeIn("slow");
		$("#HomardJ2-4").fadeIn("slow");

		$("#MerluJ2-1").fadeIn("slow");
		$("#MerluJ2-2").fadeIn("slow");
		$("#MerluJ2-3").fadeOut("slow");
		$("#MerluJ2-4").fadeOut("slow");

		$("#SoleJ2-1").fadeIn("slow");
		$("#SoleJ2-2").fadeIn("slow");
		$("#SoleJ2-3").fadeIn("slow");
		$("#SoleJ2-4").fadeOut("slow");

		$("#solea").style.transform = 'scale(' + 0.7 + ')';
		$("#homarda").style.transform = 'scale(' + 0 + ')';
		$("#merlua").style.transform = 'scale(' + 0 + ')';

	}
});

$("#scenar1").click(function(e){
	$("#BateauRougeGrosJ2").fadeOut("slow");
	$("#BateauRougePetitJ2").fadeIn("slow");
	$("#BateauBleuClairJ2").fadeOut("slow");
	$("#BateauRoseJ2").fadeOut("slow");
	$("#BateauBleuFonceJ2").fadeIn("slow");
	$("#BateauNoirJ2").fadeOut("slow");

	$("#solea").style.transform = 'scale(' +  + ')';
	$("#homarda").style.transform = 'scale(' +  + ')';
	$("#merlua").style.transform = 'scale(' +  + ')';

});

$("#scenar2").click(function(e){
	$("#BateauRougeGrosJ2").fadeIn("slow");
	$("#BateauRougePetitJ2").fadeOut("slow");
	$("#BateauBleuClairJ2").fadeOut("slow");
	$("#BateauRoseJ2").fadeOut("slow");
	$("#BateauBleuFonceJ2").fadeOut("slow");
	$("#BateauNoirJ2").fadeIn("slow");

	$("#solea").style.transform = 'scale(' +  + ')';
	$("#homarda").style.transform = 'scale(' +  + ')';
	$("#merlua").style.transform = 'scale(' +  + ')';
});

$("#scenar3").click(function(e){
	$("#BateauRougeGrosJ2").fadeIn("slow");
	$("#BateauRougePetitJ2").fadeIn("slow");
	$("#BateauBleuClairJ2").fadeOut("slow");
	$("#BateauRoseJ2").fadeOut("slow");
	$("#BateauBleuFonceJ2").fadeIn("slow");
	$("#BateauNoirJ2").fadeIn("slow");

	$("#solea").style.transform = 'scale(' +  + ')';
	$("#homarda").style.transform = 'scale(' +  + ')';
	$("#merlua").style.transform = 'scale(' +  + ')';
});

$("#scenar4").click(function(e){
	$("#BateauRougeGrosJ2").fadeIn("slow");
	$("#BateauRougePetitJ2").fadeIn("slow");
	$("#BateauBleuClairJ2").fadeIn("slow");
	$("#BateauRoseJ2").fadeIn("slow");
	$("#BateauBleuFonceJ2").fadeIn("slow");
	$("#BateauNoirJ2").fadeIn("slow");

	$("#solea").style.transform = 'scale(' +  + ')';
	$("#homarda").style.transform = 'scale(' +  + ')';
	$("#merlua").style.transform = 'scale(' +  + ')';
});

/*
$("#barreJ2").mouseup(function(e){
	if (document.getElementById("barreJ2").value==0){
		$("#BateauRougeGrosJ2").fadeOut("slow");
		$("#BateauRougePetitJ2").fadeOut("slow");
		$("#BateauBleuClairJ2").fadeOut("slow");
		$("#BateauRoseJ2").fadeOut("slow");
		$("#BateauBleuFonceJ2").fadeOut("slow");
		$("#BateauNoirJ2").fadeOut("slow");

		$("#MerluJ2-1").fadeIn("slow");
		$("#MerluJ2-2").fadeIn("slow");
		$("#MerluJ2-3").fadeIn("slow");
		$("#ColinJ2-1").fadeIn("slow");
		$("#ColinJ2-2").fadeIn("slow");
		$("#HomardJ2-1").fadeIn("slow");
		$("#HomardJ2-2").fadeIn("slow");
		$("#HomardJ2-3").fadeIn("slow");
		$("#PoissonJ2-1").fadeIn("slow");
		$("#PoissonJ2-2").fadeIn("slow");
	}

	else if (document.getElementById("barreJ2").value==1){
		$("#BateauRougeGrosJ2").fadeOut("slow");
		$("#BateauRougePetitJ2").fadeIn("slow");
		$("#BateauBleuClairJ2").fadeOut("slow");
		$("#BateauRoseJ2").fadeOut("slow");
		$("#BateauBleuFonceJ2").fadeOut("slow");
		$("#BateauNoirJ2").fadeOut("slow");

		$("#MerluJ2-1").fadeIn("slow");
		$("#MerluJ2-2").fadeIn("slow");
		$("#MerluJ2-3").fadeIn("slow");
		$("#ColinJ2-1").fadeOut("slow");
		$("#ColinJ2-2").fadeIn("slow");
		$("#HomardJ2-1").fadeIn("slow");
		$("#HomardJ2-2").fadeIn("slow");
		$("#HomardJ2-3").fadeIn("slow");
		$("#PoissonJ2-1").fadeIn("slow");
		$("#PoissonJ2-2").fadeIn("slow");
	}

	else if (document.getElementById("barreJ2").value==2){
		$("#BateauRougeGrosJ2").fadeIn("slow");
		$("#BateauRougePetitJ2").fadeIn("slow");
		$("#BateauBleuClairJ2").fadeOut("slow");
		$("#BateauRoseJ2").fadeOut("slow");
		$("#BateauBleuFonceJ2").fadeOut("slow");
		$("#BateauNoirJ2").fadeOut("slow");

		$("#MerluJ2-1").fadeIn("slow");
		$("#MerluJ2-2").fadeIn("slow");
		$("#MerluJ2-3").fadeIn("slow");
		$("#ColinJ2-1").fadeOut("slow");
		$("#ColinJ2-2").fadeIn("slow");
		$("#HomardJ2-1").fadeIn("slow");
		$("#HomardJ2-2").fadeIn("slow");
		$("#HomardJ2-3").fadeIn("slow");
		$("#PoissonJ2-1").fadeOut("slow");
		$("#PoissonJ2-2").fadeIn("slow");
	}

	else if (document.getElementById("barreJ2").value==3){
		$("#BateauRougeGrosJ2").fadeIn("slow");
		$("#BateauRougePetitJ2").fadeIn("slow");
		$("#BateauBleuClairJ2").fadeOut("slow");
		$("#BateauRoseJ2").fadeIn("slow");
		$("#BateauBleuFonceJ2").fadeOut("slow");
		$("#BateauNoirJ2").fadeOut("slow");

		$("#MerluJ2-1").fadeOut("slow");
		$("#MerluJ2-2").fadeIn("slow");
		$("#MerluJ2-3").fadeIn("slow");
		$("#ColinJ2-1").fadeOut("slow");
		$("#ColinJ2-2").fadeIn("slow");
		$("#HomardJ2-1").fadeOut("slow");
		$("#HomardJ2-2").fadeIn("slow");
		$("#HomardJ2-3").fadeIn("slow");
		$("#PoissonJ2-1").fadeOut("slow");
		$("#PoissonJ2-2").fadeIn("slow");
	}

	else if (document.getElementById("barreJ2").value==4){
		$("#BateauRougeGrosJ2").fadeIn("slow");
		$("#BateauRougePetitJ2").fadeIn("slow");
		$("#BateauBleuClairJ2").fadeOut("slow");
		$("#BateauRoseJ2").fadeIn("slow");
		$("#BateauBleuFonceJ2").fadeIn("slow");
		$("#BateauNoirJ2").fadeOut("slow");

		$("#MerluJ2-1").fadeOut("slow");
		$("#MerluJ2-2").fadeOut("slow");
		$("#MerluJ2-3").fadeIn("slow");
		$("#ColinJ2-1").fadeOut("slow");
		$("#ColinJ2-2").fadeIn("slow");
		$("#HomardJ2-1").fadeOut("slow");
		$("#HomardJ2-2").fadeOut("slow");
		$("#HomardJ2-3").fadeIn("slow");
		$("#PoissonJ2-1").fadeOut("slow");
		$("#PoissonJ2-2").fadeIn("slow");
	}

	else if (document.getElementById("barreJ2").value==5){
		$("#BateauRougeGrosJ2").fadeIn("slow");
		$("#BateauRougePetitJ2").fadeIn("slow");
		$("#BateauBleuClairJ2").fadeOut("slow");
		$("#BateauRoseJ2").fadeIn("slow");
		$("#BateauBleuFonceJ2").fadeIn("slow");
		$("#BateauNoirJ2").fadeIn("slow");

		$("#MerluJ2-1").fadeOut("slow");
		$("#MerluJ2-2").fadeOut("slow");
		$("#MerluJ2-3").fadeOut("slow");
		$("#ColinJ2-1").fadeOut("slow");
		$("#ColinJ2-2").fadeIn("slow");
		$("#HomardJ2-1").fadeOut("slow");
		$("#HomardJ2-2").fadeOut("slow");
		$("#HomardJ2-3").fadeIn("slow");
		$("#PoissonJ2-1").fadeOut("slow");
		$("#PoissonJ2-2").fadeOut("slow");
	}

	else if (document.getElementById("barreJ2").value==6){
		$("#BateauRougeGrosJ2").fadeIn("slow");
		$("#BateauRougePetitJ2").fadeIn("slow");
		$("#BateauBleuClairJ2").fadeIn("slow");
		$("#BateauRoseJ2").fadeIn("slow");
		$("#BateauBleuFonceJ2").fadeIn("slow");
		$("#BateauNoirJ2").fadeIn("slow");

		$("#MerluJ2-1").fadeOut("slow");
		$("#MerluJ2-2").fadeOut("slow");
		$("#MerluJ2-3").fadeOut("slow");
		$("#ColinJ2-1").fadeOut("slow");
		$("#ColinJ2-2").fadeOut("slow");
		$("#HomardJ2-1").fadeOut("slow");
		$("#HomardJ2-2").fadeOut("slow");
		$("#HomardJ2-3").fadeOut("slow");
		$("#PoissonJ2-1").fadeOut("slow");
		$("#PoissonJ2-2").fadeOut("slow");
	}
});
*/<|endoftext|>


<commit_before>/*
 * Copyrights phwang
 * Written by Paul Hwang
 * File name: go_cluster_module.js
 */

module.exports = {
    malloc: function (cluster_mgr_val, topic_val, session_val) {
        return new clusterObject(cluster_mgr_val, topic_val, session_val);
    },
};

function clusterObject (cluster_mgr_val, topic_val, session_val) {
    "use strict";
    this.theClusterMgrObject = cluster_mgr_val;
    session_val.setClusterObject(this);

    this.init__ = function () {
        this.theSessionArray = [2];
        this.theSessionArray[0] = session_val;
        this.theSessionArrayLength = 1;

        this.theGoObject = this.goObjectMalloc();
        this.theReceiveQueue = this.utilObject().mallocQueue();
        this.theTransmitQueue = this.utilObject().mallocQueue();
        this.theNext = null;
        this.thePrev = null;
    };

    this.goObjectMalloc = function () {
        var go_module = require("./../go_modules/go_module.js")
        return go_module.malloc(this);
    },

    this.objectName = function () {
        return "clusterObject";
    };

    this.sessionObject = function () {
        return this.sessionArray(0);
    };

    this.goObject = function () {
        return this.theGoObject;
    };

    this.clusterMgrObject = function () {
        return this.theClusterMgrObject;
    };

    this.fabricObject = function () {
        return this.clusterMgrObject().fabricObject();
    };

    this.utilObject = function () {
        return this.clusterMgrObject().utilObject();
    };

    this.sessionArray = function (index_val) {
        return this.theSessionArray[index_val];
    };

    this.sessionArrayLength = function () {
        return this.theSessionArrayLength;
    };

    this.incrementSessionArrayLength = function () {
        this.theSessionArrayLength += 1;
    };

    this.prev = function () {
        return this.thePrev;
    };

    this.setPrev = function (val) {
        this.thePrev = val;
    };

    this.next = function () {
        return this.theNext;
    };

    this.setNext = function (val) {
        this.theNext = val;
    };

    this.receiveQueue = function () {
        return this.theReceiveQueue;
    };

    this.transmitQueue = function () {
        return this.theTransmitQueue;
    };

    this.addAdditionalSession = function (session_val) {
        this.theSessionArray[this.sessionArrayLength()] = session_val;
        this.incrementSessionArrayLength();
    };

    this.enqueueTransmitData = function (data_val) {
        this.debug(true, "enqueueTransmitData", data_val);
        this.transmitQueue().enQueue(data_val);
    };

    this.dequeueTransmitData = function () {
        var data = this.transmitQueue().deQueue();
        this.debug(true, "dequeueTransmitData", data);
        return data;
    };

    this.enqueueReceiveData = function (data_val) {
        this.debug(true, "enqueueReceiveData", data_val);
        this.receiveQueue().enQueue(data_val);
    };

    this.dequeueReceiveData = function () {
        var data = this.receiveQueue().deQueue();
        this.debug(true, "dequeueReceiveData", data);
        return data;
    };

    this.processTransmitData = function () {
        while (true) {
            var data = this.dequeueTransmitData();
            if (!data) {
                return;
            }

            var i = 0;
            while (i < this.sessionArrayLength()) {
                this.sessionArray(i).enqueueTransmitData(data);
                i += 1;
            }
        }
    };

    this.processSetupTopicData = function (json_data_val) {
        this.debug(true, "processSetupTopicData", "data=" + json_data_val);
        var topic_data = JSON.parse(json_data_val);
        if (topic_data.command === "config") {
            this.goObject().configObject().createConfig(topic_data.data);
        }
    };

    this.processReceiveData = function () {
        while (true) {
            var data = this.dequeueReceiveData();
            if (!data) {
                return;
            }
            this.receiveStringData(data);
        }
    };

    this.enqueAndPocessReceiveData = function (data_val) {
        this.debug(true, "enqueAndPocessReceiveData", data_val);
        this.enqueueReceiveData(data_val);
        this.processReceiveData();
    };

    this.receiveStringData = function (str_val) {
        this.goObject().portObject().receiveStringData(str_val);
    };

    this.debug = function (debug_val, str1_val, str2_val) {
        if (debug_val) {
            this.logit(str1_val, "==" + str2_val);
        }
    };

    this.logit = function (str1_val, str2_val) {
        this.clusterMgrObject().logit(this.objectName() + "." + str1_val, str2_val);
    };

    this.abend = function (str1_val, str2_val) {
        this.clusterMgrObject().abend(this.objectName() + "." + str1_val, str2_val);
    };

    this.init__();
}
<commit_msg>cluster<commit_after>/*
 * Copyrights phwang
 * Written by Paul Hwang
 * File name: go_cluster_module.js
 */

module.exports = {
    malloc: function (cluster_mgr_val, topic_val, session_val) {
        return new clusterObject(cluster_mgr_val, topic_val, session_val);
    },
};

function clusterObject (cluster_mgr_val, topic_val, session_val) {
    "use strict";
    this.theClusterMgrObject = cluster_mgr_val;
    session_val.setClusterObject(this);

    this.init__ = function () {
        this.theSessionArray = [2];
        this.theSessionArray[0] = session_val;
        this.theSessionArrayLength = 1;

        this.theGoObject = this.goObjectMalloc();
        this.theReceiveQueue = this.utilObject().mallocQueue();
        this.theTransmitQueue = this.utilObject().mallocQueue();
        this.theNext1 = null;
        this.thePrev = null;
    };

    this.goObjectMalloc = function () {
        var go_module = require("./../go_modules/go_module.js")
        return go_module.malloc(this);
    },

    this.objectName = function () {
        return "clusterObject";
    };

    this.sessionObject = function () {
        return this.sessionArray(0);
    };

    this.goObject = function () {
        return this.theGoObject;
    };

    this.clusterMgrObject = function () {
        return this.theClusterMgrObject;
    };

    this.fabricObject = function () {
        return this.clusterMgrObject().fabricObject();
    };

    this.utilObject = function () {
        return this.clusterMgrObject().utilObject();
    };

    this.sessionArray = function (index_val) {
        return this.theSessionArray[index_val];
    };

    this.sessionArrayLength = function () {
        return this.theSessionArrayLength;
    };

    this.incrementSessionArrayLength = function () {
        this.theSessionArrayLength += 1;
    };

    this.prev = function () {
        return this.thePrev;
    };

    this.setPrev = function (val) {
        this.thePrev = val;
    };

    this.next = function () {
        return this.theNext;
    };

    this.setNext = function (val) {
        this.theNext = val;
    };

    this.receiveQueue = function () {
        return this.theReceiveQueue;
    };

    this.transmitQueue = function () {
        return this.theTransmitQueue;
    };

    this.addAdditionalSession = function (session_val) {
        this.theSessionArray[this.sessionArrayLength()] = session_val;
        this.incrementSessionArrayLength();
    };

    this.enqueueTransmitData = function (data_val) {
        this.debug(true, "enqueueTransmitData", data_val);
        this.transmitQueue().enQueue(data_val);
    };

    this.dequeueTransmitData = function () {
        var data = this.transmitQueue().deQueue();
        this.debug(true, "dequeueTransmitData", data);
        return data;
    };

    this.enqueueReceiveData = function (data_val) {
        this.debug(true, "enqueueReceiveData", data_val);
        this.receiveQueue().enQueue(data_val);
    };

    this.dequeueReceiveData = function () {
        var data = this.receiveQueue().deQueue();
        this.debug(true, "dequeueReceiveData", data);
        return data;
    };

    this.processTransmitData = function () {
        while (true) {
            var data = this.dequeueTransmitData();
            if (!data) {
                return;
            }

            var i = 0;
            while (i < this.sessionArrayLength()) {
                this.sessionArray(i).enqueueTransmitData(data);
                i += 1;
            }
        }
    };

    this.processSetupTopicData = function (json_data_val) {
        this.debug(true, "processSetupTopicData", "data=" + json_data_val);
        var topic_data = JSON.parse(json_data_val);
        if (topic_data.command === "config") {
            this.goObject().configObject().createConfig(topic_data.data);
        }
    };

    this.processReceiveData = function () {
        while (true) {
            var data = this.dequeueReceiveData();
            if (!data) {
                return;
            }
            this.receiveStringData(data);
        }
    };

    this.enqueAndPocessReceiveData = function (data_val) {
        this.debug(true, "enqueAndPocessReceiveData", data_val);
        this.enqueueReceiveData(data_val);
        this.processReceiveData();
    };

    this.receiveStringData = function (str_val) {
        this.goObject().portObject().receiveStringData(str_val);
    };

    this.debug = function (debug_val, str1_val, str2_val) {
        if (debug_val) {
            this.logit(str1_val, "==" + str2_val);
        }
    };

    this.logit = function (str1_val, str2_val) {
        this.clusterMgrObject().logit(this.objectName() + "." + str1_val, str2_val);
    };

    this.abend = function (str1_val, str2_val) {
        this.clusterMgrObject().abend(this.objectName() + "." + str1_val, str2_val);
    };

    this.init__();
}
<|endoftext|>


<commit_before>/**
 * Copyright 2012-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"). You
 * may not use this file except in compliance with the License. A copy of
 * the License is located at
 *
 *     http://aws.amazon.com/apache2.0/
 *
 * or in the "license" file accompanying this file. This file is
 * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
 * ANY KIND, either express or implied. See the License for the specific
 * language governing permissions and limitations under the License.
 */

var AWS = require('../core');
var EventEmitter = require('events').EventEmitter;
require('../http');

/**
 * @api private
 */
AWS.XHRClient = AWS.util.inherit({
  handleRequest: function handleRequest(httpRequest, httpOptions, callback, errCallback) {
    var self = this;
    var endpoint = httpRequest.endpoint;
    var xhr = new XMLHttpRequest();
    var emitter = new EventEmitter();
    var href = endpoint.protocol + '//' + endpoint.host;
    if (endpoint.port != 80 && endpoint.port != 443) {
      href += ':' + endpoint.port;
    }
    href += httpRequest.path;

    if (httpOptions.timeout) {
      xhr.timeout = httpOptions.timeout;
    }

    xhr.addEventListener('readystatechange', function() {
      if (this.readyState === this.HEADERS_RECEIVED) {
        try { xhr.responseType = 'arraybuffer'; } catch (e) {}
        emitter.statusCode = xhr.status;
        emitter.headers = self.parseHeaders(xhr.getAllResponseHeaders());
        callback(emitter);
      } else if (this.readyState === this.DONE) {
        var buffer;
        if (xhr.responseType === 'arraybuffer' && xhr.response) {
          var ab = xhr.response;
          buffer = new Buffer(ab.byteLength);
          var view = new Uint8Array(ab);
          for (var i = 0; i < buffer.length; ++i) {
            buffer[i] = view[i];
          }
        }

        try {
          if (!buffer && typeof xhr.responseText === 'string') {
            buffer = new Buffer(xhr.responseText);
          }
        } catch (e) {}

        if (buffer) emitter.emit('data', buffer);
        emitter.emit('end');
      }
    }, false);
    xhr.addEventListener('timeout', function () {
      errCallback(AWS.util.error(new Error('Timeout'), {code: 'TimeoutError'}));
    }, false);
    xhr.addEventListener('error', function () {
      errCallback(new Error('Network Failure'));
    }, false);

    xhr.open(httpRequest.method, href, true);
    AWS.util.each(httpRequest.headers, function (key, value) {
      if (key !== 'Content-Length' && key !== 'User-Agent' && key !== 'Host') {
        xhr.setRequestHeader(key, value);
      }
    });

    if (httpRequest.body && typeof httpRequest.body.buffer === 'object') {
      xhr.send(httpRequest.body.buffer); // typed arrays sent as ArrayBuffer
    } else {
      xhr.send(httpRequest.body);
    }

    return emitter;
  },

  parseHeaders: function parseHeaders(rawHeaders) {
    var headers = {};
    AWS.util.arrayEach(rawHeaders.split(/\r?\n/), function (line) {
      var key = line.split(':', 1)[0];
      var value = line.substring(key.length + 2);
      headers[key] = value;
    });
    return headers;
  }
});

/**
 * @api private
 */
AWS.HttpClient.prototype = AWS.XHRClient.prototype;

/**
 * @api private
 */
AWS.HttpClient.streamsApiVersion = 1;
<commit_msg>Ignore empty header lines when parsing XHR headers<commit_after>/**
 * Copyright 2012-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"). You
 * may not use this file except in compliance with the License. A copy of
 * the License is located at
 *
 *     http://aws.amazon.com/apache2.0/
 *
 * or in the "license" file accompanying this file. This file is
 * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
 * ANY KIND, either express or implied. See the License for the specific
 * language governing permissions and limitations under the License.
 */

var AWS = require('../core');
var EventEmitter = require('events').EventEmitter;
require('../http');

/**
 * @api private
 */
AWS.XHRClient = AWS.util.inherit({
  handleRequest: function handleRequest(httpRequest, httpOptions, callback, errCallback) {
    var self = this;
    var endpoint = httpRequest.endpoint;
    var xhr = new XMLHttpRequest();
    var emitter = new EventEmitter();
    var href = endpoint.protocol + '//' + endpoint.host;
    if (endpoint.port != 80 && endpoint.port != 443) {
      href += ':' + endpoint.port;
    }
    href += httpRequest.path;

    if (httpOptions.timeout) {
      xhr.timeout = httpOptions.timeout;
    }

    xhr.addEventListener('readystatechange', function() {
      if (this.readyState === this.HEADERS_RECEIVED) {
        try { xhr.responseType = 'arraybuffer'; } catch (e) {}
        emitter.statusCode = xhr.status;
        emitter.headers = self.parseHeaders(xhr.getAllResponseHeaders());
        callback(emitter);
      } else if (this.readyState === this.DONE) {
        var buffer;
        if (xhr.responseType === 'arraybuffer' && xhr.response) {
          var ab = xhr.response;
          buffer = new Buffer(ab.byteLength);
          var view = new Uint8Array(ab);
          for (var i = 0; i < buffer.length; ++i) {
            buffer[i] = view[i];
          }
        }

        try {
          if (!buffer && typeof xhr.responseText === 'string') {
            buffer = new Buffer(xhr.responseText);
          }
        } catch (e) {}

        if (buffer) emitter.emit('data', buffer);
        emitter.emit('end');
      }
    }, false);
    xhr.addEventListener('timeout', function () {
      errCallback(AWS.util.error(new Error('Timeout'), {code: 'TimeoutError'}));
    }, false);
    xhr.addEventListener('error', function () {
      errCallback(new Error('Network Failure'));
    }, false);

    xhr.open(httpRequest.method, href, true);
    AWS.util.each(httpRequest.headers, function (key, value) {
      if (key !== 'Content-Length' && key !== 'User-Agent' && key !== 'Host') {
        xhr.setRequestHeader(key, value);
      }
    });

    if (httpRequest.body && typeof httpRequest.body.buffer === 'object') {
      xhr.send(httpRequest.body.buffer); // typed arrays sent as ArrayBuffer
    } else {
      xhr.send(httpRequest.body);
    }

    return emitter;
  },

  parseHeaders: function parseHeaders(rawHeaders) {
    var headers = {};
    AWS.util.arrayEach(rawHeaders.split(/\r?\n/), function (line) {
      var key = line.split(':', 1)[0];
      var value = line.substring(key.length + 2);
      if (key.length > 0) headers[key] = value;
    });
    return headers;
  }
});

/**
 * @api private
 */
AWS.HttpClient.prototype = AWS.XHRClient.prototype;

/**
 * @api private
 */
AWS.HttpClient.streamsApiVersion = 1;
<|endoftext|>


<commit_before>var assert = require('assert');
var forge = require('node-forge');
var fs = require('fs');
var path = require('path');
var crypto = require('crypto');
var pki = forge.pki;
var createSecureContext = require('tls').createSecureContext || crypto.createCredentials;
var util = require('../util');
var config = require('../config');

var CUR_VERSION = process.version;
var requiredVersion = parseInt(CUR_VERSION.slice(1), 10) >= 6;
var HTTPS_DIR = util.mkdir(path.join(config.getDataDir(), 'certs'));
var ROOT_NEW_KEY_FILE = path.join(HTTPS_DIR, 'root_new.key');
var ROOT_NEW_CRT_FILE = path.join(HTTPS_DIR, 'root_new.crt');
var useNewKey = fs.existsSync(ROOT_NEW_KEY_FILE) && fs.existsSync(ROOT_NEW_CRT_FILE);
var ROOT_KEY_FILE = useNewKey ? ROOT_NEW_KEY_FILE : path.join(HTTPS_DIR, 'root.key');
var ROOT_CRT_FILE = useNewKey ? ROOT_NEW_CRT_FILE : path.join(HTTPS_DIR, 'root.crt');
var customCertDir = config.certDir;
var customPairs = {};
var wildcardPairs = {};
var cachePairs = {};
var ILEGAL_CHAR_RE = /[^a-z\d-]/i;

var ROOT_KEY, ROOT_CRT;

if (config.ATS) {
  assert(requiredVersion, 'Enable ATS requires Node >= 6 (current: '
  + CUR_VERSION + '), access https://nodejs.org to install the latest version.');
}

if (!useNewKey && requiredVersion && !checkCertificate()) {
  try {
    fs.unlinkSync(ROOT_KEY_FILE);
    fs.unlinkSync(ROOT_CRT_FILE);
  } catch(e) {}
}

function checkCertificate() {
  try {
    var crt = pki.certificateFromPem(fs.readFileSync(ROOT_CRT_FILE));
    if (crt.publicKey.n.toString(2).length < 2048) {
      return false;
    }
    return /^whistle\.\d+$/.test(getCommonName(crt));
  } catch(e) {}
  return true;
}

function getCommonName(crt) {
  var attrs = crt.issuer && crt.issuer.attributes;
  if (Array.isArray(attrs)) {
    for (var i = 0, len = attrs.length; i < len; i++) {
      var attr = attrs[i];
      if (attr && attr.name === 'commonName') {
        return attr.value;
      }
    }
  }
  return '';
}

exports.getDomain = function(hostname) {
  if (getCertificate(hostname)) {
    return hostname;
  }
  var list = hostname.split('.');
  var prefix = list[0];
  list[0] = '*';
  var wildDomain = list.join('.');
  if (getCertificate(wildDomain)) {
    return wildDomain;
  }
  var len = list.length;
  if (len < 3) {
    return hostname;
  }
  if (len > 3 || ILEGAL_CHAR_RE.test(prefix) || list[2] === 'com') {
    return wildDomain;
  }
  return hostname;
};

function getCertificate(hostname) {
  return customPairs[hostname] || wildcardPairs[hostname] || cachePairs[hostname];
}

function createCertificate(hostname) {
  var cert = getCertificate(hostname);
  if (cert) {
    return cert;
  }
  var serialNumber = crypto.createHash('sha1')
    .update(hostname, 'binary').digest('hex');
  cert = createCert(pki.setRsaPublicKey(ROOT_KEY.n, ROOT_KEY.e), serialNumber);

  cert.setSubject([{
    name: 'commonName',
    value: hostname
  }]);

  cert.setIssuer(ROOT_CRT.subject.attributes);
  cert.setExtensions([ {
    name: 'subjectAltName',
    altNames: [{
      type: 2,
      value: hostname
    }]
  } ]);
  cert.sign(ROOT_KEY, forge.md.sha256.create());
  cert = cachePairs[hostname] = {
    key: pki.privateKeyToPem(ROOT_KEY),
    cert: pki.certificateToPem(cert)
  };
  return cert;
}

function loadCustomCerts() {
  if (!customCertDir) {
    return;
  }
  var certs = {};
  try {
    fs.readdirSync(customCertDir).forEach(function(name) {
      if (!/^([*_]\.)?(.+)\.(crt|key)$/.test(name)) {
        return;
      }
      var wildcard = RegExp.$1;
      var hostname = (wildcard ? '*.' : '') + RegExp.$2;
      var suffix = RegExp.$3;
      var cert = certs[hostname] = certs[hostname] || {};
      if (suffix === 'crt') {
        suffix = 'cert';
      }
      if (wildcard) {
        cert.wildcard = true;
      }
      try {
        cert[suffix] = fs.readFileSync(path.join(customCertDir, name), {encoding: 'utf8'});
      } catch(e) {}
    });
  } catch(e) {}
  var rootCA = certs.root;
  delete certs.root;
  if (rootCA && rootCA.key && rootCA.cert) {
    ROOT_KEY_FILE = path.join(customCertDir, 'root.key');
    ROOT_CRT_FILE = path.join(customCertDir, 'root.crt');
  }
  Object.keys(certs).forEach(function(hostname) {
    var cert = certs[hostname];
    if (!cert || !cert.key || !cert.cert) {
      return;
    }
    if (cert.wildcard) {
      wildcardPairs[hostname] = cert;
    } else {
      customPairs[hostname] = cert;
    }
  });
}

function createRootCA() {
  loadCustomCerts();
  if (ROOT_KEY && ROOT_CRT) {
    return;
  }
  var rootKey, rootCrt;
  try {
    ROOT_KEY = fs.readFileSync(ROOT_KEY_FILE);
    ROOT_CRT = fs.readFileSync(ROOT_CRT_FILE);
    rootKey = ROOT_KEY;
    rootCrt = ROOT_CRT;
  } catch (e) {
    ROOT_KEY = ROOT_CRT = null;
  }

  if (ROOT_KEY && ROOT_CRT && ROOT_KEY.length && ROOT_CRT.length) {
    ROOT_KEY = pki.privateKeyFromPem(ROOT_KEY);
    ROOT_CRT = pki.certificateFromPem(ROOT_CRT);
  } else {
    var cert = createCACert();
    ROOT_CRT = cert.cert;
    ROOT_KEY = cert.key;
    rootKey = pki.privateKeyToPem(ROOT_KEY);
    rootCrt = pki.certificateToPem(ROOT_CRT);
    fs.writeFileSync(ROOT_KEY_FILE, rootKey.toString());
    fs.writeFileSync(ROOT_CRT_FILE, rootCrt.toString());
  }

  try {
    exports.DEFAULT_CERT_CTX = createSecureContext({
      key: ROOT_KEY,
      cert: ROOT_CRT
    });
  } catch (e) {
    exports.DEFAULT_CERT_CTX = createSecureContext({
      key: rootKey,
      cert: rootCrt
    });
  }
}

function getRandom() {
  var random = Math.floor(Math.random() * 1000);
  if (random < 10) {
    return '00' + random;
  }
  if (random < 100) {
    return '0' + random;
  }
  return '' + random;
}

function createCACert() {
  var keys = pki.rsa.generateKeyPair(requiredVersion ? 2048 : 1024);
  var cert = createCert(keys.publicKey);
  var now = Date.now() + getRandom();
  var attrs = [ {
    name : 'commonName',
    value : 'whistle.' + now
  }, {
    name : 'countryName',
    value : 'CN'
  }, {
    shortName : 'ST',
    value : 'ZJ'
  }, {
    name : 'localityName',
    value : 'HZ'
  }, {
    name : 'organizationName',
    value : now + '.wproxy.org'
  }, {
    shortName : 'OU',
    value : 'wproxy.org'
  } ];

  cert.setSubject(attrs);
  cert.setIssuer(attrs);
  cert.setExtensions([ {
    name : 'basicConstraints',
    cA : true
  }, {
    name : 'keyUsage',
    keyCertSign : true,
    digitalSignature : true,
    nonRepudiation : true,
    keyEncipherment : true,
    dataEncipherment : true
  }, {
    name : 'extKeyUsage',
    serverAuth : true,
    clientAuth : true,
    codeSigning : true,
    emailProtection : true,
    timeStamping : true
  }, {
    name : 'nsCertType',
    client : true,
    server : true,
    email : true,
    objsign : true,
    sslCA : true,
    emailCA : true,
    objCA : true
  } ]);

  cert.sign(keys.privateKey, forge.md.sha256.create());

  return {
    key: keys.privateKey,
    cert: cert
  };
}

function createCert(publicKey, serialNumber) {
  var cert = pki.createCertificate();
  cert.publicKey = publicKey;
  cert.serialNumber = serialNumber || '01';
  var curYear = new Date().getFullYear();
  cert.validity.notBefore = new Date();
  cert.validity.notAfter = new Date();
  cert.validity.notBefore.setFullYear(curYear - 1);
  cert.validity.notAfter.setFullYear(curYear + 10);
  return cert;
}

function getRootCAFile() {
  return ROOT_CRT_FILE;
}

createRootCA();// 启动生成ca
exports.getRootCAFile = getRootCAFile;
exports.createCertificate = createCertificate;

<commit_msg>feat: Use wildcard certificates first<commit_after>var assert = require('assert');
var forge = require('node-forge');
var fs = require('fs');
var path = require('path');
var crypto = require('crypto');
var pki = forge.pki;
var createSecureContext = require('tls').createSecureContext || crypto.createCredentials;
var util = require('../util');
var config = require('../config');

var CUR_VERSION = process.version;
var requiredVersion = parseInt(CUR_VERSION.slice(1), 10) >= 6;
var HTTPS_DIR = util.mkdir(path.join(config.getDataDir(), 'certs'));
var ROOT_NEW_KEY_FILE = path.join(HTTPS_DIR, 'root_new.key');
var ROOT_NEW_CRT_FILE = path.join(HTTPS_DIR, 'root_new.crt');
var useNewKey = fs.existsSync(ROOT_NEW_KEY_FILE) && fs.existsSync(ROOT_NEW_CRT_FILE);
var ROOT_KEY_FILE = useNewKey ? ROOT_NEW_KEY_FILE : path.join(HTTPS_DIR, 'root.key');
var ROOT_CRT_FILE = useNewKey ? ROOT_NEW_CRT_FILE : path.join(HTTPS_DIR, 'root.crt');
var customCertDir = config.certDir;
var customPairs = {};
var wildcardPairs = {};
var cachePairs = {};
var ILEGAL_CHAR_RE = /[^a-z\d-]/i;

var ROOT_KEY, ROOT_CRT;

if (config.ATS) {
  assert(requiredVersion, 'Enable ATS requires Node >= 6 (current: '
  + CUR_VERSION + '), access https://nodejs.org to install the latest version.');
}

if (!useNewKey && requiredVersion && !checkCertificate()) {
  try {
    fs.unlinkSync(ROOT_KEY_FILE);
    fs.unlinkSync(ROOT_CRT_FILE);
  } catch(e) {}
}

function checkCertificate() {
  try {
    var crt = pki.certificateFromPem(fs.readFileSync(ROOT_CRT_FILE));
    if (crt.publicKey.n.toString(2).length < 2048) {
      return false;
    }
    return /^whistle\.\d+$/.test(getCommonName(crt));
  } catch(e) {}
  return true;
}

function getCommonName(crt) {
  var attrs = crt.issuer && crt.issuer.attributes;
  if (Array.isArray(attrs)) {
    for (var i = 0, len = attrs.length; i < len; i++) {
      var attr = attrs[i];
      if (attr && attr.name === 'commonName') {
        return attr.value;
      }
    }
  }
  return '';
}

exports.getDomain = function(hostname) {
  if (getCertificate(hostname)) {
    return hostname;
  }
  var list = hostname.split('.');
  var prefix = list[0];
  list[0] = '*';
  var wildDomain = list.join('.');
  if (getCertificate(wildDomain)) {
    return wildDomain;
  }
  var len = list.length;
  if (len < 3) {
    return hostname;
  }
  if (len > 3 || ILEGAL_CHAR_RE.test(prefix)
    || list[1].length > 3 || list[2] === 'com') {
    return wildDomain;
  }
  return hostname;
};

function getCertificate(hostname) {
  return customPairs[hostname] || wildcardPairs[hostname] || cachePairs[hostname];
}

function createCertificate(hostname) {
  var cert = getCertificate(hostname);
  if (cert) {
    return cert;
  }
  var serialNumber = crypto.createHash('sha1')
    .update(hostname, 'binary').digest('hex');
  cert = createCert(pki.setRsaPublicKey(ROOT_KEY.n, ROOT_KEY.e), serialNumber);

  cert.setSubject([{
    name: 'commonName',
    value: hostname
  }]);

  cert.setIssuer(ROOT_CRT.subject.attributes);
  cert.setExtensions([ {
    name: 'subjectAltName',
    altNames: [{
      type: 2,
      value: hostname
    }]
  } ]);
  cert.sign(ROOT_KEY, forge.md.sha256.create());
  cert = cachePairs[hostname] = {
    key: pki.privateKeyToPem(ROOT_KEY),
    cert: pki.certificateToPem(cert)
  };
  return cert;
}

function loadCustomCerts() {
  if (!customCertDir) {
    return;
  }
  var certs = {};
  try {
    fs.readdirSync(customCertDir).forEach(function(name) {
      if (!/^([*_]\.)?(.+)\.(crt|key)$/.test(name)) {
        return;
      }
      var wildcard = RegExp.$1;
      var hostname = (wildcard ? '*.' : '') + RegExp.$2;
      var suffix = RegExp.$3;
      var cert = certs[hostname] = certs[hostname] || {};
      if (suffix === 'crt') {
        suffix = 'cert';
      }
      if (wildcard) {
        cert.wildcard = true;
      }
      try {
        cert[suffix] = fs.readFileSync(path.join(customCertDir, name), {encoding: 'utf8'});
      } catch(e) {}
    });
  } catch(e) {}
  var rootCA = certs.root;
  delete certs.root;
  if (rootCA && rootCA.key && rootCA.cert) {
    ROOT_KEY_FILE = path.join(customCertDir, 'root.key');
    ROOT_CRT_FILE = path.join(customCertDir, 'root.crt');
  }
  Object.keys(certs).forEach(function(hostname) {
    var cert = certs[hostname];
    if (!cert || !cert.key || !cert.cert) {
      return;
    }
    if (cert.wildcard) {
      wildcardPairs[hostname] = cert;
    } else {
      customPairs[hostname] = cert;
    }
  });
}

function createRootCA() {
  loadCustomCerts();
  if (ROOT_KEY && ROOT_CRT) {
    return;
  }
  var rootKey, rootCrt;
  try {
    ROOT_KEY = fs.readFileSync(ROOT_KEY_FILE);
    ROOT_CRT = fs.readFileSync(ROOT_CRT_FILE);
    rootKey = ROOT_KEY;
    rootCrt = ROOT_CRT;
  } catch (e) {
    ROOT_KEY = ROOT_CRT = null;
  }

  if (ROOT_KEY && ROOT_CRT && ROOT_KEY.length && ROOT_CRT.length) {
    ROOT_KEY = pki.privateKeyFromPem(ROOT_KEY);
    ROOT_CRT = pki.certificateFromPem(ROOT_CRT);
  } else {
    var cert = createCACert();
    ROOT_CRT = cert.cert;
    ROOT_KEY = cert.key;
    rootKey = pki.privateKeyToPem(ROOT_KEY);
    rootCrt = pki.certificateToPem(ROOT_CRT);
    fs.writeFileSync(ROOT_KEY_FILE, rootKey.toString());
    fs.writeFileSync(ROOT_CRT_FILE, rootCrt.toString());
  }

  try {
    exports.DEFAULT_CERT_CTX = createSecureContext({
      key: ROOT_KEY,
      cert: ROOT_CRT
    });
  } catch (e) {
    exports.DEFAULT_CERT_CTX = createSecureContext({
      key: rootKey,
      cert: rootCrt
    });
  }
}

function getRandom() {
  var random = Math.floor(Math.random() * 1000);
  if (random < 10) {
    return '00' + random;
  }
  if (random < 100) {
    return '0' + random;
  }
  return '' + random;
}

function createCACert() {
  var keys = pki.rsa.generateKeyPair(requiredVersion ? 2048 : 1024);
  var cert = createCert(keys.publicKey);
  var now = Date.now() + getRandom();
  var attrs = [ {
    name : 'commonName',
    value : 'whistle.' + now
  }, {
    name : 'countryName',
    value : 'CN'
  }, {
    shortName : 'ST',
    value : 'ZJ'
  }, {
    name : 'localityName',
    value : 'HZ'
  }, {
    name : 'organizationName',
    value : now + '.wproxy.org'
  }, {
    shortName : 'OU',
    value : 'wproxy.org'
  } ];

  cert.setSubject(attrs);
  cert.setIssuer(attrs);
  cert.setExtensions([ {
    name : 'basicConstraints',
    cA : true
  }, {
    name : 'keyUsage',
    keyCertSign : true,
    digitalSignature : true,
    nonRepudiation : true,
    keyEncipherment : true,
    dataEncipherment : true
  }, {
    name : 'extKeyUsage',
    serverAuth : true,
    clientAuth : true,
    codeSigning : true,
    emailProtection : true,
    timeStamping : true
  }, {
    name : 'nsCertType',
    client : true,
    server : true,
    email : true,
    objsign : true,
    sslCA : true,
    emailCA : true,
    objCA : true
  } ]);

  cert.sign(keys.privateKey, forge.md.sha256.create());

  return {
    key: keys.privateKey,
    cert: cert
  };
}

function createCert(publicKey, serialNumber) {
  var cert = pki.createCertificate();
  cert.publicKey = publicKey;
  cert.serialNumber = serialNumber || '01';
  var curYear = new Date().getFullYear();
  cert.validity.notBefore = new Date();
  cert.validity.notAfter = new Date();
  cert.validity.notBefore.setFullYear(curYear - 1);
  cert.validity.notAfter.setFullYear(curYear + 10);
  return cert;
}

function getRootCAFile() {
  return ROOT_CRT_FILE;
}

createRootCA();// 启动生成ca
exports.getRootCAFile = getRootCAFile;
exports.createCertificate = createCertificate;

<|endoftext|>


<commit_before>/**
 * Pimcore
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://www.pimcore.org/license
 *
 * @copyright  Copyright (c) 2009-2010 elements.at New Media Solutions GmbH (http://www.elements.at)
 * @license    http://www.pimcore.org/license     New BSD License
 */

pimcore.registerNS("pimcore.settings.systemlog");
pimcore.settings.systemlog = Class.create({

    initialize: function () {

        this.isLoaded = false;

        this.getTabPanel();
    },

    activate: function () {
        var tabPanel = Ext.getCmp("pimcore_panel_tabs");
        tabPanel.activate("pimcore_systemlog");
    },

    getTabPanel: function () {

        this.stopButton = new Ext.Button({
            text: t("stop"),
            iconCls: "pimcore_icon_stop",
            handler: this.stop.bind(this)
        });

        this.startButton = new Ext.Button({
            text: t("auto_reload"),
            iconCls: "pimcore_icon_start",
            handler: this.start.bind(this),
            disabled: true
        });

        this.reloadButton = new Ext.Button({
            text: t("reload"),
            iconCls: "pimcore_icon_reload",
            handler: this.reload.bind(this)
        });

        if (!this.panel) {
            this.panel = new Ext.Panel({
                id: "pimcore_systemlog",
                title: t("systemlog"),
                iconCls: "pimcore_icon_systemlog",
                border: false,
                layout: "fit",
                closable:true,
                bodyStyle: "-webkit-overflow-scrolling:touch;",
                html: '',
                tbar: [this.startButton, this.stopButton, "-", this.reloadButton]
            });

            this.panel.on("resize", this.onLayoutResize.bind(this));

            var tabPanel = Ext.getCmp("pimcore_panel_tabs");
            tabPanel.add(this.panel);
            tabPanel.activate("pimcore_systemlog");

            this.panel.on("destroy", function () {
                clearInterval(this.interval);
                pimcore.globalmanager.remove("systemlog");
            }.bind(this));

            this.start();

            pimcore.layout.refresh();
        }

        return this.panel;
    },

    onLayoutResize: function (el, width, height, rWidth, rHeight) {
        this.setLayoutFrameDimensions(width, height);
    },

    setLayoutFrameDimensions: function (width, height) {
        Ext.get("pimcore_systemlog_frame").setStyle({
            height: (height - 50) + "px"
        });
    },

    isLoadedComplete: function () {
        this.isLoaded = true;
    },

    getScrollPosition: function() {
        var d = this.frame.document.getElementsByTagName("body")[0],
            doc = this.frame.document,
            body = doc.body,
            docElement = doc.documentElement,
            l,
            t,
            ret;

        if(d == doc || d == body){
            if(Ext.isIE && Ext.isStrict){
                l = docElement.scrollLeft;
                t = docElement.scrollTop;
            }else{
                l = this.frame.pageXOffset;
                t = this.frame.pageYOffset;
            }
            ret = {left: l || (body ? body.scrollLeft : 0), top: t || (body ? body.scrollTop : 0)};
        }else{
            ret = {left: d.scrollLeft, top: d.scrollTop};
        }
        return ret;
    },

    reload: function () {

        if(this.isLoaded == false) {
            return;
        }

        try {
            this.lastScrollposition = this.getScrollPosition();
        }
        catch (e1) {
            clearInterval(this.interval);
            console.log(e1);
        }

        try {
            this.isLoaded = false;
            var d = new Date();
            Ext.get("pimcore_systemlog_frame").dom.src = "/admin/settings/systemlog?_dc=" + d.getTime();
        }
        catch (e2) {
            clearInterval(this.interval);
            console.log(e2);
        }
    },

    start: function () {
        this.interval = window.setInterval(this.reload.bind(this),5000);
        this.startButton.disable();
        this.stopButton.enable();
    },

    stop: function () {
        clearInterval(this.interval);

        this.startButton.enable();
        this.stopButton.disable();
    }

});<commit_msg>syslog panel bugfix<commit_after>/**
 * Pimcore
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://www.pimcore.org/license
 *
 * @copyright  Copyright (c) 2009-2010 elements.at New Media Solutions GmbH (http://www.elements.at)
 * @license    http://www.pimcore.org/license     New BSD License
 */

pimcore.registerNS("pimcore.settings.systemlog");
pimcore.settings.systemlog = Class.create({

    initialize: function () {

        this.isLoaded = false;

        this.getTabPanel();
    },

    activate: function () {
        var tabPanel = Ext.getCmp("pimcore_panel_tabs");
        tabPanel.activate("pimcore_systemlog");
    },

    getTabPanel: function () {

        this.stopButton = new Ext.Button({
            text: t("stop"),
            iconCls: "pimcore_icon_stop",
            handler: this.stop.bind(this)
        });

        this.startButton = new Ext.Button({
            text: t("auto_reload"),
            iconCls: "pimcore_icon_start",
            handler: this.start.bind(this),
            disabled: true
        });

        this.reloadButton = new Ext.Button({
            text: t("reload"),
            iconCls: "pimcore_icon_reload",
            handler: this.reload.bind(this)
        });

        if (!this.panel) {
            this.panel = new Ext.Panel({
                id: "pimcore_systemlog",
                title: t("systemlog"),
                iconCls: "pimcore_icon_systemlog",
                border: false,
                layout: "fit",
                closable:true,
                bodyStyle: "-webkit-overflow-scrolling:touch;",
                html: '',
                tbar: [this.startButton, this.stopButton, "-", this.reloadButton]
            });

            this.panel.on("resize", this.onLayoutResize.bind(this));

            this.panel.on("afterrender", function () {
                this.load();
            }.bind(this));

            var tabPanel = Ext.getCmp("pimcore_panel_tabs");
            tabPanel.add(this.panel);
            tabPanel.activate("pimcore_systemlog");

            this.panel.on("destroy", function () {
                clearInterval(this.interval);
                pimcore.globalmanager.remove("systemlog");
            }.bind(this));

            this.start();

            pimcore.layout.refresh();
        }

        return this.panel;
    },

    onLayoutResize: function (el, width, height, rWidth, rHeight) {
        this.setLayoutFrameDimensions(width, height);
    },

    setLayoutFrameDimensions: function (width, height) {
        Ext.get("pimcore_systemlog_frame").setStyle({
            height: (height - 50) + "px"
        });
    },

    isLoadedComplete: function () {
        this.isLoaded = true;
    },

    getScrollPosition: function() {
        var d = this.frame.document.getElementsByTagName("body")[0],
            doc = this.frame.document,
            body = doc.body,
            docElement = doc.documentElement,
            l,
            t,
            ret;

        if(d == doc || d == body){
            if(Ext.isIE && Ext.isStrict){
                l = docElement.scrollLeft;
                t = docElement.scrollTop;
            }else{
                l = this.frame.pageXOffset;
                t = this.frame.pageYOffset;
            }
            ret = {left: l || (body ? body.scrollLeft : 0), top: t || (body ? body.scrollTop : 0)};
        }else{
            ret = {left: d.scrollLeft, top: d.scrollTop};
        }
        return ret;
    },

    reload: function () {

        if(this.isLoaded == false) {
            return;
        }

        try {
            this.lastScrollposition = this.getScrollPosition();
        }
        catch (e1) {
            clearInterval(this.interval);
            console.log(e1);
        }

        try {
            this.isLoaded = false;
            this.load();
        }
        catch (e2) {
            clearInterval(this.interval);
            console.log(e2);
        }
    },

    load: function () {
        var d = new Date();
        Ext.get("pimcore_systemlog_frame").dom.src = "/admin/settings/systemlog?_dc=" + d.getTime();
    },

    start: function () {
        this.interval = window.setInterval(this.reload.bind(this),5000);
        this.startButton.disable();
        this.stopButton.enable();
    },

    stop: function () {
        clearInterval(this.interval);

        this.startButton.enable();
        this.stopButton.disable();
    }

});<|endoftext|>