<commit_before>(function() {
  var Worker, events, http, log,
    bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
    extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
    hasProp = {}.hasOwnProperty;

  log = require("loglevel");

  http = require("http");
  url = require("url");
  events = require("events");

  /**
   * The Worker does most of the magic. It connects to elasticsearch, queries
   * data, analyzes the result, compares it to the expectation and raises an alarm
   * when appropriate.
   *
   * @class    Worker
   * @extends  events.EventEmitter
   */

  module.exports = Worker = (function(superClass) {
    extend(Worker, superClass);

    Worker.ResultCodes = {
      Success: {
        code: 0,
        label: "SUCCESS"
      },
      ValidationFailed: {
        code: 1,
        label: "ALARM_VALIDATION_FAILED"
      },
      NoResults: {
        code: 2,
        label: "ALARM_NO_RESULTS_RECEIVED"
      },
      NotFound: {
        code: 4,
        label: "ALARM_NOT_FOUND_404"
      },
      InvalidResponse: {
        code: 5,
        label: "ALARM_INVALID_RESPONSE"
      },
      ConnectionRefused: {
        code: 6,
        label: "ALARM_CONNECTION_REFUSED"
      },
      UnhandledError: {
        code: 99,
        label: "ALARM_UNHANDLED_ERROR"
      }
    };

    /**
     * Create a new Worker, prepare data, setup request options.
     *
     * @constructor
     * @param  id        {String}  identifies this individual Worker instance
     * @param  host      {String}  elasticsearch hostname to connect to
     * @param  port      {String}  elasticsearch port to connect to
     * @param  path      {String}  elasticsearch path (in form /{index}/{type})
     * @param  query     {Object}  valid elasticsearch query
     * @param  validator {ResultValidator} a validator object that takes the response and compares it against a given expectation
     */

    function Worker(id, host, port, path, query, validator) {

      if( url.parse(host).auth  ) {
		this.auth = url.parse(host).auth;
		this.host = url.parse(host).host;
		console.log( this.host,this.auth);
      } else {
	        this.host = host;
      }

      this.id = id;
      this.port = port;
      this.path = path;
      this.query = query;
      this.validator = validator;
      this.onError = bind(this.onError, this);
      this.onResponse = bind(this.onResponse, this);
      this.raiseAlarm = bind(this.raiseAlarm, this);
      this.start = bind(this.start, this);
      if (!this.id || !this.host || !this.port || !this.path || !this.query || !this.validator) {
        throw new Error("Worker.constructor: invalid number of options received: " + (JSON.stringify(arguments)));
      }
    }

    /**
     * Execute request and hand over control to onResponse callback.
     *
     * @method start
     */

    Worker.prototype.start = function() {
      var data, e, error1;
      data = JSON.stringify({
        query: this.query
      });
      this.options = {
        host: this.host,
        port: this.port,
        path: this.path + "/_search",
        method: "POST",
	auth: this.auth,
        headers: {
          "Content-Type": "application/json",
          "Content-Length": Buffer.byteLength(data)
        }
      };
      log.debug("Worker(" + this.id + ").sendESRequest: connecting to elasticsearch at: " + this.host + ":" + this.port + this.path);
      try {
        this.request = http.request(this.options, this.onResponse);
        this.request.on("error", this.onError);
        log.debug("Worker(" + this.id + ").sendESRequest: query data is: ", data);
        this.request.write(data);
        this.request.end();
        return true;
      } catch (error1) {
        e = error1;
        return log.error("Worker(" + this.id + ").start: unhandled error: " + e.message);
      }
    };

    /**
     * Gets passed ES response data (as object) and pre-validates the contents.
     * If data is invalid or result is empty an error is raised. Valid results
     * are handed over to the ResultValidator for further analysis. If any alarm
     * condition is met, raiseAlarm is called with the appropriate alarm.
     *
     * @method handleResponseData
     * @param  data  {Object}  result set as returned by ES
     */

    Worker.prototype.handleResponseData = function(data) {
      var numHits, rc, result;
      result = null;
      var alarms = [];
      rc = Worker.ResultCodes;
      if (!data || typeof data.hits === "undefined") {
        result = rc.InvalidResponse;
      } else {
        numHits = data.hits.total;
        log.debug("Worker(" + this.id + ").onResponse: query returned " + numHits + " hits");

        if (numHits === 0) {
          result = rc.NoResults;
	  return false;
        } else {
		// Iterate Validators
		this.validator.forEach(function(validator, i){
			if (!validator.validate(data)) {
		          	result = rc.ValidationFailed;
				alarms.push(i);
			        // return false;
		        } else {
		          result = rc.Success;
		        }
		});

	      if (result === rc.Success) {
	        return true;
	      } else {

		// Iterate Alarms
		for (idx = 0; idx < alarms.length; ++idx) {
		        this.raiseAlarm(result.label + ": " + (this.validator[idx].getMessage()));
		}
	        process.exitCode = result.code;
	        return false;
	      }
	}
      }

    };

    /**
     * Raise alarm - emits "alarm" event that can be handled by interested
     * listeners.
     *
     * @method raiseAlarm
     * @emits  alarm
     * @param  message {String}  error message
     * @param  data    {object}  any additional data
     */

    Worker.prototype.raiseAlarm = function(message) {
      log.debug("Worker(" + this.id + ").raiseAlarm: raising alarm: " + message);
      return this.emit("alarm", message, {
        name: this.id
      });
    };

    /**
     * http.request: success callback
     *
     * @method onResponse
     */

    Worker.prototype.onResponse = function(response) {
      var body;
      log.debug("Worker(" + this.id + ").onResponse: status is " + response.statusCode);
      if (response.statusCode === 200) {
        body = "";
        response.setEncoding("utf8");
        response.on("data", (function(_this) {
          return function(chunk) {
            return body += chunk;
          };
        })(this));
        return response.on("end", (function(_this) {
          return function(error) {
            var data, e, error1;
            log.debug("Worker(" + _this.id + ").onResponse: response was: ", body);
            try {
              data = JSON.parse(body);
            } catch (error1) {
              e = error1;
              log.error("Worker(" + _this.id + ").onResponse: failed to parse response data");
            }
            if (data) {
              return _this.handleResponseData(data);
            }
          };
        })(this));
      } else {
        this.raiseAlarm("" + Worker.ResultCodes.NotFound.label);
        process.exitCode = Worker.ResultCodes.NotFound.code;
        this.request.end();
        return process.exit();
      }
    };

    /**
     * http.request: error callback
     *
     * @method onError
     */

    Worker.prototype.onError = function(error) {
      if (error.code === "ECONNREFUSED") {
        log.error("ERROR: connection refused, please make sure elasticsearch is running and accessible under " + this.options.host + ":" + this.options.port);
        this.raiseAlarm("" + Worker.ResultCodes.ConnectionRefused.label);
        process.exitCode = Worker.ResultCodes.ConnectionRefused.code;
      } else {
        log.debug("Worker(" + this.id + ").onError: unhandled error: ", error);
        this.raiseAlarm(Worker.ResultCodes.UnhandledError.label + ": " + error);
        process.exitCode = Worker.ResultCodes.UnhandledError.code;
      }
      return this.request.end();
    };

    return Worker;

  })(events.EventEmitter);

}).call(this);
<commit_msg>get alarms from all validators<commit_after>(function() {
  var Worker, events, http, log,
    bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
    extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
    hasProp = {}.hasOwnProperty;

  log = require("loglevel");

  http = require("http");
  url = require("url");
  events = require("events");

  /**
   * The Worker does most of the magic. It connects to elasticsearch, queries
   * data, analyzes the result, compares it to the expectation and raises an alarm
   * when appropriate.
   *
   * @class    Worker
   * @extends  events.EventEmitter
   */

  module.exports = Worker = (function(superClass) {
    extend(Worker, superClass);

    Worker.ResultCodes = {
      Success: {
        code: 0,
        label: "SUCCESS"
      },
      ValidationFailed: {
        code: 1,
        label: "ALARM_VALIDATION_FAILED"
      },
      NoResults: {
        code: 2,
        label: "ALARM_NO_RESULTS_RECEIVED"
      },
      NotFound: {
        code: 4,
        label: "ALARM_NOT_FOUND_404"
      },
      InvalidResponse: {
        code: 5,
        label: "ALARM_INVALID_RESPONSE"
      },
      ConnectionRefused: {
        code: 6,
        label: "ALARM_CONNECTION_REFUSED"
      },
      UnhandledError: {
        code: 99,
        label: "ALARM_UNHANDLED_ERROR"
      }
    };

    /**
     * Create a new Worker, prepare data, setup request options.
     *
     * @constructor
     * @param  id        {String}  identifies this individual Worker instance
     * @param  host      {String}  elasticsearch hostname to connect to
     * @param  port      {String}  elasticsearch port to connect to
     * @param  path      {String}  elasticsearch path (in form /{index}/{type})
     * @param  query     {Object}  valid elasticsearch query
     * @param  validator {ResultValidator} a validator object that takes the response and compares it against a given expectation
     */

    function Worker(id, host, port, path, query, validator) {

      if( url.parse(host).auth  ) {
		this.auth = url.parse(host).auth;
		this.host = url.parse(host).host;
		console.log( this.host,this.auth);
      } else {
	        this.host = host;
      }

      this.id = id;
      this.port = port;
      this.path = path;
      this.query = query;
      this.validator = validator;
      this.onError = bind(this.onError, this);
      this.onResponse = bind(this.onResponse, this);
      this.raiseAlarm = bind(this.raiseAlarm, this);
      this.start = bind(this.start, this);
      if (!this.id || !this.host || !this.port || !this.path || !this.query || !this.validator) {
        throw new Error("Worker.constructor: invalid number of options received: " + (JSON.stringify(arguments)));
      }
    }

    /**
     * Execute request and hand over control to onResponse callback.
     *
     * @method start
     */

    Worker.prototype.start = function() {
      var data, e, error1;
      data = JSON.stringify({
        query: this.query
      });
      this.options = {
        host: this.host,
        port: this.port,
        path: this.path + "/_search",
        method: "POST",
	auth: this.auth,
        headers: {
          "Content-Type": "application/json",
          "Content-Length": Buffer.byteLength(data)
        }
      };
      log.debug("Worker(" + this.id + ").sendESRequest: connecting to elasticsearch at: " + this.host + ":" + this.port + this.path);
      try {
        this.request = http.request(this.options, this.onResponse);
        this.request.on("error", this.onError);
        log.debug("Worker(" + this.id + ").sendESRequest: query data is: ", data);
        this.request.write(data);
        this.request.end();
        return true;
      } catch (error1) {
        e = error1;
        return log.error("Worker(" + this.id + ").start: unhandled error: " + e.message);
      }
    };

    /**
     * Gets passed ES response data (as object) and pre-validates the contents.
     * If data is invalid or result is empty an error is raised. Valid results
     * are handed over to the ResultValidator for further analysis. If any alarm
     * condition is met, raiseAlarm is called with the appropriate alarm.
     *
     * @method handleResponseData
     * @param  data  {Object}  result set as returned by ES
     */

    Worker.prototype.handleResponseData = function(data) {
      var numHits, rc, result;
      result = null;
      var alarms = [];
      rc = Worker.ResultCodes;
      if (!data || typeof data.hits === "undefined") {
        result = rc.InvalidResponse;
      } else {
        numHits = data.hits.total;
        log.debug("Worker(" + this.id + ").onResponse: query returned " + numHits + " hits");

        if (numHits === 0) {
          result = rc.NoResults;
	  return false;
        } else {
		// Iterate Validators
		this.validator.forEach(function(validator, i){
			if (!validator.validate(data)) {
		          	result = rc.ValidationFailed;
				alarms.push(i);
			        // return false;
		        } else {
		          result = rc.Success;
		        }
		});

	      // if (result === rc.Success) {
	      if (alarms.length == 0) {
	        return true;
	      } else {

		// Iterate Alarms
		for (idx = 0; idx < alarms.length; ++idx) {
		        this.raiseAlarm(result.label + ": " + (this.validator[idx].getMessage()));
		}
	        process.exitCode = result.code;
	           return false;
	      }
	}
      }

    };

    /**
     * Raise alarm - emits "alarm" event that can be handled by interested
     * listeners.
     *
     * @method raiseAlarm
     * @emits  alarm
     * @param  message {String}  error message
     * @param  data    {object}  any additional data
     */

    Worker.prototype.raiseAlarm = function(message) {
      log.debug("Worker(" + this.id + ").raiseAlarm: raising alarm: " + message);
      return this.emit("alarm", message, {
        name: this.id
      });
    };

    /**
     * http.request: success callback
     *
     * @method onResponse
     */

    Worker.prototype.onResponse = function(response) {
      var body;
      log.debug("Worker(" + this.id + ").onResponse: status is " + response.statusCode);
      if (response.statusCode === 200) {
        body = "";
        response.setEncoding("utf8");
        response.on("data", (function(_this) {
          return function(chunk) {
            return body += chunk;
          };
        })(this));
        return response.on("end", (function(_this) {
          return function(error) {
            var data, e, error1;
            log.debug("Worker(" + _this.id + ").onResponse: response was: ", body);
            try {
              data = JSON.parse(body);
            } catch (error1) {
              e = error1;
              log.error("Worker(" + _this.id + ").onResponse: failed to parse response data");
            }
            if (data) {
              return _this.handleResponseData(data);
            }
          };
        })(this));
      } else {
        this.raiseAlarm("" + Worker.ResultCodes.NotFound.label);
        process.exitCode = Worker.ResultCodes.NotFound.code;
        this.request.end();
        return process.exit();
      }
    };

    /**
     * http.request: error callback
     *
     * @method onError
     */

    Worker.prototype.onError = function(error) {
      if (error.code === "ECONNREFUSED") {
        log.error("ERROR: connection refused, please make sure elasticsearch is running and accessible under " + this.options.host + ":" + this.options.port);
        this.raiseAlarm("" + Worker.ResultCodes.ConnectionRefused.label);
        process.exitCode = Worker.ResultCodes.ConnectionRefused.code;
      } else {
        log.debug("Worker(" + this.id + ").onError: unhandled error: ", error);
        this.raiseAlarm(Worker.ResultCodes.UnhandledError.label + ": " + error);
        process.exitCode = Worker.ResultCodes.UnhandledError.code;
      }
      return this.request.end();
    };

    return Worker;

  })(events.EventEmitter);

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


<commit_before>var css = require('../css/style.css');
var Delegator = require("dom-delegator");
Delegator();
function constructor(opts) {
    var router = require('./services/router.js');
    var dataService = require('./services/data');
    var confService = require('./services/config');
    var optionsService = require('./services/options');
    var revisionService = require('./services/revision');
    var templateService = require('./services/templates');
    var initializer = require('./services/initializer');
    var Api = require('./services/api');
    var mediator = require('mediatorjs');
    var h = require('virtual-dom/h');
    var mInstance = new mediator.Mediator();
    var data = new dataService(mInstance);
    var config = new confService(mInstance, data);

    var services = {
        data: data,
        config: config,
        mediator: mInstance,
        options: optionsService(mInstance),
        templates: templateService(),
        revision: revisionService(mInstance)
    };

    var states = {};

    // by default show this tab
    if(!opts.dataTab || opts.dataTab != false) {
        states.data = {
            title: 'Data',
            dependencies: function () {
                var that = {};
                that.import = require('./components/import.js')(services);
                return that;
            },
            template: function (dependencies) {
                return h('div', [dependencies.import.template()]);
            },
            destroy: function (dependencies) {
                dependencies.import.destroy()
            }
        }
    }
    // by default show this tab.

    if(opts.templatesTab != false) {
        states.templates = {
            title: 'Templates',
            dependencies: function () {
                var that = {};
                that.templateSelection = require('./components/templateSelection.js')(services);
                return that;
            },
            template: function (dependencies) {
                return h('div', [dependencies.templateSelection.template()]);
            }
        }
    }
    if (opts.customiseTab != false) {
        states.customise = {
            title: 'Customise',
            dependencies: function () {
                var that = {};
                that.configurate = require('./components/configure.js')(services);
                return that;
            },
            template: function (dependencies) {
                return h('div', [dependencies.configurate.template()]);
            },
            destroy: function (dependencies) {
                dependencies.configurate.destroy()
            }
        }
    }
    if (opts.debuggerTab != false) {
        states.debugger = {
            title: 'Debug',
            dependencies: function () {
                var that = {};
                that.debug = require('./components/debug.js')(services);
                return that;
            },
            template: function (dependencies) {
                return h('div', [dependencies.debug.template()]);
            }
        }
    }

    // initialise the application with given options
    initializer(opts, services);
    if (typeof opts.element !== 'undefined') {
        opts.element.className += ' ec';
        var mainRouter = new router(opts.element, states, services);
        if(opts.dataTab != false) {
            mainRouter.goToState('data');
        } else if(opts.templateTab != false) {
            mainRouter.goToState('templates');
        } else if(opts.customiseTab != false) {
            mainRouter.goToState('customise');
        }
    }

    return new Api(services);
}
module.exports = constructor;
window.ec = constructor;<commit_msg>make debug not visible by default<commit_after>var css = require('../css/style.css');
var Delegator = require("dom-delegator");
Delegator();
function constructor(opts) {
    var router = require('./services/router.js');
    var dataService = require('./services/data');
    var confService = require('./services/config');
    var optionsService = require('./services/options');
    var revisionService = require('./services/revision');
    var templateService = require('./services/templates');
    var initializer = require('./services/initializer');
    var Api = require('./services/api');
    var mediator = require('mediatorjs');
    var h = require('virtual-dom/h');
    var mInstance = new mediator.Mediator();
    var data = new dataService(mInstance);
    var config = new confService(mInstance, data);

    var services = {
        data: data,
        config: config,
        mediator: mInstance,
        options: optionsService(mInstance),
        templates: templateService(),
        revision: revisionService(mInstance)
    };

    var states = {};

    // by default show this tab
    if(!opts.dataTab || opts.dataTab != false) {
        states.data = {
            title: 'Data',
            dependencies: function () {
                var that = {};
                that.import = require('./components/import.js')(services);
                return that;
            },
            template: function (dependencies) {
                return h('div', [dependencies.import.template()]);
            },
            destroy: function (dependencies) {
                dependencies.import.destroy()
            }
        }
    }
    // by default show this tab.

    if(opts.templatesTab != false) {
        states.templates = {
            title: 'Templates',
            dependencies: function () {
                var that = {};
                that.templateSelection = require('./components/templateSelection.js')(services);
                return that;
            },
            template: function (dependencies) {
                return h('div', [dependencies.templateSelection.template()]);
            }
        }
    }
    if (opts.customiseTab != false) {
        states.customise = {
            title: 'Customise',
            dependencies: function () {
                var that = {};
                that.configurate = require('./components/configure.js')(services);
                return that;
            },
            template: function (dependencies) {
                return h('div', [dependencies.configurate.template()]);
            },
            destroy: function (dependencies) {
                dependencies.configurate.destroy()
            }
        }
    }
    if (opts.debuggerTab == true) {
        states.debugger = {
            title: 'Debug',
            dependencies: function () {
                var that = {};
                that.debug = require('./components/debug.js')(services);
                return that;
            },
            template: function (dependencies) {
                return h('div', [dependencies.debug.template()]);
            }
        }
    }

    // initialise the application with given options
    initializer(opts, services);
    if (typeof opts.element !== 'undefined') {
        opts.element.className += ' ec';
        var mainRouter = new router(opts.element, states, services);
        if(opts.dataTab != false) {
            mainRouter.goToState('data');
        } else if(opts.templateTab != false) {
            mainRouter.goToState('templates');
        } else if(opts.customiseTab != false) {
            mainRouter.goToState('customise');
        }
    }

    return new Api(services);
}
module.exports = constructor;
window.ec = constructor;<|endoftext|>


<commit_before>function(doc) {
	// !code _attachments/script/doc-helper.js

	if (doc.type != "document") { return; }

	var needed = false;
	if (!("sha1" in doc)) {
		needed = true;
	}
	if (docHelper.needsThumbnail(doc)) {
		needed = true;
	}

	if (needed) { emit(null, 1); }
}
<commit_msg>The code macro doesn't work in erica, so copying the code directly in<commit_after>function(doc) {
	if (doc.type != "document") { return; }

	var needed = false;
	if (!("sha1" in doc)) {
		needed = true;
	}
	if (!('thumbnail' in doc)) {
		needed = true;
	}

	if (needed) {
		emit(null, 1);
	}
}
<|endoftext|>


<commit_before>;(function(root, factory) {
  if (typeof define === "function" && define.amd) {
    define(["peasy"], factory);
  } else if (typeof module === "object" && module.exports) {
    module.exports = factory();
  } else {
    root.peasy = factory();
  }
}(this, function() {

  "use strict";

  // BUSINESS SERVICE

  var BusinessService = function(dataProxy) {
    if (this instanceof BusinessService) {
      this.dataProxy = dataProxy;
    } else {
      return new BusinessService(dataProxy);
    }
  };

  BusinessService.extend = function(options) {

    options = options || {};
    options.params = options.params || ['dataProxy'];
    options.functions = options.functions || {};

    var Extended = function() {
      var self = this;
      self.arguments = arguments;
      BusinessService.call(this);
      options.params.forEach(function(field, index) {
        self[field] = self.arguments[index];
      });
    };

    Extended.prototype = new BusinessService();
    var keys = Object.keys(BusinessService.prototype);
    Object.keys(options.functions).forEach(function(key) {
      if (keys.indexOf(key) === -1) {
        console.warn("The method: '" + key + "' is not an overridable method of BusinessService");
      }
      Extended.prototype[key] = options.functions[key];
    });

    function createCommand(options) {
      options = options || {};
      options.service = Extended;
      BusinessService.createCommand(options);
      return {
        createCommand: createCommand,
        service: Extended
      };
    }

    return {
      createCommand: createCommand,
      service: Extended
    };
  };

  BusinessService.createCommand = function(options) {

    function capitalize(value) {
      return value.charAt(0).toUpperCase() + value.slice(1);
    }

    options = options || {};

    if (!options.name) {
      throw new Error('A value for name must be supplied');
    }

    if (!options.service) {
      throw new Error('A function for the service argument must be supplied');
    }

    var name = options.name;
    var onInitialization = '_on' + capitalize(name) + 'Initialization';
    var getRules = '_getRulesFor' + capitalize(name);
    var onValidationSuccess = '_' + name.replace("Command", "");
    var commandParams = '_' + name + 'Params';
    var functions = options.functions || {};
    var service = options.service;

    service.prototype[onInitialization] = functions._onInitialization || function(context, done) {
      done();
    };

    service.prototype[getRules] = functions._getRules || function(context, done) {
      done(null, []);
    };

    service.prototype[onValidationSuccess] = functions._onValidationSuccess || function(context, done) {
      done();
    };

    service.prototype[commandParams] = options.params || [];

    service.prototype[name] = function() {
      var serviceInstance = this;

      var command = new Command({
        _onInitialization: function(context, done) {
          serviceInstance[onInitialization].call(this, context, done);
        },
        _getRules: function(context, done) {
          return serviceInstance[getRules].call(this, context, done);
        },
        _onValidationSuccess: function(context, done) {
          return serviceInstance[onValidationSuccess].call(this, context, done);
        }
      });

      var args = arguments;
      serviceInstance[commandParams].forEach(function(param, index) {
        command[param] = args[index];
      });
      Object.keys(serviceInstance).forEach((key) => {
        command[key] = serviceInstance[key];
      });
      return command;
    };

    return service;
  };

  Object.defineProperty(BusinessService.prototype, "constructor", {
    enumerable: false,
    value: BusinessService
  });

  BusinessService.createCommand({
    name: "getByIdCommand",
    service: BusinessService,
    params: ["id"],
    functions: {
      _onValidationSuccess: function(context, done) {
        this.dataProxy.getById(this.id, done);
      }
    }
  });

  BusinessService.createCommand({
    name: "getAllCommand",
    service: BusinessService,
    functions: {
      _onValidationSuccess: function(context, done) {
        this.dataProxy.getAll();
      }
    }
  });

  BusinessService.createCommand({
    name: "insertCommand",
    service: BusinessService,
    params: ["data"],
    functions: {
      _onValidationSuccess: function(context, done) {
        this.dataProxy.insert(this.data, done);
      }
    }
  });

  BusinessService.createCommand({
    name: "updateCommand",
    service: BusinessService,
    params: ["data"],
    functions: {
      _onValidationSuccess: function(context, done) {
        this.dataProxy.update(this.data, done);
      }
    }
  });

  BusinessService.createCommand({
    name: "destroyCommand",
    service: BusinessService,
    params: ["id"],
    functions: {
      _onValidationSuccess: function(context, done) {
        this.dataProxy.destroy(this.id, done);
      }
    }
  });

  // COMMAND

  var Command = function(callbacks) {
    callbacks = callbacks || {};
    if (this instanceof Command) {

      if (!this._onInitialization) { // allow for inheritance (ES6)
        this._onInitialization = callbacks._onInitialization || function(context, done) {
          done();
        };
      }

      if (!this._getRules) { // allow for inheritance (ES6)
        this._getRules = callbacks._getRules || function(context, done) {
          done(null, []);
        };
      }

      if (!this._onValidationSuccess) { // allow for inheritance (ES6)
        this._onValidationSuccess = callbacks._onValidationSuccess || function(context, done) {
          done();
        };
      }

    } else {
      return new Command(
        callbacks.onInitialization,
        callbacks.getRules,
        callbacks.onValidationSuccess
      );
    }
  };

  Command.prototype = {

    constructor: Command,

    execute: function(done) {
      var self = this;
      var context = {};

      self._onInitialization(context, function(err) {

        if(err) return done(err);

        self._getRules(context, function(err, rules) {

          if(err) return done(err);

          if (!Array.isArray(rules)) {
            rules = [rules];
          }

          new RulesValidator(rules).validate(function(err) {

            if (err) return done(err);

            var errors = rules.filter(function(rule) { return !rule.valid; })
                              .map(function(rule) { return rule.errors; });

            errors = [].concat.apply([], errors); // flatten array

            if (errors.length > 0)
              return done(null, new ExecutionResult(false, null, errors));

            try {
              self._onValidationSuccess(context, function(err, result) {
                if(err) return done(err);
                done(null, new ExecutionResult(true, result, null));
              });
            }
            catch(ex) {
              if (ex instanceof ServiceException) {
                done(null, new ExecutionResult(false, null, [{ association: ex.association, message: ex.message }]));
              } else {
                done(ex);
              }
            }
          });
        });
      });
    }
  };

  Command.extend = function(options) {
    options = options || {};
    var params = options.params || [];
    var functions = options.functions || {};

    var Extended = function() {
      var self = this;
      self.arguments = arguments;
      params.forEach(function(param, index) {
        self[param] = self.arguments[index];
      });
    };

    Extended.prototype = new Command();

    Extended.prototype._onInitialization = functions._onInitialization || function(context, done) {
      done();
    };

    Extended.prototype._getRules = functions._getRules || function(context, done) {
      done(null, []);
    };

    Extended.prototype._onValidationSuccess = functions._onValidationSuccess || function(context, done) {
      done();
    };

    return Extended;
  };

  // RULES VALIDATOR
  var RulesValidator = function(rules) {
    if (this instanceof RulesValidator) {
      this.rules = rules;
    } else {
      return new RulesValidator(rules);
    }
  };

  RulesValidator.prototype.validate = function(done) {
    var self = this;
    var counter = self.rules.length;

    function onRuleValidated(err) {
      if(err) return done(err);
      counter--;
      if (counter === 0) {
        done();
      }
    }

    if (self.rules.length > 0) {
      self.rules.forEach(function(rule) {
        rule.validate(onRuleValidated);
      });
    } else {
      done();
    }
  };

  // SERVICE EXCEPTION

  var ServiceException = function(message) {
    this.message = message;
  };

  ServiceException.prototype = new Error();

  // EXECUTION RESULT

  var ExecutionResult = function(success, value, errors) {
    if (this instanceof ExecutionResult) {
      this.success = success;
      this.value = value;
      this.errors = errors;
    } else {
      return new ExecutionResult(success, value, errors);
    }
  };

  // RULE

  var Rule = function(options) {
    if (this instanceof Rule) {
      options = options || {};
      this.association = options.association || null;
      this.errors = [];
      this.ifInvalidThenFn = null;
      this.ifValidThenFn = null;
      this.ifValidThenGetRulesFn = null;
      this.successors = [];
      this.valid = true;
    } else {
      return new Rule();
    }
  };

  Rule.ifAllValid = function(rules) {

    function thenGetRules(func) {
      var rule = new Rule();
      rule._onValidate = function(done) {
        done();
      };

      rule.successors = rules;
      rule.ifValidThenGetRulesFn = func;
      return rule;
    }

    return {
      thenGetRules: thenGetRules
    };

  };

  Rule.extend = function(options) {
    options = options || {};
    options.functions = options.functions || {};

    if (typeof options.functions._onValidate !== 'function') {
      throw new Error('An onValidate method needs to be supplied to execute!');
    }

    options.association = options.association || null;
    options.params = options.params || [];

    var Extended = function() {
      var self = this;
      self.arguments = arguments;
      Rule.call(self, { association: options.association });
      options.params.forEach(function(field, index) {
        self[field] = self.arguments[index];
      });
    };

    Extended.prototype = new Rule();
    Extended.prototype._onValidate = options.functions._onValidate;

    return Extended;
  };

  Rule.prototype = {

    constructor: Rule,

    _invalidate: function(errors) {
      var self = this;
      this.valid = false;
      if (!Array.isArray(errors)) {
        errors = [errors];
      }
      errors.forEach(function(err) {
        if (typeof err === "string") {
          self.errors.push({ association: self.association, message: err });
        } else {
          self.errors.push(err);
        }
      });
    },

    _onValidate: function(done) {
    },

    validate: function(done) {
      var self = this;
      self.errors = [];

      this._onValidate(function(err) {
        if (err) return done(err);
        if (self.valid) {
          if (self.ifValidThenFn) {
            self.ifValidThenFn();
          }
          if (self.successors.length > 0) {
            new RulesValidator(self.successors).validate(function(err) {
              if (err) return done(err);
              invalidate(self).ifAnyInvalid(self.successors);
              if (self.ifValidThenGetRulesFn) {
                return invokeNextRules(self, self.successors, done);
              }
              done();
            });
            return;
          } else {
            if (self.ifValidThenGetRulesFn) {
              return invokeNextRules(self, self.successors, done);
            }
          }
        } else {
          if (self.ifInvalidThenFn) {
            self.ifInvalidThenFn();
          }
        }
        done();
      });

      function invokeNextRules(rule, rules, done) {
        var failedRules = rules.filter(function(rule) { return !rule.valid; });
        if (failedRules.length === 0) {
          rule.ifValidThenGetRulesFn(function(err, result) {
            if (!Array.isArray(result)) {
              result = [result];
            }
            new RulesValidator(result).validate(function(err) {
              if (err) return done(err);
              invalidate(rule).ifAnyInvalid(result);
              done();
            });
          });
        } else {
          done();
        }
      }

      function invalidate(rule) {

        function ifAnyInvalid(rules) {
          rules.filter(function(r) { return !r.valid; })
               .forEach(function(r) {
                 rule._invalidate(r.errors);
               });
        }

        return { ifAnyInvalid: ifAnyInvalid };
      }
    },

    ifValidThenValidate: function(rules) {
      if (!Array.isArray(rules)) {
        rules = [rules];
      }
      this.successors = rules;
      return this;
    },

    ifValidThenExecute: function(funcToExecute) {
      this.ifValidThenFn = funcToExecute;
      return this;
    },

    ifInvalidThenExecute: function(funcToExecute) {
      this.ifInvalidThenFn = funcToExecute;
      return this;
    },

    ifValidThenGetRules: function(funcToExecute) {
      this.ifValidThenGetRulesFn = funcToExecute;
      return this;
    }

  };

  // PEASY JS

  return {
    BusinessService: BusinessService,
    Command: Command,
    ExecutionResult: ExecutionResult,
    Rule: Rule,
    ServiceException: ServiceException
  };

}));

<commit_msg>pass callback to dataProxy.getAll in BusinessService<commit_after>;(function(root, factory) {
  if (typeof define === "function" && define.amd) {
    define(["peasy"], factory);
  } else if (typeof module === "object" && module.exports) {
    module.exports = factory();
  } else {
    root.peasy = factory();
  }
}(this, function() {

  "use strict";

  // BUSINESS SERVICE

  var BusinessService = function(dataProxy) {
    if (this instanceof BusinessService) {
      this.dataProxy = dataProxy;
    } else {
      return new BusinessService(dataProxy);
    }
  };

  BusinessService.extendService = function(service, options) {
    options.service = service;
    return BusinessService.extend(options);
  }

  BusinessService.extend = function(options) {

    options = options || {};
    options.params = options.params || ['dataProxy'];
    options.functions = options.functions || {};

    var Extended = options.service || function() {
      var self = this;
      self.arguments = arguments;
      BusinessService.call(this);
      options.params.forEach(function(field, index) {
        self[field] = self.arguments[index];
      });
    };

    var service = options.service || BusinessService;
    Extended.prototype = new service();
    var keys = Object.keys(BusinessService.prototype);
    Object.keys(options.functions).forEach(function(key) {
      if (keys.indexOf(key) === -1) {
        console.warn("The method: '" + key + "' is not an overridable method of BusinessService");
      }
      Extended.prototype[key] = options.functions[key];
    });

    function createCommand(options) {
      options = options || {};
      options.service = Extended;
      BusinessService.createCommand(options);
      return {
        createCommand: createCommand,
        service: Extended
      };
    }

    return {
      createCommand: createCommand,
      service: Extended
    };
  };

  BusinessService.createCommand = function(options) {

    function capitalize(value) {
      return value.charAt(0).toUpperCase() + value.slice(1);
    }

    options = options || {};

    if (!options.name) {
      throw new Error('A value for name must be supplied');
    }

    if (!options.service) {
      throw new Error('A function for the service argument must be supplied');
    }

    var name = options.name;
    var onInitialization = '_on' + capitalize(name) + 'Initialization';
    var getRules = '_getRulesFor' + capitalize(name);
    var onValidationSuccess = '_' + name.replace("Command", "");
    var commandParams = '_' + name + 'Params';
    var functions = options.functions || {};
    var service = options.service;

    service.prototype[onInitialization] = functions._onInitialization || function(context, done) {
      done();
    };

    service.prototype[getRules] = functions._getRules || function(context, done) {
      done(null, []);
    };

    service.prototype[onValidationSuccess] = functions._onValidationSuccess || function(context, done) {
      done();
    };

    service.prototype[commandParams] = options.params || [];

    service.prototype[name] = function() {
      var serviceInstance = this;

      var command = new Command({
        _onInitialization: function(context, done) {
          serviceInstance[onInitialization].call(this, context, done);
        },
        _getRules: function(context, done) {
          return serviceInstance[getRules].call(this, context, done);
        },
        _onValidationSuccess: function(context, done) {
          return serviceInstance[onValidationSuccess].call(this, context, done);
        }
      });

      var args = arguments;
      serviceInstance[commandParams].forEach(function(param, index) {
        command[param] = args[index];
      });
      Object.keys(serviceInstance).forEach((key) => {
        command[key] = serviceInstance[key];
      });
      return command;
    };

    return service;
  };

  Object.defineProperty(BusinessService.prototype, "constructor", {
    enumerable: false,
    value: BusinessService
  });

  BusinessService.createCommand({
    name: "getByIdCommand",
    service: BusinessService,
    params: ["id"],
    functions: {
      _onValidationSuccess: function(context, done) {
        this.dataProxy.getById(this.id, done);
      }
    }
  });

  BusinessService.createCommand({
    name: "getAllCommand",
    service: BusinessService,
    functions: {
      _onValidationSuccess: function(context, done) {
        this.dataProxy.getAll(done);
      }
    }
  });

  BusinessService.createCommand({
    name: "insertCommand",
    service: BusinessService,
    params: ["data"],
    functions: {
      _onValidationSuccess: function(context, done) {
        this.dataProxy.insert(this.data, done);
      }
    }
  });

  BusinessService.createCommand({
    name: "updateCommand",
    service: BusinessService,
    params: ["data"],
    functions: {
      _onValidationSuccess: function(context, done) {
        this.dataProxy.update(this.data, done);
      }
    }
  });

  BusinessService.createCommand({
    name: "destroyCommand",
    service: BusinessService,
    params: ["id"],
    functions: {
      _onValidationSuccess: function(context, done) {
        this.dataProxy.destroy(this.id, done);
      }
    }
  });

  // COMMAND

  var Command = function(callbacks) {
    callbacks = callbacks || {};
    if (this instanceof Command) {

      if (!this._onInitialization) { // allow for inheritance (ES6)
        this._onInitialization = callbacks._onInitialization || function(context, done) {
          done();
        };
      }

      if (!this._getRules) { // allow for inheritance (ES6)
        this._getRules = callbacks._getRules || function(context, done) {
          done(null, []);
        };
      }

      if (!this._onValidationSuccess) { // allow for inheritance (ES6)
        this._onValidationSuccess = callbacks._onValidationSuccess || function(context, done) {
          done();
        };
      }

    } else {
      return new Command(
        callbacks.onInitialization,
        callbacks.getRules,
        callbacks.onValidationSuccess
      );
    }
  };

  Command.prototype = {

    constructor: Command,

    execute: function(done) {
      var self = this;
      var context = {};

      self._onInitialization(context, function(err) {

        if(err) return done(err);

        self._getRules(context, function(err, rules) {

          if(err) return done(err);

          if (!Array.isArray(rules)) {
            rules = [rules];
          }

          new RulesValidator(rules).validate(function(err) {

            if (err) return done(err);

            var errors = rules.filter(function(rule) { return !rule.valid; })
                              .map(function(rule) { return rule.errors; });

            errors = [].concat.apply([], errors); // flatten array

            if (errors.length > 0)
              return done(null, new ExecutionResult(false, null, errors));

            try {
              self._onValidationSuccess(context, function(err, result) {
                if(err) return done(err);
                done(null, new ExecutionResult(true, result, null));
              });
            }
            catch(ex) {
              if (ex instanceof ServiceException) {
                done(null, new ExecutionResult(false, null, [{ association: ex.association, message: ex.message }]));
              } else {
                done(ex);
              }
            }
          });
        });
      });
    }
  };

  Command.extend = function(options) {
    options = options || {};
    var params = options.params || [];
    var functions = options.functions || {};

    var Extended = function() {
      var self = this;
      self.arguments = arguments;
      params.forEach(function(param, index) {
        self[param] = self.arguments[index];
      });
    };

    Extended.prototype = new Command();

    Extended.prototype._onInitialization = functions._onInitialization || function(context, done) {
      done();
    };

    Extended.prototype._getRules = functions._getRules || function(context, done) {
      done(null, []);
    };

    Extended.prototype._onValidationSuccess = functions._onValidationSuccess || function(context, done) {
      done();
    };

    return Extended;
  };

  // RULES VALIDATOR
  var RulesValidator = function(rules) {
    if (this instanceof RulesValidator) {
      this.rules = rules;
    } else {
      return new RulesValidator(rules);
    }
  };

  RulesValidator.prototype.validate = function(done) {
    var self = this;
    var counter = self.rules.length;

    function onRuleValidated(err) {
      if(err) return done(err);
      counter--;
      if (counter === 0) {
        done();
      }
    }

    if (self.rules.length > 0) {
      self.rules.forEach(function(rule) {
        rule.validate(onRuleValidated);
      });
    } else {
      done();
    }
  };

  // SERVICE EXCEPTION

  var ServiceException = function(message) {
    this.message = message;
  };

  ServiceException.prototype = new Error();

  // EXECUTION RESULT

  var ExecutionResult = function(success, value, errors) {
    if (this instanceof ExecutionResult) {
      this.success = success;
      this.value = value;
      this.errors = errors;
    } else {
      return new ExecutionResult(success, value, errors);
    }
  };

  // RULE

  var Rule = function(options) {
    if (this instanceof Rule) {
      options = options || {};
      this.association = options.association || null;
      this.errors = [];
      this.ifInvalidThenFn = null;
      this.ifValidThenFn = null;
      this.ifValidThenGetRulesFn = null;
      this.successors = [];
      this.valid = true;
    } else {
      return new Rule();
    }
  };

  Rule.ifAllValid = function(rules) {

    function thenGetRules(func) {
      var rule = new Rule();
      rule._onValidate = function(done) {
        done();
      };

      rule.successors = rules;
      rule.ifValidThenGetRulesFn = func;
      return rule;
    }

    return {
      thenGetRules: thenGetRules
    };

  };

  Rule.extend = function(options) {
    options = options || {};
    options.functions = options.functions || {};

    if (typeof options.functions._onValidate !== 'function') {
      throw new Error('An onValidate method needs to be supplied to execute!');
    }

    options.association = options.association || null;
    options.params = options.params || [];

    var Extended = function() {
      var self = this;
      self.arguments = arguments;
      Rule.call(self, { association: options.association });
      options.params.forEach(function(field, index) {
        self[field] = self.arguments[index];
      });
    };

    Extended.prototype = new Rule();
    Extended.prototype._onValidate = options.functions._onValidate;

    return Extended;
  };

  Rule.prototype = {

    constructor: Rule,

    _invalidate: function(errors) {
      var self = this;
      this.valid = false;
      if (!Array.isArray(errors)) {
        errors = [errors];
      }
      errors.forEach(function(err) {
        if (typeof err === "string") {
          self.errors.push({ association: self.association, message: err });
        } else {
          self.errors.push(err);
        }
      });
    },

    _onValidate: function(done) {
    },

    validate: function(done) {
      var self = this;
      self.errors = [];

      this._onValidate(function(err) {
        if (err) return done(err);
        if (self.valid) {
          if (self.ifValidThenFn) {
            self.ifValidThenFn();
          }
          if (self.successors.length > 0) {
            new RulesValidator(self.successors).validate(function(err) {
              if (err) return done(err);
              invalidate(self).ifAnyInvalid(self.successors);
              if (self.ifValidThenGetRulesFn) {
                return invokeNextRules(self, self.successors, done);
              }
              done();
            });
            return;
          } else {
            if (self.ifValidThenGetRulesFn) {
              return invokeNextRules(self, self.successors, done);
            }
          }
        } else {
          if (self.ifInvalidThenFn) {
            self.ifInvalidThenFn();
          }
        }
        done();
      });

      function invokeNextRules(rule, rules, done) {
        var failedRules = rules.filter(function(rule) { return !rule.valid; });
        if (failedRules.length === 0) {
          rule.ifValidThenGetRulesFn(function(err, result) {
            if (!Array.isArray(result)) {
              result = [result];
            }
            new RulesValidator(result).validate(function(err) {
              if (err) return done(err);
              invalidate(rule).ifAnyInvalid(result);
              done();
            });
          });
        } else {
          done();
        }
      }

      function invalidate(rule) {

        function ifAnyInvalid(rules) {
          rules.filter(function(r) { return !r.valid; })
               .forEach(function(r) {
                 rule._invalidate(r.errors);
               });
        }

        return { ifAnyInvalid: ifAnyInvalid };
      }
    },

    ifValidThenValidate: function(rules) {
      if (!Array.isArray(rules)) {
        rules = [rules];
      }
      this.successors = rules;
      return this;
    },

    ifValidThenExecute: function(funcToExecute) {
      this.ifValidThenFn = funcToExecute;
      return this;
    },

    ifInvalidThenExecute: function(funcToExecute) {
      this.ifInvalidThenFn = funcToExecute;
      return this;
    },

    ifValidThenGetRules: function(funcToExecute) {
      this.ifValidThenGetRulesFn = funcToExecute;
      return this;
    }

  };

  // PEASY JS

  return {
    BusinessService: BusinessService,
    Command: Command,
    ExecutionResult: ExecutionResult,
    Rule: Rule,
    ServiceException: ServiceException
  };

}));

<|endoftext|>


<commit_before>/* router.js */

function Router(routes){
	this.routes = routes;
}

Router.prototype.addRoute = function(newRoutes){
	for(k in newRoutes)
		this.routes[k] = newRoutes[k];
}

Router.prototype.route = function(uri){
	for(r in this.routes){
		var patt = new RegExp(r,"i");
		var result = uri.match(patt);
		if(result){
			print(result);
			break;
		}

	}
}
<commit_msg>Update router.js<commit_after>/* router.js */

function Router(routes){
	this.routes = routes;
}

Router.prototype.addRoute = function(newRoutes){
	for(k in newRoutes)
		this.routes[k] = newRoutes[k];
}

Router.prototype.route = function(uri){
	for(r in this.routes){
		var patt = new RegExp(r,"i");
		var result = uri.match(patt);
		if(result){
			return result;
			break;
		}

	}
}
<|endoftext|>


<commit_before>/**
 * Copyright (c) 2014 and beyond Dwayne Charrington
 * Email: dwaynecharrington (at) gmail (dot) com
 * Twitter: abolitionof_
 * Licensed under MIT
 * @author Dwayne Charrington
 * @version 1.0
 */

(function($, window, document, History, undefined) {

    // Events trigger

    // While loading: wpAjax.loading: (event, url)
    // If failed: wpAjax.failed: (event, url)
    // Content loaded: wpAjax.loaded: (event, data, url)
    // Content loaded and populated: wpAjax.complete: (event, contentEl)

    /*
        Example:

        //To configure wpAjax:
        wpAjax.configure({
            content: "#content" // Element with our content which will be AJAX''d out
        });

        // Call this from within a click event
        wpAjax.trigger("http://www.someurl.com");

        // Request is currently happening (with current URL and new URL)
        $(document).on("wpAjax.loading", function(event) {
            // Methods are;
            // event.previousUrl
            // event.previousSlug
            // event.previousID
            // event.url
            // event.slug
            // event.ID
        });

        // All data has loaded
        $(document).on("wpAjax.loaded", function(event) {
            // Methods are;
            // event.previousUrl
            // event.previousSlug
            // event.previousID
            // event.content
            // event.url
            // event.slug
            // event.ID
        });

        $(document).on("wpAjax.failed", function(event) {
            // Methods are;
            // event.url
        });

        // All data has been populated the content element returned
        $(document).on("wpAjax.complete", function(event) {
            // Methods are;
            // event.contentEl
            // event.url
            // event.slug
            // event.ID
        });
    */

    var currentRequest = null,
         previousUrl = "",
         previousSlug = "",
         previousID = 0,
         requestCount = 0;

    // Main WP Ajax object
    var wpAjax = {};

    // Options
    var settings = {
            content: '#content',      // This is our container
            cacheRequests: true,  // Use HTML5 localStorage to cache pages?
            cacheExpiry: 1,          // Time in hours cached items should be cached for
            waitForImages: true,   // Wait for images to load before loading a page?
            debug: false,              // Debug mode shows console messages if true
            testMode: false           // Modifies certain methods so we can test them
        },
        o = settings;

    // These two elements never disappear and are always consistent
    var $body    = $("body");
    var $wpvars = $("wpvars");
    var $content = $(o.content);

    // Statechange when the URL changes, we roll
    $(window).off("statechange").on("statechange", function() {
        var State = History.getState();

        log("Event.statechange: HTML5 History statechange event trigger with URL: "+State.url);

        if (previousUrl !== State.url) {
            log("Event.statechange: Calling the wpAjax.loadPage function with State.url as its parameter");
            wpAjax.loadPage(State.url);
        } else {
            log("Event.statechange: User is already on the requested page to load. No request will be made.");
        }
    });

    // Allows us to configure wpAjax
    wpAjax.configure = function(options) {
        log("configure: Setting options for Wpajax");
        $.extend(settings, options);
        return this;
    };

    // Return the configuration object
    wpAjax.getConfiguration = function() {
        return settings;
    };

    // Helper function for checking the current URL
    wpAjax.getCurrentUrl = function() {
        log("getCurrentUrl: Getting the current browser address URL");
        return window.location.href;
    };

    // Get all vars supplied via the body classes
    wpAjax.getPluginClassVars = function() {
        var bodyClasses = $("body").attr("class");
        var returnObj = {};

        if (bodyClasses) {
            var classesArr  = bodyClasses.split(" ");

            var pageNameArr  = classesArr;
            var pageIDArr       = classesArr;

            for (var i = 0, len = classesArr.length; i < len; ++i) {
                var pointer = classesArr[i];

                if (pointer) {
                    if (pointer.indexOf("wpajax-pagename-") === -1) {
                        pageNameArr.splice(i, 1);
                    }
                    if (pointer.indexOf("wpajax-pageid-") === -1) {
                        pageIDArr.splice(i, 1);
                    }
                }
            }
        }
    };

    // Trigger a page load
    wpAjax.trigger = function(url) {
        log("trigger: Calling History.pushState which will trigger a statechange");

        wpAjax.getPluginClassVars();

        // Store current URL as the previous URL
        previousUrl = wpAjax.getCurrentUrl();

        wpAjax.getTitle(url, function(title) {
            History.pushState({}, title, url);
        });
    };

    // Have we reached our page limit
    wpAjax.pageLimitReached = function() {
        return (wpvars.max == wpvars.paged);
    }

    // What is the current page we are on
    wpAjax.getCurrentPageNumber = function() {
        return wpvars.paged;
    }

    // Get the maximum number of pages in our results
    wpAjax.getMaxPages = function() {
        return wpvars.max;
    }

    // Load page function
    wpAjax.loadPage = function(url) {

        log("loadPage: No other request is taking place, we are good to go");

        if (!o.testMode) {
            // Apply a loading class to the body
            $("body").addClass("loading-page");

            var loadingEvent = jQuery.Event("wpAjax.loading", {
                previousUrl: previousUrl,
                previousSlug: previousSlug,
                previousID: previousID,
                url: url
            });

            // Trigger loading event
            $(document).trigger(loadingEvent);

            // Before content is loaded in, fade out the old content
            wpAjax.fadeOutContent(function() {

               // Perform our AJAX request
                wpAjax.doRequest(url, function(data) {
                    wpAjax.processRequest(data, url);
                }, function() {

                    if (!o.testMode) {
                        wpAjax.fadeInContent();

                        log("loadPage: Called doRequest and the request failed. Throwing a failed event on document");

                        var failedEvent = jQuery.Event("wpAjax.failed", {
                            url: url
                        });

                        // Trigger failed event
                        $(document).trigger(failedEvent);
                    }
                });

            });

            log("loadPage: Loading class applied to body, loading event fired and content element faded out");
        }

    };

    // Fade out the content area
    wpAjax.fadeOutContent = function(callback) {
        log("fadeOutContent: Animating content element out");

        if (arguments.length == 0) callback = function() {};

        $content.animate({opacity:0}, 800, callback);
    };

    // Fade in the content area
    wpAjax.fadeInContent = function(callback) {
        log("fadeInContent: Animating content element in");

        if (arguments.length == 0) callback = function() {};

        $content.animate({opacity:1}, 800, callback);
    };

    // Performs an AJAX request to get the page title
    // Also has the advantage of pre-fetching the page
    // for us as well.
    wpAjax.getTitle = function(url, callback) {
        var title = "";

        log("getTitle: Calling wpAjax.doRequest now to get the title");

        wpAjax.doRequest(url, function(data) {
            title = $(data).filter("title").text();
            log("getTitle: doRequest AJAX call successful. Title returned: "+title+" ");

            if ($.isFunction(callback)) {
                callback(title);
            }
        }, function() {
            if ($.isFunction(callback)) {
                callback(title);
            }
        });
    };

    // Handles performing the page load request
    // Leaves checking for other requests and validity to other functions
    wpAjax.doRequest = function(url, success, error) {

        log("doRequest: About to perform an AJAX call");

        // Do the fetching and stuff...
        currentRequest = $.ajax({
            url: url,
            localCache: o.cacheRequests,
            cacheTTL: o.cacheExpiry,
            type: 'GET',
            dataType: 'html',
            requestCount: ++requestCount,
            beforeSend: function() {
                // Check if we have a promise and cancel any current requests
                if (currentRequest !== null) {
                    currentRequest.abort();
                }
            },
            success: function(response, textStatus, jqXHR) {
                log("doRequest: AJAX success callback");
                if (requestCount !== this.requestCount) return;
                success(response, textStatus, jqXHR);
            },
            error: function(jqXHR, textStatus, errorThrown) {
                log("doRequest: AJAX error callback");
                if ($.isFunction(error)) {
                    error(jqXHR, textStatus, errorThrown);
                }
            }
        });

    };

    // Once our AJAX request is done, this function is called
    // Which allows us to process the response
    wpAjax.processRequest = function(data, url) {
        var _html = $(data);

        if (!o.testMode) {
            var _content = _html.find(o.content).html();
            var _wpvars = _html.find("#wpvars").html();
        } else {
            var _content = _html.find("body").html();
        }

        log("processRequest: Processing the data returned by a successful AJAX call");

        // Do we have content?
        if (_content && _content.length) {

            if (!o.testMode) {
                // Get latest version of WP Vars object
                $("#wpvars").remove();

                var s = document.createElement("script");
                s.id = "wpvars";
                s.type = "text/javascript";
                s.text = _wpvars;
                $("body").append(s);
            }

            var loadedEvent = jQuery.Event("wpAjax.loaded", {
                previousUrl: previousUrl,
                previousSlug: previousSlug,
                previousID: previousID,
                content: data,
                url: url
            });

             // AJAX load finished fire a loaded event with the data
             $(document).trigger(loadedEvent);

            log("processRequest: Content found from the AJAX request, determining what to do with it");

            // We want to wait for images to load before proceeding
            if (o.waitForImages) {

                log("processRequest Wait for images option is enabled, finding images");

                // We have images to preload
                if ($(_content).find("img").length) {

                    log("processRequest: We found images. Waiting for all images in the returned data to preload");

                    // Populate the content element
                    wpAjax.populateContent(_content, function(contentEl) {

                        log("processRequest: Populated the content element with content, about to preload iamges");

                        // Wait for any newly populated images to load
                        contentEl.waitForImages(function() {

                            log("processRequest: All images in AJAX loaded content have preloaded");

                            // Replace body classes with those of the loaded body classes
                            $body.attr("class", data.match(/body class=\"(.*?)\"/)[1]);

                            var completeEvent = jQuery.Event("wpAjax.complete", {
                                contentEl: contentEl
                            });

                            // All content has been populated, assume we've succeeded
                            $(document).trigger(completeEvent);

                        });

                    });

                } else {
                    // Populate the content element
                    wpAjax.populateContent(_content, function(contentEl) {

                        log("processRequest: Requested AJAX content has been added to the content element and classes changed");

                        // Replace body classes with those of the loaded body classes
                        $body.attr("class", data.match(/body class=\"(.*?)\"/)[1]);

                            var completeEvent = jQuery.Event("wpAjax.complete", {
                                contentEl: contentEl
                            });

                            // All content has been populated, assume we've succeeded
                            $(document).trigger(completeEvent);

                    });
                }

            } else {
                // Populate the content element
                wpAjax.populateContent(_content, function(contentEl) {

                    log("processRequest: Requested AJAX content has been added to the content element and classes changed");

                    // Replace body classes with those of the loaded body classes
                    $("body").attr("class",data.filter("body").attr("class"));

                            var completeEvent = jQuery.Event("wpAjax.complete", {
                                contentEl: contentEl
                            });

                            // All content has been populated, assume we've succeeded
                            $(document).trigger(completeEvent);
                });
            }

            // Fade in the content DIV now we've done what we've wanted with it
            wpAjax.fadeInContent();

        } else {
            log("processRequest: Returned AJAX content is empty. Could be a problem server-side.");
        }
    };

    // Populates the appropriate content DIV with our
    // load content from the AJAX request (if successful)
    wpAjax.populateContent = function(content, callback) {
        log("populateContent: About to populate the content element with returned HTML");

        if (!o.testMode) {
            // Populate the content element
            $content.html(content);
        }

        // If we have a callback function
        if ($.isFunction(callback)) {
            log("populateContent: We've added in the content, calling the callback function with the element as an argument");
            callback($content);
        }
    };

    // Console log wrapper checks if debugging is on
    function log(msg) {
        if (o.debug) {
            console.log(msg);
        }
    }

    // Expose our method to the world
    window.wpAjax = wpAjax;

})(jQuery, window, window.document, window.History);

// Regex selector for jQuery: http://james.padolsey.com/javascript/regex-selector-for-jquery/
(function($, undefined) {

    jQuery.expr[':'].regex = function(elem, index, match) {
        var matchParams = match[3].split(','),
            validLabels = /^(data|css):/,
            attr = {
                method: matchParams[0].match(validLabels) ?
                            matchParams[0].split(':')[0] : 'attr',
                property: matchParams.shift().replace(validLabels,'')
            },
            regexFlags = 'ig',
            regex = new RegExp(matchParams.join('').replace(/^\s+|\s+$/g,''), regexFlags);
        return regex.test(jQuery(elem)[attr.method](attr.property));
    };

})(jQuery);

(function($, undefined) {

    // github.com/paulirish/jquery-ajax-localstorage-cache
    // dependent on Modernizr's localStorage test
    $.ajaxPrefilter( function( options, originalOptions, jqXHR ) {

      // Modernizr.localstorage, version 3 12/12/13
      function hasLocalStorage() {
        var mod = 'modernizr';
        try {
          localStorage.setItem(mod, mod);
          localStorage.removeItem(mod);
          return true;
        } catch(e) {
          return false;
        }
      }

      // Cache it ?
      if ( !hasLocalStorage() || !options.localCache ) return;

      var hourstl = options.cacheTTL || 5;

      var cacheKey = options.cacheKey ||
                     options.url.replace( /jQuery.*/,'' ) + options.type + (options.data || '');

      // isCacheValid is a function to validate cache
      if ( options.isCacheValid &&  ! options.isCacheValid() ){
        localStorage.removeItem( cacheKey );
      }
      // if there's a TTL that's expired, flush this item
      var ttl = localStorage.getItem(cacheKey + 'cachettl');
      if ( ttl && ttl < +new Date() ){
        localStorage.removeItem( cacheKey );
        localStorage.removeItem( cacheKey  + 'cachettl' );
        ttl = 'expired';
      }

      var value = localStorage.getItem( cacheKey );
      if ( value ){
        //In the cache? So get it, apply success callback & abort the XHR request
        // parse back to JSON if we can.
        if ( options.dataType.indexOf( 'json' ) === 0 ) value = JSON.parse( value );
        options.success( value );
        // Abort is broken on JQ 1.5 :(
        jqXHR.abort();
      } else {

        //If it not in the cache, we change the success callback, just put data on localstorage and after that apply the initial callback
        if ( options.success ) {
          options.realsuccess = options.success;
        }
        options.success = function( data ) {
          var strdata = data;
          if ( this.dataType.indexOf( 'json' ) === 0 ) strdata = JSON.stringify( data );

          // Save the data to localStorage catching exceptions (possibly QUOTA_EXCEEDED_ERR)
          try {
            localStorage.setItem( cacheKey, strdata );
          } catch (e) {
            // Remove any incomplete data that may have been saved before the exception was caught
            localStorage.removeItem( cacheKey );
            localStorage.removeItem( cacheKey + 'cachettl' );
            if ( options.cacheError ) options.cacheError( e, cacheKey, strdata );
          }

          if ( options.realsuccess ) options.realsuccess( data );
        };

        // store timestamp
        if ( ! ttl || ttl === 'expired' ) {
          localStorage.setItem( cacheKey  + 'cachettl', +new Date() + 1000 * 60 * 60 * hourstl );
        }

      }
    });

});
<commit_msg>Store references to existing page slug and ID in appropriate variables.<commit_after>/**
 * Copyright (c) 2014 and beyond Dwayne Charrington
 * Email: dwaynecharrington (at) gmail (dot) com
 * Twitter: abolitionof_
 * Licensed under MIT
 * @author Dwayne Charrington
 * @version 1.0
 */

(function($, window, document, History, undefined) {

    // Events trigger

    // While loading: wpAjax.loading: (event, url)
    // If failed: wpAjax.failed: (event, url)
    // Content loaded: wpAjax.loaded: (event, data, url)
    // Content loaded and populated: wpAjax.complete: (event, contentEl)

    /*
        Example:

        //To configure wpAjax:
        wpAjax.configure({
            content: "#content" // Element with our content which will be AJAX''d out
        });

        // Call this from within a click event
        wpAjax.trigger("http://www.someurl.com");

        // Request is currently happening (with current URL and new URL)
        $(document).on("wpAjax.loading", function(event) {
            // Methods are;
            // event.previousUrl
            // event.previousSlug
            // event.previousID
            // event.url
            // event.slug
            // event.ID
        });

        // All data has loaded
        $(document).on("wpAjax.loaded", function(event) {
            // Methods are;
            // event.previousUrl
            // event.previousSlug
            // event.previousID
            // event.content
            // event.url
            // event.slug
            // event.ID
        });

        $(document).on("wpAjax.failed", function(event) {
            // Methods are;
            // event.url
        });

        // All data has been populated the content element returned
        $(document).on("wpAjax.complete", function(event) {
            // Methods are;
            // event.contentEl
            // event.url
            // event.slug
            // event.ID
        });
    */

    var currentRequest = null,
         previousUrl = "",
         previousSlug = "",
         previousID = 0,
         requestCount = 0;

    // Main WP Ajax object
    var wpAjax = {};

    // Options
    var settings = {
            content: '#content',      // This is our container
            cacheRequests: true,  // Use HTML5 localStorage to cache pages?
            cacheExpiry: 1,          // Time in hours cached items should be cached for
            waitForImages: true,   // Wait for images to load before loading a page?
            debug: false,              // Debug mode shows console messages if true
            testMode: false           // Modifies certain methods so we can test them
        },
        o = settings;

    // These two elements never disappear and are always consistent
    var $body    = $("body");
    var $wpvars = $("wpvars");
    var $content = $(o.content);

    // Statechange when the URL changes, we roll
    $(window).off("statechange").on("statechange", function() {
        var State = History.getState();

        log("Event.statechange: HTML5 History statechange event trigger with URL: "+State.url);

        if (previousUrl !== State.url) {
            log("Event.statechange: Calling the wpAjax.loadPage function with State.url as its parameter");
            wpAjax.loadPage(State.url);
        } else {
            log("Event.statechange: User is already on the requested page to load. No request will be made.");
        }
    });

    // Allows us to configure wpAjax
    wpAjax.configure = function(options) {
        log("configure: Setting options for Wpajax");
        $.extend(settings, options);
        return this;
    };

    // Return the configuration object
    wpAjax.getConfiguration = function() {
        return settings;
    };

    // Helper function for checking the current URL
    wpAjax.getCurrentUrl = function() {
        log("getCurrentUrl: Getting the current browser address URL");
        return window.location.href;
    };

    // Trigger a page load
    wpAjax.trigger = function(url) {
        log("trigger: Calling History.pushState which will trigger a statechange");

        // Store current URL as the previous URL
        previousUrl   = wpAjax.getCurrentUrl();

        // Store the current page/post slug
        previousSlug = wpajax.pagename;

        // Store the current page/post ID
        previousID    = wpajax.pageid;

        wpAjax.getTitle(url, function(title) {
            History.pushState({}, title, url);
        });
    };

    // Have we reached our page limit
    wpAjax.pageLimitReached = function() {
        return (wpvars.max == wpvars.paged);
    }

    // What is the current page we are on
    wpAjax.getCurrentPageNumber = function() {
        return wpvars.paged;
    }

    // Get the maximum number of pages in our results
    wpAjax.getMaxPages = function() {
        return wpvars.max;
    }

    // Load page function
    wpAjax.loadPage = function(url) {

        log("loadPage: No other request is taking place, we are good to go");

        if (!o.testMode) {
            // Apply a loading class to the body
            $("body").addClass("loading-page");

            var loadingEvent = jQuery.Event("wpAjax.loading", {
                previousUrl: previousUrl,
                previousSlug: previousSlug,
                previousID: previousID,
                url: url
            });

            // Trigger loading event
            $(document).trigger(loadingEvent);

            // Before content is loaded in, fade out the old content
            wpAjax.fadeOutContent(function() {

               // Perform our AJAX request
                wpAjax.doRequest(url, function(data) {
                    wpAjax.processRequest(data, url);
                }, function() {

                    if (!o.testMode) {
                        wpAjax.fadeInContent();

                        log("loadPage: Called doRequest and the request failed. Throwing a failed event on document");

                        var failedEvent = jQuery.Event("wpAjax.failed", {
                            url: url
                        });

                        // Trigger failed event
                        $(document).trigger(failedEvent);
                    }
                });

            });

            log("loadPage: Loading class applied to body, loading event fired and content element faded out");
        }

    };

    // Fade out the content area
    wpAjax.fadeOutContent = function(callback) {
        log("fadeOutContent: Animating content element out");

        if (arguments.length == 0) callback = function() {};

        $content.animate({opacity:0}, 800, callback);
    };

    // Fade in the content area
    wpAjax.fadeInContent = function(callback) {
        log("fadeInContent: Animating content element in");

        if (arguments.length == 0) callback = function() {};

        $content.animate({opacity:1}, 800, callback);
    };

    // Performs an AJAX request to get the page title
    // Also has the advantage of pre-fetching the page
    // for us as well.
    wpAjax.getTitle = function(url, callback) {
        var title = "";

        log("getTitle: Calling wpAjax.doRequest now to get the title");

        wpAjax.doRequest(url, function(data) {
            title = $(data).filter("title").text();
            log("getTitle: doRequest AJAX call successful. Title returned: "+title+" ");

            if ($.isFunction(callback)) {
                callback(title);
            }
        }, function() {
            if ($.isFunction(callback)) {
                callback(title);
            }
        });
    };

    // Handles performing the page load request
    // Leaves checking for other requests and validity to other functions
    wpAjax.doRequest = function(url, success, error) {

        log("doRequest: About to perform an AJAX call");

        // Do the fetching and stuff...
        currentRequest = $.ajax({
            url: url,
            localCache: o.cacheRequests,
            cacheTTL: o.cacheExpiry,
            type: 'GET',
            dataType: 'html',
            requestCount: ++requestCount,
            beforeSend: function() {
                // Check if we have a promise and cancel any current requests
                if (currentRequest !== null) {
                    currentRequest.abort();
                }
            },
            success: function(response, textStatus, jqXHR) {
                log("doRequest: AJAX success callback");
                if (requestCount !== this.requestCount) return;
                success(response, textStatus, jqXHR);
            },
            error: function(jqXHR, textStatus, errorThrown) {
                log("doRequest: AJAX error callback");
                if ($.isFunction(error)) {
                    error(jqXHR, textStatus, errorThrown);
                }
            }
        });

    };

    // Once our AJAX request is done, this function is called
    // Which allows us to process the response
    wpAjax.processRequest = function(data, url) {
        var _html = $(data);

        if (!o.testMode) {
            var _content = _html.find(o.content).html();
            var _wpvars = _html.find("#wpvars").html();
        } else {
            var _content = _html.find("body").html();
        }

        log("processRequest: Processing the data returned by a successful AJAX call");

        // Do we have content?
        if (_content && _content.length) {

            if (!o.testMode) {
                // Get latest version of WP Vars object
                $("#wpvars").remove();

                var s = document.createElement("script");
                s.id = "wpvars";
                s.type = "text/javascript";
                s.text = _wpvars;
                $("body").append(s);
            }

            var loadedEvent = jQuery.Event("wpAjax.loaded", {
                previousUrl: previousUrl,
                previousSlug: previousSlug,
                previousID: previousID,
                content: data,
                url: url
            });

             // AJAX load finished fire a loaded event with the data
             $(document).trigger(loadedEvent);

            log("processRequest: Content found from the AJAX request, determining what to do with it");

            // We want to wait for images to load before proceeding
            if (o.waitForImages) {

                log("processRequest Wait for images option is enabled, finding images");

                // We have images to preload
                if ($(_content).find("img").length) {

                    log("processRequest: We found images. Waiting for all images in the returned data to preload");

                    // Populate the content element
                    wpAjax.populateContent(_content, function(contentEl) {

                        log("processRequest: Populated the content element with content, about to preload iamges");

                        // Wait for any newly populated images to load
                        contentEl.waitForImages(function() {

                            log("processRequest: All images in AJAX loaded content have preloaded");

                            // Replace body classes with those of the loaded body classes
                            $body.attr("class", data.match(/body class=\"(.*?)\"/)[1]);

                            var completeEvent = jQuery.Event("wpAjax.complete", {
                                contentEl: contentEl
                            });

                            // All content has been populated, assume we've succeeded
                            $(document).trigger(completeEvent);

                        });

                    });

                } else {
                    // Populate the content element
                    wpAjax.populateContent(_content, function(contentEl) {

                        log("processRequest: Requested AJAX content has been added to the content element and classes changed");

                        // Replace body classes with those of the loaded body classes
                        $body.attr("class", data.match(/body class=\"(.*?)\"/)[1]);

                            var completeEvent = jQuery.Event("wpAjax.complete", {
                                contentEl: contentEl
                            });

                            // All content has been populated, assume we've succeeded
                            $(document).trigger(completeEvent);

                    });
                }

            } else {
                // Populate the content element
                wpAjax.populateContent(_content, function(contentEl) {

                    log("processRequest: Requested AJAX content has been added to the content element and classes changed");

                    // Replace body classes with those of the loaded body classes
                    $("body").attr("class",data.filter("body").attr("class"));

                            var completeEvent = jQuery.Event("wpAjax.complete", {
                                contentEl: contentEl
                            });

                            // All content has been populated, assume we've succeeded
                            $(document).trigger(completeEvent);
                });
            }

            // Fade in the content DIV now we've done what we've wanted with it
            wpAjax.fadeInContent();

        } else {
            log("processRequest: Returned AJAX content is empty. Could be a problem server-side.");
        }
    };

    // Populates the appropriate content DIV with our
    // load content from the AJAX request (if successful)
    wpAjax.populateContent = function(content, callback) {
        log("populateContent: About to populate the content element with returned HTML");

        if (!o.testMode) {
            // Populate the content element
            $content.html(content);
        }

        // If we have a callback function
        if ($.isFunction(callback)) {
            log("populateContent: We've added in the content, calling the callback function with the element as an argument");
            callback($content);
        }
    };

    // Console log wrapper checks if debugging is on
    function log(msg) {
        if (o.debug) {
            console.log(msg);
        }
    }

    // Expose our method to the world
    window.wpAjax = wpAjax;

})(jQuery, window, window.document, window.History);

// Regex selector for jQuery: http://james.padolsey.com/javascript/regex-selector-for-jquery/
(function($, undefined) {

    jQuery.expr[':'].regex = function(elem, index, match) {
        var matchParams = match[3].split(','),
            validLabels = /^(data|css):/,
            attr = {
                method: matchParams[0].match(validLabels) ?
                            matchParams[0].split(':')[0] : 'attr',
                property: matchParams.shift().replace(validLabels,'')
            },
            regexFlags = 'ig',
            regex = new RegExp(matchParams.join('').replace(/^\s+|\s+$/g,''), regexFlags);
        return regex.test(jQuery(elem)[attr.method](attr.property));
    };

})(jQuery);

(function($, undefined) {

    // github.com/paulirish/jquery-ajax-localstorage-cache
    // dependent on Modernizr's localStorage test
    $.ajaxPrefilter( function( options, originalOptions, jqXHR ) {

      // Modernizr.localstorage, version 3 12/12/13
      function hasLocalStorage() {
        var mod = 'modernizr';
        try {
          localStorage.setItem(mod, mod);
          localStorage.removeItem(mod);
          return true;
        } catch(e) {
          return false;
        }
      }

      // Cache it ?
      if ( !hasLocalStorage() || !options.localCache ) return;

      var hourstl = options.cacheTTL || 5;

      var cacheKey = options.cacheKey ||
                     options.url.replace( /jQuery.*/,'' ) + options.type + (options.data || '');

      // isCacheValid is a function to validate cache
      if ( options.isCacheValid &&  ! options.isCacheValid() ){
        localStorage.removeItem( cacheKey );
      }
      // if there's a TTL that's expired, flush this item
      var ttl = localStorage.getItem(cacheKey + 'cachettl');
      if ( ttl && ttl < +new Date() ){
        localStorage.removeItem( cacheKey );
        localStorage.removeItem( cacheKey  + 'cachettl' );
        ttl = 'expired';
      }

      var value = localStorage.getItem( cacheKey );
      if ( value ){
        //In the cache? So get it, apply success callback & abort the XHR request
        // parse back to JSON if we can.
        if ( options.dataType.indexOf( 'json' ) === 0 ) value = JSON.parse( value );
        options.success( value );
        // Abort is broken on JQ 1.5 :(
        jqXHR.abort();
      } else {

        //If it not in the cache, we change the success callback, just put data on localstorage and after that apply the initial callback
        if ( options.success ) {
          options.realsuccess = options.success;
        }
        options.success = function( data ) {
          var strdata = data;
          if ( this.dataType.indexOf( 'json' ) === 0 ) strdata = JSON.stringify( data );

          // Save the data to localStorage catching exceptions (possibly QUOTA_EXCEEDED_ERR)
          try {
            localStorage.setItem( cacheKey, strdata );
          } catch (e) {
            // Remove any incomplete data that may have been saved before the exception was caught
            localStorage.removeItem( cacheKey );
            localStorage.removeItem( cacheKey + 'cachettl' );
            if ( options.cacheError ) options.cacheError( e, cacheKey, strdata );
          }

          if ( options.realsuccess ) options.realsuccess( data );
        };

        // store timestamp
        if ( ! ttl || ttl === 'expired' ) {
          localStorage.setItem( cacheKey  + 'cachettl', +new Date() + 1000 * 60 * 60 * hourstl );
        }

      }
    });

});
<|endoftext|>


<commit_before>/*
  LIGHTSTREAMER - www.lightstreamer.com
  JMS Stock-List Demo

  Copyright (c) Lightstreamer Srl

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

  http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License 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.
*/

import stocksGrid from './grid.js';

jms.TopicConnectionFactory.createTopicConnection("http://localhost:8080/", "ActiveMQ", null, null, {
    onConnectionCreated: function (conn) {
        // Connection succeeded, topic subscription
        var topicSession = conn.createSession(false, "PRE_ACK");
        var topic = topicSession.createTopic("stocksTopic");
        var consumer = topicSession.createConsumer(topic, null);

        // Add listener to message consumer
        consumer.setMessageListener({
            onMessage: function (message) {

                // Message received
                var feedMessage = message.getObject();
                if (!feedMessage.currentValues) {
                    return;
                }

                var key = feedMessage.itemName;
                var values = feedMessage.currentValues;

                // Update the view with the received data
                stocksGrid.updateRow(key, values);
            }
        });

        // Start the connection
        conn.start();
    },

    onConnectionFailed: function (errorCode, errorMessage) {

        // Connection failed, show the error
        alert("Error: " + errorCode + " " + errorMessage);

    },

    onLSClient: function (lsClient) {
        // Enable connection sharing and status widget (optional)
        lsClient.connectionSharing.enableSharing("JMSDemoCommonConnection", "ATTACH", "CREATE");
        lsClient.addListener(new StatusWidget("left", "0px", true));
    }
});<commit_msg>Fix indentation<commit_after>/*
  LIGHTSTREAMER - www.lightstreamer.com
  JMS Stock-List Demo

  Copyright (c) Lightstreamer Srl

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

  http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License 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.
*/

import stocksGrid from './grid.js';

jms.TopicConnectionFactory.createTopicConnection("http://localhost:8080/", "ActiveMQ", null, null, {
  onConnectionCreated: function (conn) {
    // Connection succeeded, topic subscription
    var topicSession = conn.createSession(false, "PRE_ACK");
    var topic = topicSession.createTopic("stocksTopic");
    var consumer = topicSession.createConsumer(topic, null);

    // Add listener to message consumer
    consumer.setMessageListener({
      onMessage: function (message) {

        // Message received
        var feedMessage = message.getObject();
        if (!feedMessage.currentValues) {
          return;
        }

        var key = feedMessage.itemName;
        var values = feedMessage.currentValues;

        // Update the view with the received data
        stocksGrid.updateRow(key, values);
      }
    });

    // Start the connection
    conn.start();
  },

  onConnectionFailed: function (errorCode, errorMessage) {

    // Connection failed, show the error
    alert("Error: " + errorCode + " " + errorMessage);

  },

  onLSClient: function (lsClient) {
    // Enable connection sharing and status widget (optional)
    lsClient.connectionSharing.enableSharing("JMSDemoCommonConnection", "ATTACH", "CREATE");
    lsClient.addListener(new StatusWidget("left", "0px", true));
  }
});<|endoftext|>