<commit_before>/**
 * Copyright (c) 2012 Andreas Madsen
 * MIT License
 */

var vows = require('vows'),
    assert = require('assert'),

    common = require('../common.js'),
    prope = require(common.watcher('interface.js'));

common.reset();

function startImmortal(callback) {
  prope.createInterface(common.fixture('longlive.js'), {
    strategy: 'daemon',
    options: {
      simultaneousError: true
    }
  }, callback);
}

var testsuite = vows.describe('testing simultaneous error');

function addTestSeries() {
  var monitor = null;

  testsuite.addBatch({
    'when starting immortal': {
      topic: function () {
        var self = this;
        startImmortal(function (error, prope) {
          monitor = prope;
          self.callback(error, prope);
        });
      },

      'no errors should occurre in startup': function (error, monitor) {
        assert.ifError(error);
        assert.isNull(monitor.error);
      }
    }

  }).addBatch({
    'when immortal group is ready': {
      topic: function () {
        var self = this;
        monitor.ready();
        monitor.once('process', function () {
          self.callback(null, monitor);
        });
      },

      'an error should occurre in this regression': {
        topic: function (monitor) {
          var self = this;
          var pids = common.copy(monitor.pid);

          monitor.once('reconnect', function () {
            monitor.ready();
            monitor.once('process', function () {

              self.callback(null, monitor, pids);
            });
          });
        },

        'the old immortal group should be dead': function (error, monitor, pids) {
          assert.ifError(error);

          assert.isNumber(pids.daemon);
          assert.isFalse(common.isAlive(pids.daemon));

          assert.isNumber(pids.monitor);
          assert.isFalse(common.isAlive(pids.monitor));

          assert.isNumber(pids.process);
          assert.isFalse(common.isAlive(pids.process));
        },

        'the error should not contain something': function (error, monitor) {
          assert.ifError(error);
          assert.isNull(monitor.error);
        }
      }
    }
  }).addBatch({

    'when immortal stops': {
      topic: function () {
        var self = this;
        var pids = common.copy(monitor.pid);;
        monitor.shutdown(function () {
          monitor.close(function () {
            setTimeout(function () {
              self.callback(null, monitor, pids);
            }, 100);
          });
        });
      },

      'the immortal group should be dead': function (error, monitor, pid) {
        assert.ifError(error);

        assert.isNumber(pid.daemon);
        assert.isFalse(common.isAlive(pid.daemon));

        assert.isNumber(pid.monitor);
        assert.isFalse(common.isAlive(pid.monitor));

        assert.isNumber(pid.process);
        assert.isFalse(common.isAlive(pid.process));
      }
    }
  });
}

// Test this 10 times
var i = 10;
while(i--) addTestSeries();

testsuite.exportTo(module);
<commit_msg>[test] increased death threshold<commit_after>/**
 * Copyright (c) 2012 Andreas Madsen
 * MIT License
 */

var vows = require('vows'),
    assert = require('assert'),

    common = require('../common.js'),
    prope = require(common.watcher('interface.js'));

common.reset();

function startImmortal(callback) {
  prope.createInterface(common.fixture('longlive.js'), {
    strategy: 'daemon',
    options: {
      simultaneousError: true
    }
  }, callback);
}

var testsuite = vows.describe('testing simultaneous error');

function addTestSeries() {
  var monitor = null;

  testsuite.addBatch({
    'when starting immortal': {
      topic: function () {
        var self = this;
        startImmortal(function (error, prope) {
          monitor = prope;
          self.callback(error, prope);
        });
      },

      'no errors should occurre in startup': function (error, monitor) {
        assert.ifError(error);
        assert.isNull(monitor.error);
      }
    }

  }).addBatch({
    'when immortal group is ready': {
      topic: function () {
        var self = this;
        monitor.ready();
        monitor.once('process', function () {
          self.callback(null, monitor);
        });
      },

      'an error should occurre in this regression': {
        topic: function (monitor) {
          var self = this;
          var pids = common.copy(monitor.pid);

          monitor.once('reconnect', function () {
            monitor.ready();
            monitor.once('process', function () {

              self.callback(null, monitor, pids);
            });
          });
        },

        'the old immortal group should be dead': function (error, monitor, pids) {
          assert.ifError(error);

          assert.isNumber(pids.daemon);
          assert.isFalse(common.isAlive(pids.daemon));

          assert.isNumber(pids.monitor);
          assert.isFalse(common.isAlive(pids.monitor));

          assert.isNumber(pids.process);
          assert.isFalse(common.isAlive(pids.process));
        },

        'the error should not contain something': function (error, monitor) {
          assert.ifError(error);
          assert.isNull(monitor.error);
        }
      }
    }
  }).addBatch({

    'when immortal stops': {
      topic: function () {
        var self = this;
        var pids = common.copy(monitor.pid);
        monitor.shutdown(function () {
          monitor.close(function () {
            setTimeout(function () {
              self.callback(null, monitor, pids);
            }, 400);
          });
        });
      },

      'the immortal group should be dead': function (error, monitor, pid) {
        assert.ifError(error);

        assert.isNumber(pid.daemon);
        assert.isFalse(common.isAlive(pid.daemon));

        assert.isNumber(pid.monitor);
        assert.isFalse(common.isAlive(pid.monitor));

        assert.isNumber(pid.process);
        assert.isFalse(common.isAlive(pid.process));
      }
    }
  });
}

// Test this 10 times
var i = 10;
while(i--) addTestSeries();

testsuite.exportTo(module);
<|endoftext|>


<commit_before>goog.provide('ol.test.source.TileWMS');

describe('ol.source.TileWMS', function() {

  var options;
  beforeEach(function() {
    options = {
      params: {
        'LAYERS': 'layer'
      },
      url: 'http://example.com/wms'
    };
  });

  describe('#getTile', function() {

    it('returns a tile with the expected URL', function() {
      var source = new ol.source.TileWMS(options);
      var tile = source.getTile(3, 2, 1, 1, ol.proj.get('EPSG:3857'));
      expect(tile).to.be.an(ol.ImageTile);
      var uri = new goog.Uri(tile.src_);
      expect(uri.getScheme()).to.be('http');
      expect(uri.getDomain()).to.be('example.com');
      expect(uri.getPath()).to.be('/wms');
      var queryData = uri.getQueryData();
      expect(queryData.get('BBOX')).to.be(
          '-10018754.171394622,-15028131.257091932,' +
          '-5009377.085697311,-10018754.17139462');
      expect(queryData.get('CRS')).to.be('EPSG:3857');
      expect(queryData.get('FORMAT')).to.be('image/png');
      expect(queryData.get('HEIGHT')).to.be('256');
      expect(queryData.get('LAYERS')).to.be('layer');
      expect(queryData.get('REQUEST')).to.be('GetMap');
      expect(queryData.get('SERVICE')).to.be('WMS');
      expect(queryData.get('SRS')).to.be(undefined);
      expect(queryData.get('STYLES')).to.be('');
      expect(queryData.get('TRANSPARENT')).to.be('true');
      expect(queryData.get('VERSION')).to.be('1.3.0');
      expect(queryData.get('WIDTH')).to.be('256');
      expect(uri.getFragment()).to.be.empty();
    });

    it('returns a larger tile when a gutter is specified', function() {
      options.gutter = 16;
      var source = new ol.source.TileWMS(options);
      var tile = source.getTile(3, 2, 1, 1, ol.proj.get('EPSG:3857'));
      expect(tile).to.be.an(ol.ImageTile);
      var uri = new goog.Uri(tile.src_);
      var queryData = uri.getQueryData();
      expect(queryData.get('BBOX')).to.be(
          '-10331840.239250705,-15341217.324948015,' +
          '-4696291.017841229,-9705668.103538537');
      expect(queryData.get('HEIGHT')).to.be('288');
      expect(queryData.get('WIDTH')).to.be('288');
    });

    it('sets the SRS query value instead of CRS if version < 1.3', function() {
      options.params.VERSION = '1.2';
      var source = new ol.source.TileWMS(options);
      var tile = source.getTile(3, 2, 1, 1, ol.proj.get('EPSG:4326'));
      var uri = new goog.Uri(tile.src_);
      var queryData = uri.getQueryData();
      expect(queryData.get('CRS')).to.be(undefined);
      expect(queryData.get('SRS')).to.be('EPSG:4326');
    });

    it('allows various parameters to be overridden', function() {
      options.params.FORMAT = 'image/jpeg';
      options.params.TRANSPARENT = false;
      var source = new ol.source.TileWMS(options);
      var tile = source.getTile(3, 2, 1, 1, ol.proj.get('EPSG:4326'));
      var uri = new goog.Uri(tile.src_);
      var queryData = uri.getQueryData();
      expect(queryData.get('FORMAT')).to.be('image/jpeg');
      expect(queryData.get('TRANSPARENT')).to.be('false');
    });

    it('does not add a STYLES= option if one is specified', function() {
      options.params.STYLES = 'foo';
      var source = new ol.source.TileWMS(options);
      var tile = source.getTile(3, 2, 1, 1, ol.proj.get('EPSG:4326'));
      var uri = new goog.Uri(tile.src_);
      var queryData = uri.getQueryData();
      expect(queryData.get('STYLES')).to.be('foo');
    });

    it('changes the BBOX order for EN axis orientations', function() {
      var source = new ol.source.TileWMS(options);
      var tile = source.getTile(3, 2, 1, 1, ol.proj.get('EPSG:4326'));
      var uri = new goog.Uri(tile.src_);
      var queryData = uri.getQueryData();
      expect(queryData.get('BBOX')).to.be('-45,-90,0,-45');
    });

    it('uses EN BBOX order if version < 1.3', function() {
      options.params.VERSION = '1.1.0';
      var source = new ol.source.TileWMS(options);
      var tile = source.getTile(3, 2, 1, 1, ol.proj.get('CRS:84'));
      var uri = new goog.Uri(tile.src_);
      var queryData = uri.getQueryData();
      expect(queryData.get('BBOX')).to.be('-90,-45,-45,0');
    });

  });

});

goog.require('goog.Uri');
goog.require('ol.ImageTile');
goog.require('ol.source.TileWMS');
goog.require('ol.proj');
<commit_msg>Add tests for ol.source.TileWMS#getGetFeatureInfoUrl<commit_after>goog.provide('ol.test.source.TileWMS');

describe('ol.source.TileWMS', function() {

  var options;
  beforeEach(function() {
    options = {
      params: {
        'LAYERS': 'layer'
      },
      url: 'http://example.com/wms'
    };
  });

  describe('#getTile', function() {

    it('returns a tile with the expected URL', function() {
      var source = new ol.source.TileWMS(options);
      var tile = source.getTile(3, 2, 1, 1, ol.proj.get('EPSG:3857'));
      expect(tile).to.be.an(ol.ImageTile);
      var uri = new goog.Uri(tile.src_);
      expect(uri.getScheme()).to.be('http');
      expect(uri.getDomain()).to.be('example.com');
      expect(uri.getPath()).to.be('/wms');
      var queryData = uri.getQueryData();
      expect(queryData.get('BBOX')).to.be(
          '-10018754.171394622,-15028131.257091932,' +
          '-5009377.085697311,-10018754.17139462');
      expect(queryData.get('CRS')).to.be('EPSG:3857');
      expect(queryData.get('FORMAT')).to.be('image/png');
      expect(queryData.get('HEIGHT')).to.be('256');
      expect(queryData.get('LAYERS')).to.be('layer');
      expect(queryData.get('REQUEST')).to.be('GetMap');
      expect(queryData.get('SERVICE')).to.be('WMS');
      expect(queryData.get('SRS')).to.be(undefined);
      expect(queryData.get('STYLES')).to.be('');
      expect(queryData.get('TRANSPARENT')).to.be('true');
      expect(queryData.get('VERSION')).to.be('1.3.0');
      expect(queryData.get('WIDTH')).to.be('256');
      expect(uri.getFragment()).to.be.empty();
    });

    it('returns a larger tile when a gutter is specified', function() {
      options.gutter = 16;
      var source = new ol.source.TileWMS(options);
      var tile = source.getTile(3, 2, 1, 1, ol.proj.get('EPSG:3857'));
      expect(tile).to.be.an(ol.ImageTile);
      var uri = new goog.Uri(tile.src_);
      var queryData = uri.getQueryData();
      expect(queryData.get('BBOX')).to.be(
          '-10331840.239250705,-15341217.324948015,' +
          '-4696291.017841229,-9705668.103538537');
      expect(queryData.get('HEIGHT')).to.be('288');
      expect(queryData.get('WIDTH')).to.be('288');
    });

    it('sets the SRS query value instead of CRS if version < 1.3', function() {
      options.params.VERSION = '1.2';
      var source = new ol.source.TileWMS(options);
      var tile = source.getTile(3, 2, 1, 1, ol.proj.get('EPSG:4326'));
      var uri = new goog.Uri(tile.src_);
      var queryData = uri.getQueryData();
      expect(queryData.get('CRS')).to.be(undefined);
      expect(queryData.get('SRS')).to.be('EPSG:4326');
    });

    it('allows various parameters to be overridden', function() {
      options.params.FORMAT = 'image/jpeg';
      options.params.TRANSPARENT = false;
      var source = new ol.source.TileWMS(options);
      var tile = source.getTile(3, 2, 1, 1, ol.proj.get('EPSG:4326'));
      var uri = new goog.Uri(tile.src_);
      var queryData = uri.getQueryData();
      expect(queryData.get('FORMAT')).to.be('image/jpeg');
      expect(queryData.get('TRANSPARENT')).to.be('false');
    });

    it('does not add a STYLES= option if one is specified', function() {
      options.params.STYLES = 'foo';
      var source = new ol.source.TileWMS(options);
      var tile = source.getTile(3, 2, 1, 1, ol.proj.get('EPSG:4326'));
      var uri = new goog.Uri(tile.src_);
      var queryData = uri.getQueryData();
      expect(queryData.get('STYLES')).to.be('foo');
    });

    it('changes the BBOX order for EN axis orientations', function() {
      var source = new ol.source.TileWMS(options);
      var tile = source.getTile(3, 2, 1, 1, ol.proj.get('EPSG:4326'));
      var uri = new goog.Uri(tile.src_);
      var queryData = uri.getQueryData();
      expect(queryData.get('BBOX')).to.be('-45,-90,0,-45');
    });

    it('uses EN BBOX order if version < 1.3', function() {
      options.params.VERSION = '1.1.0';
      var source = new ol.source.TileWMS(options);
      var tile = source.getTile(3, 2, 1, 1, ol.proj.get('CRS:84'));
      var uri = new goog.Uri(tile.src_);
      var queryData = uri.getQueryData();
      expect(queryData.get('BBOX')).to.be('-90,-45,-45,0');
    });

  });

  describe('#getGetFeatureInfo', function() {

    it('returns the expected GetFeatureInfo URL', function() {
      var source = new ol.source.TileWMS(options);
      source.pixelRatio_ = 1;
      var url = source.getGetFeatureInfoUrl(
          [-7000000, -12000000],
          19567.87924100512, ol.proj.get('EPSG:3857'),
          {INFO_FORMAT: 'text/plain'});
      var uri = new goog.Uri(url);
      expect(uri.getScheme()).to.be('http');
      expect(uri.getDomain()).to.be('example.com');
      expect(uri.getPath()).to.be('/wms');
      var queryData = uri.getQueryData();
      expect(queryData.get('BBOX')).to.be(
          '-10018754.171394622,-15028131.257091932,' +
          '-5009377.085697311,-10018754.17139462');
      expect(queryData.get('CRS')).to.be('EPSG:3857');
      expect(queryData.get('FORMAT')).to.be('image/png');
      expect(queryData.get('HEIGHT')).to.be('256');
      expect(queryData.get('I')).to.be('154');
      expect(queryData.get('J')).to.be('101');
      expect(queryData.get('LAYERS')).to.be('layer');
      expect(queryData.get('QUERY_LAYERS')).to.be('layer');
      expect(queryData.get('REQUEST')).to.be('GetFeatureInfo');
      expect(queryData.get('SERVICE')).to.be('WMS');
      expect(queryData.get('SRS')).to.be(undefined);
      expect(queryData.get('STYLES')).to.be('');
      expect(queryData.get('TRANSPARENT')).to.be('true');
      expect(queryData.get('VERSION')).to.be('1.3.0');
      expect(queryData.get('WIDTH')).to.be('256');
      expect(uri.getFragment()).to.be.empty();
    });

    it('sets the QUERY_LAYERS param as expected', function() {
      var source = new ol.source.TileWMS(options);
      source.pixelRatio_ = 1;
      var url = source.getGetFeatureInfoUrl(
          [-7000000, -12000000],
          19567.87924100512, ol.proj.get('EPSG:3857'),
          {INFO_FORMAT: 'text/plain', QUERY_LAYERS: 'foo,bar'});
      var uri = new goog.Uri(url);
      expect(uri.getScheme()).to.be('http');
      expect(uri.getDomain()).to.be('example.com');
      expect(uri.getPath()).to.be('/wms');
      var queryData = uri.getQueryData();
      expect(queryData.get('BBOX')).to.be(
          '-10018754.171394622,-15028131.257091932,' +
          '-5009377.085697311,-10018754.17139462');
      expect(queryData.get('CRS')).to.be('EPSG:3857');
      expect(queryData.get('FORMAT')).to.be('image/png');
      expect(queryData.get('HEIGHT')).to.be('256');
      expect(queryData.get('I')).to.be('154');
      expect(queryData.get('J')).to.be('101');
      expect(queryData.get('LAYERS')).to.be('layer');
      expect(queryData.get('QUERY_LAYERS')).to.be('foo,bar');
      expect(queryData.get('REQUEST')).to.be('GetFeatureInfo');
      expect(queryData.get('SERVICE')).to.be('WMS');
      expect(queryData.get('SRS')).to.be(undefined);
      expect(queryData.get('STYLES')).to.be('');
      expect(queryData.get('TRANSPARENT')).to.be('true');
      expect(queryData.get('VERSION')).to.be('1.3.0');
      expect(queryData.get('WIDTH')).to.be('256');
      expect(uri.getFragment()).to.be.empty();
      expect(uri.getFragment()).to.be.empty();
    });
  });
});

goog.require('goog.Uri');
goog.require('ol.ImageTile');
goog.require('ol.source.TileWMS');
goog.require('ol.proj');
<|endoftext|>


<commit_before>const JSONRPC = {};
JSONRPC.ServerPluginBase = require("../src/ServerPluginBase");
JSONRPC.Exception = require("../src/Exception");

JSONRPC.Plugins = {};
JSONRPC.Plugins.Client = require("../src/Plugins/Client/index");
JSONRPC.Utils = require("../src/Utils");

const assert = require("assert");

module.exports =
class ServerPluginAuthorizeWebSocket extends JSONRPC.ServerPluginBase
{
	constructor()
	{
		super();

		this._objSessions = {};
		this._objATeamMemberToConnectionID = {};

		Object.seal(this);
	}

	/**
	 * Called after JSON parsing of the JSONRPC request.
	 *
	 * @override
	 *
	 * @param {JSONRPC.IncomingRequest} incomingRequest
	 */
	async afterJSONDecode(incomingRequest)
	{
		if(incomingRequest.isAuthenticated && incomingRequest.isAuthorized)
		{
			// Nothing to do.
		}
		else if(incomingRequest.requestObject.method === "ImHereForTheParty")
		{
			incomingRequest.isAuthenticated = true;
			incomingRequest.isAuthorized = true;

			// The ImHereForTheParty is an authentication function.
			// It will throw if not authenticated.
		}
		else if(
			typeof incomingRequest.connectionID === "number"
			&& this._objSessions.hasOwnProperty(incomingRequest.connectionID)
			&& this._objSessions[incomingRequest.connectionID]
			&& this._objSessions[incomingRequest.connectionID].partyMembership !== null
		)
		{
			incomingRequest.isAuthenticated = true;
			incomingRequest.isAuthorized = this._objSessions[incomingRequest.connectionID].authorized;
		}
	}

	/**
	 * This is called after a function has been called successfully.
	 *
	 * @param {JSONRPC.IncomingRequest} incomingRequest
	 */
	async result(incomingRequest)
	{
		if(incomingRequest.requestObject.method === "ImHereForTheParty")
		{
			assert(typeof incomingRequest.connectionID === "number");

			if(
				this._objSessions.hasOwnProperty(incomingRequest.connectionID)
				&& this._objSessions[incomingRequest.connectionID].partyMembership !== null
			)
			{
				// Maybe race condition somewhere from alternating authenticated IDs.
				incomingRequest.callResult = new JSONRPC.Exception("Not authorized. Current connnection " + incomingRequest.connectionID + " was already authenticated.", JSONRPC.Exception.NOT_AUTHORIZED);

				return;
			}

			if(!this._objSessions.hasOwnProperty(incomingRequest.connectionID))
			{
				throw new Error("addConnection was not called with connection id " + JSON.stringify(incomingRequest.connectionID) + ".");
			}

			assert(!(incomingRequest.callResult instanceof Error));
			this._objSessions[incomingRequest.connectionID].partyMembership = incomingRequest.callResult;

			// bDoNotAuthorizeMe param.
			assert(typeof incomingRequest.requestObject.params[2] === "boolean");
			this._objSessions[incomingRequest.connectionID].authorized = !incomingRequest.requestObject.params[2];

			this._objATeamMemberToConnectionID[incomingRequest.callResult.teamMember] = incomingRequest.connectionID;
		}
	}

	/**
	 * @param {number} nWebSocketConnectionID
	 * @param {WebSocket} webSocket
	 */
	addConnection(nWebSocketConnectionID, webSocket)
	{
		assert(typeof nWebSocketConnectionID === "number");

		this._objSessions[nWebSocketConnectionID] = {
			partyMembership: null,
			authorized: false,
			connectionID: nWebSocketConnectionID
		};

		webSocket.on(
			"close",
			(code, message) => {
				if(
					this._objSessions.hasOwnProperty(nWebSocketConnectionID)
					&& this._objSessions[nWebSocketConnectionID].partyMembership
					&& this._objATeamMemberToConnectionID.hasOwnProperty(this._objSessions[nWebSocketConnectionID].partyMembership.teamMember)
				)
				{
					delete this._objATeamMemberToConnectionID[this._objSessions[nWebSocketConnectionID].partyMembership.teamMember];
				}

				delete this._objSessions[nWebSocketConnectionID];
			}
		);
	}

	/**
	 * @param {string} strATeamMember
	 *
	 * @returns {JSONRPC.Client}
	 */
	aTeamMemberToConnectionID(strATeamMember)
	{
		if(!this._objATeamMemberToConnectionID.hasOwnProperty(strATeamMember))
		{
			throw new Error("The team member is not logged in!!!");
		}

		return this._objATeamMemberToConnectionID[strATeamMember];
	}
};
<commit_msg>Incorrect return type doc.<commit_after>const JSONRPC = {};
JSONRPC.ServerPluginBase = require("../src/ServerPluginBase");
JSONRPC.Exception = require("../src/Exception");

JSONRPC.Plugins = {};
JSONRPC.Plugins.Client = require("../src/Plugins/Client/index");
JSONRPC.Utils = require("../src/Utils");

const assert = require("assert");

module.exports =
class ServerPluginAuthorizeWebSocket extends JSONRPC.ServerPluginBase
{
	constructor()
	{
		super();

		this._objSessions = {};
		this._objATeamMemberToConnectionID = {};

		Object.seal(this);
	}

	/**
	 * Called after JSON parsing of the JSONRPC request.
	 *
	 * @override
	 *
	 * @param {JSONRPC.IncomingRequest} incomingRequest
	 */
	async afterJSONDecode(incomingRequest)
	{
		if(incomingRequest.isAuthenticated && incomingRequest.isAuthorized)
		{
			// Nothing to do.
		}
		else if(incomingRequest.requestObject.method === "ImHereForTheParty")
		{
			incomingRequest.isAuthenticated = true;
			incomingRequest.isAuthorized = true;

			// The ImHereForTheParty is an authentication function.
			// It will throw if not authenticated.
		}
		else if(
			typeof incomingRequest.connectionID === "number"
			&& this._objSessions.hasOwnProperty(incomingRequest.connectionID)
			&& this._objSessions[incomingRequest.connectionID]
			&& this._objSessions[incomingRequest.connectionID].partyMembership !== null
		)
		{
			incomingRequest.isAuthenticated = true;
			incomingRequest.isAuthorized = this._objSessions[incomingRequest.connectionID].authorized;
		}
	}

	/**
	 * This is called after a function has been called successfully.
	 *
	 * @param {JSONRPC.IncomingRequest} incomingRequest
	 */
	async result(incomingRequest)
	{
		if(incomingRequest.requestObject.method === "ImHereForTheParty")
		{
			assert(typeof incomingRequest.connectionID === "number");

			if(
				this._objSessions.hasOwnProperty(incomingRequest.connectionID)
				&& this._objSessions[incomingRequest.connectionID].partyMembership !== null
			)
			{
				// Maybe race condition somewhere from alternating authenticated IDs.
				incomingRequest.callResult = new JSONRPC.Exception("Not authorized. Current connnection " + incomingRequest.connectionID + " was already authenticated.", JSONRPC.Exception.NOT_AUTHORIZED);

				return;
			}

			if(!this._objSessions.hasOwnProperty(incomingRequest.connectionID))
			{
				throw new Error("addConnection was not called with connection id " + JSON.stringify(incomingRequest.connectionID) + ".");
			}

			assert(!(incomingRequest.callResult instanceof Error));
			this._objSessions[incomingRequest.connectionID].partyMembership = incomingRequest.callResult;

			// bDoNotAuthorizeMe param.
			assert(typeof incomingRequest.requestObject.params[2] === "boolean");
			this._objSessions[incomingRequest.connectionID].authorized = !incomingRequest.requestObject.params[2];

			this._objATeamMemberToConnectionID[incomingRequest.callResult.teamMember] = incomingRequest.connectionID;
		}
	}

	/**
	 * @param {number} nWebSocketConnectionID
	 * @param {WebSocket} webSocket
	 */
	addConnection(nWebSocketConnectionID, webSocket)
	{
		assert(typeof nWebSocketConnectionID === "number");

		this._objSessions[nWebSocketConnectionID] = {
			partyMembership: null,
			authorized: false,
			connectionID: nWebSocketConnectionID
		};

		webSocket.on(
			"close",
			(code, message) => {
				if(
					this._objSessions.hasOwnProperty(nWebSocketConnectionID)
					&& this._objSessions[nWebSocketConnectionID].partyMembership
					&& this._objATeamMemberToConnectionID.hasOwnProperty(this._objSessions[nWebSocketConnectionID].partyMembership.teamMember)
				)
				{
					delete this._objATeamMemberToConnectionID[this._objSessions[nWebSocketConnectionID].partyMembership.teamMember];
				}

				delete this._objSessions[nWebSocketConnectionID];
			}
		);
	}

	/**
	 * @param {string} strATeamMember
	 *
	 * @returns {number}
	 */
	aTeamMemberToConnectionID(strATeamMember)
	{
		if(!this._objATeamMemberToConnectionID.hasOwnProperty(strATeamMember))
		{
			throw new Error("The team member is not logged in!!!");
		}

		return this._objATeamMemberToConnectionID[strATeamMember];
	}
};
<|endoftext|>


<commit_before><commit_msg>Remove horizontal bar chart code duplication<commit_after><|endoftext|>


<commit_before>import Ember from 'ember';

export default Ember.Route.extend({
  model() {
    const formActionSchema = {
      "schema": {
        "title": "Your Information",
        "type": "object",
        "properties": {
          "firstName": {
            "title": "First Name",
            "type": "string"
          },
          "lastName": {
            "title": "Last Name",
            "type": "string"
          },
          "age": {
            "title": "Age",
            "type": "integer",
            "minimum": 0,
            "maximum": 100
          }
        }
      },
      "options": {
        "focus":false,
        "form": {
          "attributes": {
            "action": "http://httpbin.org/post",
            "method": "post"
          },
          "buttons": {
            "noop": {
              "type": "button",
              "value": "Do Nothing",
              "styles": "btn btn-primary"
            },
            "validate": {
              "title": "Validate and view JSON!"
            },
            "submit": {
              "id": "mySubmit",
              "attributes": {
                "data-test": "123"
              }
            }
          }
        }
      }
    };
    const formActions = {
      noop: function () {
        alert("Ain't gonna do it");
      },
      submit: function () {
        this.ajaxSubmit().always(function() {
          alert("Form submitted!");
        });
      },
      validate: function () {
        this.refreshValidationState(true);
        if (this.isValid(true)) {
          var value = this.getValue();
          alert(JSON.stringify(value, null, "  "));
        }
      }
    };
    return { formActionSchema, formActions };
  }
});
<commit_msg>fix jshint for alerts<commit_after>import Ember from 'ember';

export default Ember.Route.extend({
  model() {
    const formActionSchema = {
      "schema": {
        "title": "Your Information",
        "type": "object",
        "properties": {
          "firstName": {
            "title": "First Name",
            "type": "string"
          },
          "lastName": {
            "title": "Last Name",
            "type": "string"
          },
          "age": {
            "title": "Age",
            "type": "integer",
            "minimum": 0,
            "maximum": 100
          }
        }
      },
      "options": {
        "focus":false,
        "form": {
          "attributes": {
            "action": "http://httpbin.org/post",
            "method": "post"
          },
          "buttons": {
            "noop": {
              "type": "button",
              "value": "Do Nothing",
              "styles": "btn btn-primary"
            },
            "validate": {
              "title": "Validate and view JSON!"
            },
            "submit": {
              "id": "mySubmit",
              "attributes": {
                "data-test": "123"
              }
            }
          }
        }
      }
    };
    const formActions = {
      noop: function () {
        window.alert("Ain't gonna do it");
      },
      submit: function () {
        this.ajaxSubmit().always(function() {
          window.alert("Form submitted!");
        });
      },
      validate: function () {
        this.refreshValidationState(true);
        if (this.isValid(true)) {
          var value = this.getValue();
          window.alert(JSON.stringify(value, null, "  "));
        }
      }
    };
    return { formActionSchema, formActions };
  }
});
<|endoftext|>


<commit_before>dojo.provide("dojox.lang.oo.declare");

dojo.experimental("dojox.lang.oo.declare");

// a drop-in replacement for dojo.declare() with fixed bugs and enhancements

(function(){
	var d = dojo, oo = dojox.lang.oo, op = Object.prototype,
		cname = "constructor", has = "hasOwnProperty", dname = "declaredClass",
		isF = d.isFunction, each = d.forEach, xtor = function(){}, counter = 0;

	function err(msg){ throw new Error("declare: " + msg); }

	// C3 Method Resolution Order (see http://www.python.org/download/releases/2.3/mro/)
	function c3mro(bases){
		var result = [0], l = bases.length, classes = new Array(l),
			i = 0, j, m, m2, c, cls, lin, proto, name, clsNum = 0;

		// initialize
		for(; i < l; ++i){
			c = bases[i];
			if(!c) err("mixin #" + i + " is null");
			lin = c._meta && c._meta.bases || [c];
			clsNum += lin.length;
			m = {};
			for(j = 0, m2 = lin.length; j < m2; ++j){
				// the assignment on the next line is intentional
				proto = (cls = lin[j]).prototype;
				name = proto[has](dname) && proto[dname];
				if(!name) name = proto[dname] = "dojoUniqClassName_" + (counter++);
				m[name] = cls;
			}
			classes[i] = {
				idx: 0,
				map: m,
				lin: d.map(lin, function(c){ return c.prototype[dname]; })
			};
		}

		// C3 MRO algorithm
		while(clsNum){
			for(i = l; i--;){
				m = classes[i];
				c = m.lin[m.idx];
				if(c){
					// check if it is in the tail of any classes
					for(j = l; j--;){
						m2 = classes[j];
						if(i != j && (c in m2.map) && c != m2.lin[m2.idx]) break;
					}
					if(j < 0){
						result.push(m.map[c]);
						// remove c from all heads
						for(j = l; j--;){
							m = classes[j];
							if(c == m.lin[m.idx]){
								++m.idx;
								--clsNum
							}
						}
						break;
					}
				}
			}
			if(i < 0) err("can't build consistent linearization");
		}

		return result;
	}

	oo.makeDeclare = function(ctorSpecial, chains){
		chains = chains || {};

		function buildMethodList(bases, name){
			var methods = [], i = 0, l = bases.length, h, b;
			for(;i < l; ++i){
				b = bases[i];
				// the assignment on the next line is intentional
				if(h = b._meta) (h = h.hidden)[has](name) && methods.push(h[name]);
				else
					// the assignment on the next line is intentional
					(name == cname) && methods.push(b) ||
						(h = b.prototype[name]) && h !== op[name] && methods.push(h);
			}
			name != cname && (h = op[name]) && methods.push(h);
			return chains[name] === "after" ? methods.reverse() : methods;
		}

		function inherited(args, a, b){
			var c = this.constructor, m = c._meta, cache = c._cache,
				caller, i, l, f, n, ch, x, name;

			// crack arguments
			if(typeof args == "string"){
				name = args;
				args = a;
				a = b;
			}

			caller = inherited.caller;
			n = caller.nom;
			if(n && name && n !== name) err("calling inherited() with a different name: " + name);
			name = name || n;
			ch = cache[has](name) && cache[name];

			// get the cached method list
			if(!ch){
				if(!name) err("can't deduce a name to call inherited()");
				if(name == cname && ctorSpecial) err("calling constructor as inherited");
				if(chains[has](name)) err("calling chained method as inherited: " + name);
				ch = cache[name] = buildMethodList(m.bases, name);
			}

			// alternative (simpler) caching
			x = this._inherited;
			if(!x || x.name !== name || ch[x.pos] !== caller || caller.caller !== inherited){
				// find the caller
				for(i = 0, l = ch.length; i < l && ch[i] !== caller; ++i);
				// the assignment on the next line is intentional
				if(i == l) this[name] === caller && (i = -1) || err("can't find the caller for inherited()");
				// the assignment on the next line is intentional
				this._inherited = x = {name: name, pos: i};
			}
			f = ch[++x.pos];
			return f ? f.apply(this, a || args) : undefined;
		}

		return function(className, superclass, props){
			var mixins, proto, i, l, t, ctor, ctorChain, name, bases;

			// crack parameters
			if(typeof className != "string"){
				props = superclass;
				superclass = className;
				className = "";
			}
			props = props || {};

			// build a prototype
			if(superclass){
				// multiple inheritance (potentially)
				bases = d.isArray(superclass) ? c3mro(superclass) :
					[0].concat((t = superclass._meta) && t.bases || [superclass]);
				// the assignment on the next line is intentional
				superclass = bases[l = bases.length - 1];
				for(i = l - 1;;){
					t = bases[i--];
					// delegation
					xtor.prototype = superclass.prototype;
					proto = new xtor;
					if(!t) break;
					d._mixin(proto, t.prototype);
					(ctor = function(){}).superclass = superclass;
					ctor.prototype = proto;
					superclass = proto.constructor = ctor;
				}
				xtor.prototype = 0;	// cleanup
			}else{
				bases = [0];
				proto = {};
			}

			// add metadata for incoming functions
			for(name in props) (t = props[name]) !== op[name] && isF(t) && (t.nom = name);
			each(d._extraNames, function(name, t){ (t = props[name]) !== op[name] && isF(t) && (t.nom = name); });

			// add props
			d._mixin(proto, props);

			// build ctor
			if(ctorSpecial){
				// compatibility mode with the legacy dojo.declare()
				ctor = function(){
					var a = arguments, args = a, a0, f, i, l, h, preArgs;
					this._inherited = 0;
					// perform the shaman's rituals of the original dojo.declare()
					// 1) call two types of the preamble
					if((a0 = a[0]) && a0.preamble || this.preamble){
						// full blown ritual
						preArgs = new Array(bases.length);
						// prepare parameters
						preArgs[0] = a;
						for(i = 0, l = bases.length - 1; i < l;){
							// the assignment on the next line is intentional
							a = (a0 = a[0]) && (f = a0.preamble) && f.apply(this, a) || a;
							// the assignment on the next line is intentional
							a = (f = bases[i]._meta.hidden.preamble) && f.apply(this, a) || a;
							preArgs[++i] = a;
						}
						// call all constructors
						for(; i >= 0; --i){
							h = bases[i]._meta.hidden;
							h[has](cname) && h.constructor.apply(this, preArgs[i]);
						}
					}else{
						// reduced ritual
						// 2) call the constructor with the same parameters
						for(i = ctorChain.length - 1; i >= 0; ctorChain[i--].apply(this, a));
					}
					// 3) continue the original ritual: call the postscript
					// the assignment on the next line is intentional
					(f = this.postscript) && f.apply(this, args);
				};
			}else{
				if(chains[has](cname)){
					// chained constructor
					ctor = function(){
						var a = arguments, f, i, l;
						this._inherited = 0;
						// perform the shaman's rituals of the original dojo.declare()
						// 1) do not call the preamble
						// 2) call the constructor with the same parameters
						for(i = 0, l = ctorChain.length; i < l; ctorChain[i++].apply(this, a));
						// 3) call the postscript
						// the assignment on the next line is intentional
						(f = this.postscript) && f.apply(this, a);
					};
				}else{
					// plain vanilla constructor
					ctor = function(){
						var a = arguments, f;
						this._inherited = 0;
						// perform the shaman's rituals of the original dojo.declare()
						// 1) do not call the preamble
						// 2) call our original constructor
						// the assignment on the next line is intentional
						(f = ctorChain[0]) && f.apply(this, a);
						// 3) call the postscript
						// the assignment on the next line is intentional
						(f = this.postscript) && f.apply(this, a);
					};
				}
			}

			// build metadata on the constructor
			bases[0] = ctor;
			ctor._meta  = {bases: bases, hidden: props};
			ctor._cache = {};
			ctor.superclass = superclass && superclass.prototype;

			proto.constructor = ctor;
			ctor.prototype = proto;

			// add "standard" methods to the ptototype
			proto.inherited = inherited;
			proto.isInstanceOf = function(cls){
				for(var i = 0, l = bases.length; i < l; ++i){
					if(bases[i] === cls) return true;
				}
				return this instanceof cls;
			};

			// the assignment on the next line is intentional
			className && d.setObject(proto[dname] = className, ctor);

			// build chains and add them to the prototype
			function bindChain(name){
				if(typeof chains[name] == "string")
					(proto[name] = function(){
						var t = buildMethodList(bases, name), l = t.length,
							f = function(){ for(var i = 0; i < l; ++i){ t[i].apply(this, arguments); } };
						f.nom = name;
						// memoization
						// the assignment on the next line is intentional
						(ctor.prototype[name] = f).apply(this, arguments);
					}).nom = name;
			}
			for(name in chains){ bindChain(name); }
			//each(d._extraNames, bindChain); // no need to chain functions
			ctorChain = buildMethodList(bases, cname);

			return ctor;	// Function
		};
	};

	oo.declare = oo.makeDeclare(true);

	/*=====
	//	summary:
	//		Create a feature-rich constructor from compact notation
	//	className: String?:
	//		The optional name of the constructor (loosely, a "class")
	//		stored in the "declaredClass" property in the created prototype
	//	superclass: Function|Function[]:
	//		May be null, a Function, or an Array of Functions. If an array,
	//		the first element is used as the prototypical ancestor and
	//		any following Functions become mixin ancestors.
	//	props: Object:
	//		An object whose properties are copied to the created prototype.
	//		Add an instance-initialization function by making it a property
	//		named "constructor".
	//	description:
	//		Create a constructor using a compact notation for inheritance and
	//		prototype extension.
	//
	//		Mixin ancestors provide a type of multiple inheritance. Prototypes of mixin
	//		ancestors are copied to the new class: changes to mixin prototypes will
	//		not affect classes to which they have been mixed in.
	//
	//		"className" is cached in "declaredClass" property of the new class.
	//
	//	example:
	//	|	dojox.lang.oo.declare("my.classes.bar", my.classes.foo, {
	//	|		// properties to be added to the class prototype
	//	|		someValue: 2,
	//	|		// initialization function
	//	|		constructor: function(){
	//	|			this.myComplicatedObject = new ReallyComplicatedObject();
	//	|		},
	//	|		// other functions
	//	|		someMethod: function(){
	//	|			doStuff();
	//	|		}
	//	|	});
	=====*/
})();
<commit_msg>lang.oo: minor refactoring of the prototype-building code in oo.declare, !strict.<commit_after>dojo.provide("dojox.lang.oo.declare");

dojo.experimental("dojox.lang.oo.declare");

// a drop-in replacement for dojo.declare() with fixed bugs and enhancements

(function(){
	var d = dojo, oo = dojox.lang.oo, op = Object.prototype,
		cname = "constructor", has = "hasOwnProperty", dname = "declaredClass",
		isF = d.isFunction, each = d.forEach, xtor = function(){}, counter = 0;

	function err(msg){ throw new Error("declare: " + msg); }

	// C3 Method Resolution Order (see http://www.python.org/download/releases/2.3/mro/)
	function c3mro(bases){
		var result = [0], l = bases.length, classes = new Array(l),
			i = 0, j, m, m2, c, cls, lin, proto, name, clsNum = 0;

		// initialize
		for(; i < l; ++i){
			c = bases[i];
			if(!c) err("mixin #" + i + " is null");
			lin = c._meta && c._meta.bases || [c];
			clsNum += lin.length;
			m = {};
			for(j = 0, m2 = lin.length; j < m2; ++j){
				// the assignment on the next line is intentional
				proto = (cls = lin[j]).prototype;
				name = proto[has](dname) && proto[dname];
				if(!name) name = proto[dname] = "dojoUniqClassName_" + (counter++);
				m[name] = cls;
			}
			classes[i] = {
				idx: 0,
				map: m,
				lin: d.map(lin, function(c){ return c.prototype[dname]; })
			};
		}

		// C3 MRO algorithm
		while(clsNum){
			for(i = l; i--;){
				m = classes[i];
				c = m.lin[m.idx];
				if(c){
					// check if it is in the tail of any classes
					for(j = l; j--;){
						m2 = classes[j];
						if(i != j && (c in m2.map) && c != m2.lin[m2.idx]) break;
					}
					if(j < 0){
						result.push(m.map[c]);
						// remove c from all heads
						for(j = l; j--;){
							m = classes[j];
							if(c == m.lin[m.idx]){
								++m.idx;
								--clsNum
							}
						}
						break;
					}
				}
			}
			if(i < 0) err("can't build consistent linearization");
		}

		return result;
	}

	oo.makeDeclare = function(ctorSpecial, chains){
		chains = chains || {};

		function buildMethodList(bases, name){
			var methods = [], i = 0, l = bases.length, h, b;
			for(;i < l; ++i){
				b = bases[i];
				// the assignment on the next line is intentional
				if(h = b._meta) (h = h.hidden)[has](name) && methods.push(h[name]);
				else
					// the assignment on the next line is intentional
					(name == cname) && methods.push(b) ||
						(h = b.prototype[name]) && h !== op[name] && methods.push(h);
			}
			name != cname && (h = op[name]) && methods.push(h);
			return chains[name] === "after" ? methods.reverse() : methods;
		}

		function inherited(args, a, b){
			var c = this.constructor, m = c._meta, cache = c._cache,
				caller, i, l, f, n, ch, x, name;

			// crack arguments
			if(typeof args == "string"){
				name = args;
				args = a;
				a = b;
			}

			caller = inherited.caller;
			n = caller.nom;
			if(n && name && n !== name) err("calling inherited() with a different name: " + name);
			name = name || n;
			ch = cache[has](name) && cache[name];

			// get the cached method list
			if(!ch){
				if(!name) err("can't deduce a name to call inherited()");
				if(name == cname && ctorSpecial) err("calling constructor as inherited");
				if(chains[has](name)) err("calling chained method as inherited: " + name);
				ch = cache[name] = buildMethodList(m.bases, name);
			}

			// alternative (simpler) caching
			x = this._inherited;
			if(!x || x.name !== name || ch[x.pos] !== caller || caller.caller !== inherited){
				// find the caller
				for(i = 0, l = ch.length; i < l && ch[i] !== caller; ++i);
				// the assignment on the next line is intentional
				if(i == l) this[name] === caller && (i = -1) || err("can't find the caller for inherited()");
				// the assignment on the next line is intentional
				this._inherited = x = {name: name, pos: i};
			}
			f = ch[++x.pos];
			return f ? f.apply(this, a || args) : undefined;
		}

		return function(className, superclass, props){
			var mixins, proto, i, l, t, ctor, ctorChain, name, bases;

			// crack parameters
			if(typeof className != "string"){
				props = superclass;
				superclass = className;
				className = "";
			}
			props = props || {};

			// build a prototype
			if(d.isArray(superclass)) bases = c3mro(superclass);
			else{
				bases = [0];
				if(superclass) (t = superclass._meta) && (bases = bases.concat(t.bases)) || bases.push(superclass);
			}
			// the assignment on the next line is intentional
			superclass = bases[l = bases.length - 1];
			if(superclass) for(i = l - 1;;){
				t = bases[i--];
				// delegation
				xtor.prototype = superclass.prototype;
				proto = new xtor;
				if(!t) break;
				d._mixin(proto, t.prototype);
				(ctor = function(){}).superclass = superclass;
				ctor.prototype = proto;
				superclass = proto.constructor = ctor;
			}
			else proto = {};
			xtor.prototype = 0;	// cleanup

			// add metadata for incoming functions
			for(name in props) (t = props[name]) !== op[name] && isF(t) && (t.nom = name);
			each(d._extraNames, function(name, t){ (t = props[name]) !== op[name] && isF(t) && (t.nom = name); });

			// add props
			d._mixin(proto, props);

			// build ctor
			if(ctorSpecial){
				// compatibility mode with the legacy dojo.declare()
				ctor = function(){
					var a = arguments, args = a, a0, f, i, l, h, preArgs;
					this._inherited = 0;
					// perform the shaman's rituals of the original dojo.declare()
					// 1) call two types of the preamble
					if((a0 = a[0]) && a0.preamble || this.preamble){
						// full blown ritual
						preArgs = new Array(bases.length);
						// prepare parameters
						preArgs[0] = a;
						for(i = 0, l = bases.length - 1; i < l;){
							// the assignment on the next line is intentional
							a = (a0 = a[0]) && (f = a0.preamble) && f.apply(this, a) || a;
							// the assignment on the next line is intentional
							a = (f = bases[i]._meta.hidden.preamble) && f.apply(this, a) || a;
							preArgs[++i] = a;
						}
						// call all constructors
						for(; i >= 0; --i){
							h = bases[i]._meta.hidden;
							h[has](cname) && h.constructor.apply(this, preArgs[i]);
						}
					}else{
						// reduced ritual
						// 2) call the constructor with the same parameters
						for(i = ctorChain.length - 1; i >= 0; ctorChain[i--].apply(this, a));
					}
					// 3) continue the original ritual: call the postscript
					// the assignment on the next line is intentional
					(f = this.postscript) && f.apply(this, args);
				};
			}else{
				if(chains[has](cname)){
					// chained constructor
					ctor = function(){
						var a = arguments, f, i, l;
						this._inherited = 0;
						// perform the shaman's rituals of the original dojo.declare()
						// 1) do not call the preamble
						// 2) call the constructor with the same parameters
						for(i = 0, l = ctorChain.length; i < l; ctorChain[i++].apply(this, a));
						// 3) call the postscript
						// the assignment on the next line is intentional
						(f = this.postscript) && f.apply(this, a);
					};
				}else{
					// plain vanilla constructor
					ctor = function(){
						var a = arguments, f;
						this._inherited = 0;
						// perform the shaman's rituals of the original dojo.declare()
						// 1) do not call the preamble
						// 2) call our original constructor
						// the assignment on the next line is intentional
						(f = ctorChain[0]) && f.apply(this, a);
						// 3) call the postscript
						// the assignment on the next line is intentional
						(f = this.postscript) && f.apply(this, a);
					};
				}
			}

			// build metadata on the constructor
			bases[0] = ctor;
			ctor._meta  = {bases: bases, hidden: props};
			ctor._cache = {};
			ctor.superclass = superclass && superclass.prototype;

			proto.constructor = ctor;
			ctor.prototype = proto;

			// add "standard" methods to the ptototype
			proto.inherited = inherited;
			proto.isInstanceOf = function(cls){
				for(var i = 0, l = bases.length; i < l; ++i){
					if(bases[i] === cls) return true;
				}
				return this instanceof cls;
			};

			// the assignment on the next line is intentional
			className && d.setObject(proto[dname] = className, ctor);

			// build chains and add them to the prototype
			function bindChain(name){
				if(typeof chains[name] == "string")
					(proto[name] = function(){
						var t = buildMethodList(bases, name), l = t.length,
							f = function(){ for(var i = 0; i < l; ++i){ t[i].apply(this, arguments); } };
						f.nom = name;
						// memoization
						// the assignment on the next line is intentional
						(ctor.prototype[name] = f).apply(this, arguments);
					}).nom = name;
			}
			for(name in chains){ bindChain(name); }
			//each(d._extraNames, bindChain); // no need to chain functions
			ctorChain = buildMethodList(bases, cname);

			return ctor;	// Function
		};
	};

	oo.declare = oo.makeDeclare(true);

	/*=====
	//	summary:
	//		Create a feature-rich constructor from compact notation
	//	className: String?:
	//		The optional name of the constructor (loosely, a "class")
	//		stored in the "declaredClass" property in the created prototype
	//	superclass: Function|Function[]:
	//		May be null, a Function, or an Array of Functions. If an array,
	//		the first element is used as the prototypical ancestor and
	//		any following Functions become mixin ancestors.
	//	props: Object:
	//		An object whose properties are copied to the created prototype.
	//		Add an instance-initialization function by making it a property
	//		named "constructor".
	//	description:
	//		Create a constructor using a compact notation for inheritance and
	//		prototype extension.
	//
	//		Mixin ancestors provide a type of multiple inheritance. Prototypes of mixin
	//		ancestors are copied to the new class: changes to mixin prototypes will
	//		not affect classes to which they have been mixed in.
	//
	//		"className" is cached in "declaredClass" property of the new class.
	//
	//	example:
	//	|	dojox.lang.oo.declare("my.classes.bar", my.classes.foo, {
	//	|		// properties to be added to the class prototype
	//	|		someValue: 2,
	//	|		// initialization function
	//	|		constructor: function(){
	//	|			this.myComplicatedObject = new ReallyComplicatedObject();
	//	|		},
	//	|		// other functions
	//	|		someMethod: function(){
	//	|			doStuff();
	//	|		}
	//	|	});
	=====*/
})();
<|endoftext|>


<commit_before>"use strict";

// Extend the object
var extend = function(template, fields) {
  var object = {};
  for(var name in template) {
    object[name] = template[name];
  }

  for(var name in fields) {
   object[name] = fields[name];
  }

  return object;
}

exports['Successful connection to replicaset of 1 primary, 1 secondary and 1 arbiter'] = {
  metadata: {
    requires: {
      generators: true,
      topology: "single"
    }
  },

  test: function(configuration, test) {
    var ReplSet = configuration.require.ReplSet,
      ObjectId = configuration.require.BSON.ObjectId,
      ReadPreference = configuration.require.ReadPreference,
      Long = configuration.require.BSON.Long,
      co = require('co'),
      mockupdb = require('../../../mock');

    // Contain mock server
    var primaryServer = null;
    var firstSecondaryServer = null;
    var arbiterServer = null;
    var running = true;
    var electionIds = [new ObjectId(), new ObjectId()];

    // Default message fields
    var defaultFields = {
      "setName": "rs", "setVersion": 1, "electionId": electionIds[0],
      "maxBsonObjectSize" : 16777216, "maxMessageSizeBytes" : 48000000,
      "maxWriteBatchSize" : 1000, "localTime" : new Date(), "maxWireVersion" : 4,
      "minWireVersion" : 0, "ok" : 1, "hosts": ["localhost:32000", "localhost:32001", "localhost:32002"], "arbiters": ["localhost:32002"]
    }

    // Primary server states
    var primary = [extend(defaultFields, {
      "ismaster":true, "secondary":false, "me": "localhost:32000", "primary": "localhost:32000", "tags" : { "loc" : "ny" }
    })];

    // Primary server states
    var firstSecondary = [extend(defaultFields, {
      "ismaster":false, "secondary":true, "me": "localhost:32001", "primary": "localhost:32000", "tags" : { "loc" : "sf" }
    })];

    // Primary server states
    var arbiter = [extend(defaultFields, {
      "ismaster":false, "secondary":false, "arbiterOnly": true, "me": "localhost:32002", "primary": "localhost:32000"
    })];

    // Boot the mock
    co(function*() {
      primaryServer = yield mockupdb.createServer(32000, 'localhost');
      firstSecondaryServer = yield mockupdb.createServer(32001, 'localhost');
      arbiterServer = yield mockupdb.createServer(32002, 'localhost');

      // Primary state machine
      co(function*() {
        while(running) {
          var request = yield primaryServer.receive();
          var doc = request.document;

          if(doc.ismaster) {
            request.reply(primary[0]);
          }
        }
      }).catch(function(err) {
        console.log(err.stack);
      });

      // First secondary state machine
      co(function*() {
        while(running) {
          var request = yield firstSecondaryServer.receive();
          var doc = request.document;

          if(doc.ismaster) {
            request.reply(firstSecondary[0]);
          }
        }
      }).catch(function(err) {
        console.log(err.stack);
      });

      // Second secondary state machine
      co(function*() {
        while(running) {
          var request = yield arbiterServer.receive();
          var doc = request.document;

          if(doc.ismaster) {
            request.reply(arbiter[0]);
          }
        }
      }).catch(function(err) {
        console.log(err.stack);
      });
    });

    // Attempt to connect
    var server = new ReplSet([
      { host: 'localhost', port: 32000 },
      { host: 'localhost', port: 32001 },
      { host: 'localhost', port: 32002 }], {
        setName: 'rs',
        connectionTimeout: 3000,
        socketTimeout: 0,
        haInterval: 2000,
        size: 1
    });

    server.on('joined', function(_type) {
      if(_type == 'arbiter' || _type == 'secondary' || _type == 'primary') {
        if(server.s.replState.secondaries.length == 1
          && server.s.replState.arbiters.length == 1
          && server.s.replState.primary) {
            test.equal(1, server.s.replState.secondaries.length);
            test.equal('localhost:32001', server.s.replState.secondaries[0].name);

            test.equal(1, server.s.replState.arbiters.length);
            test.equal('localhost:32002', server.s.replState.arbiters[0].name);

            test.ok(server.s.replState.primary != null);
            test.equal('localhost:32000', server.s.replState.primary.name);

            primaryServer.destroy();
            firstSecondaryServer.destroy();
            arbiterServer.destroy();
            server.destroy();
            running = false;

            test.done();
          }
      }
    });

    server.on('connect', function(e) {
      server.__connected = true;
    });

    // Add event listeners
    server.on('fullsetup', function(_server) {});
    // Gives proxies a chance to boot up
    setTimeout(function() {
      server.connect();
    }, 100)
  }
}

exports['Successful connection to replicaset of 1 primary, 1 secondary but missing arbiter'] = {
  metadata: {
    requires: {
      generators: true,
      topology: "single"
    }
  },

  test: function(configuration, test) {
    var ReplSet = configuration.require.ReplSet,
      ObjectId = configuration.require.BSON.ObjectId,
      ReadPreference = configuration.require.ReadPreference,
      Long = configuration.require.BSON.Long,
      co = require('co'),
      mockupdb = require('../../../mock');

    // Contain mock server
    var primaryServer = null;
    var firstSecondaryServer = null;
    var secondSecondaryServer = null;
    var running = true;
    var electionIds = [new ObjectId(), new ObjectId()];

    // Default message fields
    var defaultFields = {
      "setName": "rs", "setVersion": 1, "electionId": electionIds[0],
      "maxBsonObjectSize" : 16777216, "maxMessageSizeBytes" : 48000000,
      "maxWriteBatchSize" : 1000, "localTime" : new Date(), "maxWireVersion" : 4,
      "minWireVersion" : 0, "ok" : 1, "hosts": ["localhost:32000", "localhost:32001", "localhost:32002"], "arbiters": ["localhost:32002"]
    }

    // Primary server states
    var primary = [extend(defaultFields, {
      "ismaster":true, "secondary":false, "me": "localhost:32000", "primary": "localhost:32000", "tags" : { "loc" : "ny" }
    })];

    // Primary server states
    var firstSecondary = [extend(defaultFields, {
      "ismaster":false, "secondary":true, "me": "localhost:32001", "primary": "localhost:32000", "tags" : { "loc" : "sf" }
    })];

    // Boot the mock
    co(function*() {
      primaryServer = yield mockupdb.createServer(32000, 'localhost');
      firstSecondaryServer = yield mockupdb.createServer(32001, 'localhost');

      // Primary state machine
      co(function*() {
        while(running) {
          var request = yield primaryServer.receive();
          var doc = request.document;

          if(doc.ismaster) {
            request.reply(primary[0]);
          }
        }
      }).catch(function(err) {
        console.log(err.stack);
      });

      // First secondary state machine
      co(function*() {
        while(running) {
          var request = yield firstSecondaryServer.receive();
          var doc = request.document;

          if(doc.ismaster) {
            request.reply(firstSecondary[0]);
          }
        }
      }).catch(function(err) {
        console.log(err.stack);
      });
    });

    // Attempt to connect
    var server = new ReplSet([
      { host: 'localhost', port: 32000 },
      { host: 'localhost', port: 32001 },
      { host: 'localhost', port: 32002 }], {
        setName: 'rs',
        connectionTimeout: 3000,
        socketTimeout: 0,
        haInterval: 2000,
        size: 1
    });

    // Add event listeners
    server.on('fullsetup', function(_server) {
      test.equal(true, server.__connected);

      test.equal(1, server.s.replState.secondaries.length);
      test.equal('localhost:32001', server.s.replState.secondaries[0].name);

      test.equal(0, server.s.replState.arbiters.length);

      test.ok(server.s.replState.primary != null);
      test.equal('localhost:32000', server.s.replState.primary.name);

      primaryServer.destroy();
      firstSecondaryServer.destroy();
      server.destroy();
      running = false;

      test.done();
    });

    server.on('connect', function(e) {
      server.__connected = true;
    });

    // Gives proxies a chance to boot up
    setTimeout(function() {
      server.connect();
    }, 100)
  }
}

exports['Fail to connect due to missing primary'] = {
  metadata: {
    requires: {
      generators: true,
      topology: "single"
    }
  },

  test: function(configuration, test) {
    var ReplSet = configuration.require.ReplSet,
      ObjectId = configuration.require.BSON.ObjectId,
      ReadPreference = configuration.require.ReadPreference,
      Long = configuration.require.BSON.Long,
      co = require('co'),
      mockupdb = require('../../../mock');

    // Contain mock server
    var firstSecondaryServer = null;
    var running = true;
    var electionIds = [new ObjectId(), new ObjectId()];

    // Default message fields
    var defaultFields = {
      "setName": "rs", "setVersion": 1, "electionId": electionIds[0],
      "maxBsonObjectSize" : 16777216, "maxMessageSizeBytes" : 48000000,
      "maxWriteBatchSize" : 1000, "localTime" : new Date(), "maxWireVersion" : 4,
      "minWireVersion" : 0, "ok" : 1, "hosts": ["localhost:32000", "localhost:32001", "localhost:32002"], "arbiters": ["localhost:32002"]
    }

    // Primary server states
    var firstSecondary = [extend(defaultFields, {
      "ismaster":false, "secondary":true, "me": "localhost:32001", "primary": "localhost:32000", "tags" : { "loc" : "sf" }
    })];

    // Boot the mock
    co(function*() {
      firstSecondaryServer = yield mockupdb.createServer(32001, 'localhost');

      // First secondary state machine
      co(function*() {
        while(running) {
          var request = yield firstSecondaryServer.receive();
          var doc = request.document;

          if(doc.ismaster) {
            request.reply(firstSecondary[0]);
          }
        }
      }).catch(function(err) {
        console.log(err.stack);
      });
    });

    // Attempt to connect
    var server = new ReplSet([
      { host: 'localhost', port: 32000 },
      { host: 'localhost', port: 32001 },
      { host: 'localhost', port: 32002 }], {
        setName: 'rs',
        connectionTimeout: 3000,
        socketTimeout: 0,
        haInterval: 2000,
        size: 1
    });

    server.on('error', function(error) {
      server.destroy();
      firstSecondaryServer.destroy();
      running = false;
      test.done();
    });

    // Gives proxies a chance to boot up
    setTimeout(function() {
      server.connect();
    }, 100)
  }
}

exports['Successful connection to replicaset of 0 primary, 1 secondary and 1 arbiter with secondaryOnlyConnectionAllowed'] = {
  metadata: {
    requires: {
      generators: true,
      topology: "single"
    }
  },

  test: function(configuration, test) {
    var ReplSet = configuration.require.ReplSet,
      ObjectId = configuration.require.BSON.ObjectId,
      ReadPreference = configuration.require.ReadPreference,
      Long = configuration.require.BSON.Long,
      co = require('co'),
      mockupdb = require('../../../mock');

    // Contain mock server
    var firstSecondaryServer = null;
    var arbiterServer = null;
    var running = true;
    var electionIds = [new ObjectId(), new ObjectId()];

    // Default message fields
    var defaultFields = {
      "setName": "rs", "setVersion": 1, "electionId": electionIds[0],
      "maxBsonObjectSize" : 16777216, "maxMessageSizeBytes" : 48000000,
      "maxWriteBatchSize" : 1000, "localTime" : new Date(), "maxWireVersion" : 4,
      "minWireVersion" : 0, "ok" : 1, "hosts": ["localhost:32000", "localhost:32001", "localhost:32002"], "arbiters": ["localhost:32002"]
    }

    // Primary server states
    var firstSecondary = [extend(defaultFields, {
      "ismaster":false, "secondary":true, "me": "localhost:32001", "primary": "localhost:32000", "tags" : { "loc" : "sf" }
    })];

    // Primary server states
    var arbiter = [extend(defaultFields, {
      "ismaster":false, "secondary":false, "arbiterOnly": true, "me": "localhost:32002", "primary": "localhost:32000"
    })];

    // Boot the mock
    co(function*() {
      firstSecondaryServer = yield mockupdb.createServer(32001, 'localhost');
      arbiterServer = yield mockupdb.createServer(32002, 'localhost');

      // First secondary state machine
      co(function*() {
        while(running) {
          var request = yield firstSecondaryServer.receive();
          var doc = request.document;

          if(doc.ismaster) {
            request.reply(firstSecondary[0]);
          }
        }
      }).catch(function(err) {
        console.log(err.stack);
      });

      // Second secondary state machine
      co(function*() {
        while(running) {
          var request = yield arbiterServer.receive();
          var doc = request.document;

          if(doc.ismaster) {
            request.reply(arbiter[0]);
          }
        }
      }).catch(function(err) {
        console.log(err.stack);
      });
    });

    // Attempt to connect
    var server = new ReplSet([
      { host: 'localhost', port: 32000 },
      { host: 'localhost', port: 32001 },
      { host: 'localhost', port: 32002 }], {
        setName: 'rs',
        connectionTimeout: 3000,
        socketTimeout: 0,
        haInterval: 2000,
        size: 1,
        secondaryOnlyConnectionAllowed: true
    });

    server.on('joined', function(_type) {
      if(server.s.replState.secondaries.length == 1
        && server.s.replState.arbiters.length == 1) {
          test.equal(true, server.__connected);

          test.equal(1, server.s.replState.secondaries.length);
          test.equal('localhost:32001', server.s.replState.secondaries[0].name);

          test.equal(1, server.s.replState.arbiters.length);
          test.equal('localhost:32002', server.s.replState.arbiters[0].name);

          test.ok(server.s.replState.primary == null);

          firstSecondaryServer.destroy();
          arbiterServer.destroy();
          server.destroy();
          running = false;
          test.done();
        }
    });

    server.on('connect', function(e) {
      server.__connected = true;
    });

    // Gives proxies a chance to boot up
    setTimeout(function() {
      server.connect();
    }, 100)
  }
}
<commit_msg>fix brittle test<commit_after>"use strict";

// Extend the object
var extend = function(template, fields) {
  var object = {};
  for(var name in template) {
    object[name] = template[name];
  }

  for(var name in fields) {
   object[name] = fields[name];
  }

  return object;
}

exports['Successful connection to replicaset of 1 primary, 1 secondary and 1 arbiter'] = {
  metadata: {
    requires: {
      generators: true,
      topology: "single"
    }
  },

  test: function(configuration, test) {
    var ReplSet = configuration.require.ReplSet,
      ObjectId = configuration.require.BSON.ObjectId,
      ReadPreference = configuration.require.ReadPreference,
      Long = configuration.require.BSON.Long,
      co = require('co'),
      mockupdb = require('../../../mock');

    // Contain mock server
    var primaryServer = null;
    var firstSecondaryServer = null;
    var arbiterServer = null;
    var running = true;
    var electionIds = [new ObjectId(), new ObjectId()];

    // Default message fields
    var defaultFields = {
      "setName": "rs", "setVersion": 1, "electionId": electionIds[0],
      "maxBsonObjectSize" : 16777216, "maxMessageSizeBytes" : 48000000,
      "maxWriteBatchSize" : 1000, "localTime" : new Date(), "maxWireVersion" : 4,
      "minWireVersion" : 0, "ok" : 1, "hosts": ["localhost:32000", "localhost:32001", "localhost:32002"], "arbiters": ["localhost:32002"]
    }

    // Primary server states
    var primary = [extend(defaultFields, {
      "ismaster":true, "secondary":false, "me": "localhost:32000", "primary": "localhost:32000", "tags" : { "loc" : "ny" }
    })];

    // Primary server states
    var firstSecondary = [extend(defaultFields, {
      "ismaster":false, "secondary":true, "me": "localhost:32001", "primary": "localhost:32000", "tags" : { "loc" : "sf" }
    })];

    // Primary server states
    var arbiter = [extend(defaultFields, {
      "ismaster":false, "secondary":false, "arbiterOnly": true, "me": "localhost:32002", "primary": "localhost:32000"
    })];

    // Boot the mock
    co(function*() {
      primaryServer = yield mockupdb.createServer(32000, 'localhost');
      firstSecondaryServer = yield mockupdb.createServer(32001, 'localhost');
      arbiterServer = yield mockupdb.createServer(32002, 'localhost');

      // Primary state machine
      co(function*() {
        while(running) {
          var request = yield primaryServer.receive();
          var doc = request.document;

          if(doc.ismaster) {
            request.reply(primary[0]);
          }
        }
      }).catch(function(err) {
        console.log(err.stack);
      });

      // First secondary state machine
      co(function*() {
        while(running) {
          var request = yield firstSecondaryServer.receive();
          var doc = request.document;

          if(doc.ismaster) {
            request.reply(firstSecondary[0]);
          }
        }
      }).catch(function(err) {
        console.log(err.stack);
      });

      // Second secondary state machine
      co(function*() {
        while(running) {
          var request = yield arbiterServer.receive();
          var doc = request.document;

          if(doc.ismaster) {
            request.reply(arbiter[0]);
          }
        }
      }).catch(function(err) {
        console.log(err.stack);
      });
    });

    // Attempt to connect
    var server = new ReplSet([
      { host: 'localhost', port: 32000 },
      { host: 'localhost', port: 32001 },
      { host: 'localhost', port: 32002 }], {
        setName: 'rs',
        connectionTimeout: 3000,
        socketTimeout: 0,
        haInterval: 2000,
        size: 1
    });

    server.on('joined', function(_type) {
      if(_type == 'arbiter' || _type == 'secondary' || _type == 'primary') {
        if(server.s.replState.secondaries.length == 1
          && server.s.replState.arbiters.length == 1
          && server.s.replState.primary) {
            test.equal(1, server.s.replState.secondaries.length);
            test.equal('localhost:32001', server.s.replState.secondaries[0].name);

            test.equal(1, server.s.replState.arbiters.length);
            test.equal('localhost:32002', server.s.replState.arbiters[0].name);

            test.ok(server.s.replState.primary != null);
            test.equal('localhost:32000', server.s.replState.primary.name);

            primaryServer.destroy();
            firstSecondaryServer.destroy();
            arbiterServer.destroy();
            server.destroy();
            running = false;

            test.done();
          }
      }
    });

    server.on('connect', function(e) {
      server.__connected = true;
    });

    // Add event listeners
    server.on('fullsetup', function(_server) {});
    // Gives proxies a chance to boot up
    setTimeout(function() {
      server.connect();
    }, 100)
  }
}

exports['Successful connection to replicaset of 1 primary, 1 secondary but missing arbiter'] = {
  metadata: {
    requires: {
      generators: true,
      topology: "single"
    }
  },

  test: function(configuration, test) {
    var ReplSet = configuration.require.ReplSet,
      ObjectId = configuration.require.BSON.ObjectId,
      ReadPreference = configuration.require.ReadPreference,
      Long = configuration.require.BSON.Long,
      co = require('co'),
      mockupdb = require('../../../mock');

    // Contain mock server
    var primaryServer = null;
    var firstSecondaryServer = null;
    var secondSecondaryServer = null;
    var running = true;
    var electionIds = [new ObjectId(), new ObjectId()];

    // Default message fields
    var defaultFields = {
      "setName": "rs", "setVersion": 1, "electionId": electionIds[0],
      "maxBsonObjectSize" : 16777216, "maxMessageSizeBytes" : 48000000,
      "maxWriteBatchSize" : 1000, "localTime" : new Date(), "maxWireVersion" : 4,
      "minWireVersion" : 0, "ok" : 1, "hosts": ["localhost:32000", "localhost:32001", "localhost:32002"], "arbiters": ["localhost:32002"]
    }

    // Primary server states
    var primary = [extend(defaultFields, {
      "ismaster":true, "secondary":false, "me": "localhost:32000", "primary": "localhost:32000", "tags" : { "loc" : "ny" }
    })];

    // Primary server states
    var firstSecondary = [extend(defaultFields, {
      "ismaster":false, "secondary":true, "me": "localhost:32001", "primary": "localhost:32000", "tags" : { "loc" : "sf" }
    })];

    // Boot the mock
    co(function*() {
      primaryServer = yield mockupdb.createServer(32000, 'localhost');
      firstSecondaryServer = yield mockupdb.createServer(32001, 'localhost');

      // Primary state machine
      co(function*() {
        while(running) {
          var request = yield primaryServer.receive();
          var doc = request.document;

          if(doc.ismaster) {
            request.reply(primary[0]);
          }
        }
      }).catch(function(err) {
        console.log(err.stack);
      });

      // First secondary state machine
      co(function*() {
        while(running) {
          var request = yield firstSecondaryServer.receive();
          var doc = request.document;

          if(doc.ismaster) {
            request.reply(firstSecondary[0]);
          }
        }
      }).catch(function(err) {
        console.log(err.stack);
      });
    });

    // Attempt to connect
    var server = new ReplSet([
      { host: 'localhost', port: 32000 },
      { host: 'localhost', port: 32001 },
      { host: 'localhost', port: 32002 }], {
        setName: 'rs',
        connectionTimeout: 3000,
        socketTimeout: 0,
        haInterval: 2000,
        size: 1
    });

    // Add event listeners
    server.on('fullsetup', function(_server) {
      test.equal(true, server.__connected);

      test.equal(1, server.s.replState.secondaries.length);
      test.equal('localhost:32001', server.s.replState.secondaries[0].name);

      test.equal(0, server.s.replState.arbiters.length);

      test.ok(server.s.replState.primary != null);
      test.equal('localhost:32000', server.s.replState.primary.name);

      primaryServer.destroy();
      firstSecondaryServer.destroy();
      server.destroy();
      running = false;

      test.done();
    });

    server.on('connect', function(e) {
      server.__connected = true;
    });

    // Gives proxies a chance to boot up
    setTimeout(function() {
      server.connect();
    }, 100)
  }
}

exports['Fail to connect due to missing primary'] = {
  metadata: {
    requires: {
      generators: true,
      topology: "single"
    }
  },

  test: function(configuration, test) {
    var ReplSet = configuration.require.ReplSet,
      ObjectId = configuration.require.BSON.ObjectId,
      ReadPreference = configuration.require.ReadPreference,
      Long = configuration.require.BSON.Long,
      co = require('co'),
      mockupdb = require('../../../mock');

    // Contain mock server
    var firstSecondaryServer = null;
    var running = true;
    var electionIds = [new ObjectId(), new ObjectId()];

    // Default message fields
    var defaultFields = {
      "setName": "rs", "setVersion": 1, "electionId": electionIds[0],
      "maxBsonObjectSize" : 16777216, "maxMessageSizeBytes" : 48000000,
      "maxWriteBatchSize" : 1000, "localTime" : new Date(), "maxWireVersion" : 4,
      "minWireVersion" : 0, "ok" : 1, "hosts": ["localhost:32000", "localhost:32001", "localhost:32002"], "arbiters": ["localhost:32002"]
    }

    // Primary server states
    var firstSecondary = [extend(defaultFields, {
      "ismaster":false, "secondary":true, "me": "localhost:32001", "primary": "localhost:32000", "tags" : { "loc" : "sf" }
    })];

    // Boot the mock
    co(function*() {
      firstSecondaryServer = yield mockupdb.createServer(32001, 'localhost');

      // First secondary state machine
      co(function*() {
        while(running) {
          var request = yield firstSecondaryServer.receive();
          var doc = request.document;

          if(doc.ismaster) {
            request.reply(firstSecondary[0]);
          }
        }
      }).catch(function(err) {
        console.log(err.stack);
      });
    });

    // Attempt to connect
    var server = new ReplSet([
      { host: 'localhost', port: 32000 },
      { host: 'localhost', port: 32001 },
      { host: 'localhost', port: 32002 }], {
        setName: 'rs',
        connectionTimeout: 3000,
        socketTimeout: 0,
        haInterval: 2000,
        size: 1
    });

    server.on('error', function(error) {
      server.destroy();
      firstSecondaryServer.destroy();
      running = false;
      test.done();
    });

    // Gives proxies a chance to boot up
    setTimeout(function() {
      server.connect();
    }, 100)
  }
}

exports['Successful connection to replicaset of 0 primary, 1 secondary and 1 arbiter with secondaryOnlyConnectionAllowed'] = {
  metadata: {
    requires: {
      generators: true,
      topology: "single"
    }
  },

  test: function(configuration, test) {
    var ReplSet = configuration.require.ReplSet,
      ObjectId = configuration.require.BSON.ObjectId,
      ReadPreference = configuration.require.ReadPreference,
      Long = configuration.require.BSON.Long,
      co = require('co'),
      mockupdb = require('../../../mock');

    // Contain mock server
    var firstSecondaryServer = null;
    var arbiterServer = null;
    var running = true;
    var electionIds = [new ObjectId(), new ObjectId()];

    // Default message fields
    var defaultFields = {
      "setName": "rs", "setVersion": 1, "electionId": electionIds[0],
      "maxBsonObjectSize" : 16777216, "maxMessageSizeBytes" : 48000000,
      "maxWriteBatchSize" : 1000, "localTime" : new Date(), "maxWireVersion" : 4,
      "minWireVersion" : 0, "ok" : 1, "hosts": ["localhost:32000", "localhost:32001", "localhost:32002"], "arbiters": ["localhost:32002"]
    }

    // Primary server states
    var firstSecondary = [extend(defaultFields, {
      "ismaster":false, "secondary":true, "me": "localhost:32001", "primary": "localhost:32000", "tags" : { "loc" : "sf" }
    })];

    // Primary server states
    var arbiter = [extend(defaultFields, {
      "ismaster":false, "secondary":false, "arbiterOnly": true, "me": "localhost:32002", "primary": "localhost:32000"
    })];

    // Boot the mock
    co(function*() {
      firstSecondaryServer = yield mockupdb.createServer(32001, 'localhost');
      arbiterServer = yield mockupdb.createServer(32002, 'localhost');

      // First secondary state machine
      co(function*() {
        while(running) {
          var request = yield firstSecondaryServer.receive();
          var doc = request.document;

          if(doc.ismaster) {
            request.reply(firstSecondary[0]);
          }
        }
      }).catch(function(err) {
        console.log(err.stack);
      });

      // Second secondary state machine
      co(function*() {
        while(running) {
          var request = yield arbiterServer.receive();
          var doc = request.document;

          if(doc.ismaster) {
            request.reply(arbiter[0]);
          }
        }
      }).catch(function(err) {
        console.log(err.stack);
      });
    });

    // Attempt to connect
    var server = new ReplSet([
      { host: 'localhost', port: 32000 },
      { host: 'localhost', port: 32001 },
      { host: 'localhost', port: 32002 }], {
        setName: 'rs',
        connectionTimeout: 3000,
        socketTimeout: 0,
        haInterval: 2000,
        size: 1,
        secondaryOnlyConnectionAllowed: true
    });

    server.on('joined', function(_type) {
      if(server.s.replState.secondaries.length == 1
        && server.s.replState.arbiters.length == 1) {
          test.equal(1, server.s.replState.secondaries.length);
          test.equal('localhost:32001', server.s.replState.secondaries[0].name);

          test.equal(1, server.s.replState.arbiters.length);
          test.equal('localhost:32002', server.s.replState.arbiters[0].name);

          test.ok(server.s.replState.primary == null);

          firstSecondaryServer.destroy();
          arbiterServer.destroy();
          server.destroy();
          running = false;
          test.done();
        }
    });

    server.on('connect', function(e) {
      server.__connected = true;
    });

    // Gives proxies a chance to boot up
    setTimeout(function() {
      server.connect();
    }, 100)
  }
}
<|endoftext|>


<commit_before><commit_msg>rm term.js<commit_after><|endoftext|>


<commit_before>function w(name) {
  document.write(name + ': ' + (
    isEventSupported(name)
      ? 'true'
      : 'false'
    ) + '
');
}

document.write('
' + isEventSupported + '

');

document.write('
Mouse events:
');

w('click');
w('dblclick');
w('mousedown');
w('mouseup');
w('mouseover');
w('mousemove');
w('mouseout');

document.write('
Key events:
');

w('keypress');
w('keydown');
w('keyup');

document.write('
HTML events
');

w('load');
w('unload');
w('abort');
w('error');

document.write('
View events
');

w('resize');
w('scroll');

document.write('
Form events:
');

w('submit');
w('reset');

document.write('
Form controls\' events:
');

w('select');
w('change');

document.write('
Activation events:
');

w('focus');
w('blur');

document.write('
MSHTML DOM events:
');

w('cut');
w('copy');
w('paste');
w('beforecut');
w('beforecopy');
w('beforepaste');
w('afterupdate');
w('beforeupdate');
w('cellchange');
w('dataavailable');
w('datasetchanged');
w('datasetcomplete');
w('errorupdate');
w('rowenter');
w('rowexit');
w('rowsdelete');
w('drag');
w('dragstart');
w('dragenter');
w('dragover');
w('dragleave');
w('dragend');
w('drop');
w('selectstart');
w('mouseenter');
w('mouseleave');
w('activate');
w('beforeactivate');
w('deactivate');
w('beforedeactivate');
w('focusin');
w('focusout');
w('stop');
w('readystatechange');

document.write('
Unexistent (most likely) events:
');

w('click2');
w('foobarbaz');

document.write('
Unexistent in Opera <=10a
');

w('contextmenu');<commit_msg>Add iPhone touch events<commit_after>function w(name) {
  document.write(name + ': ' + (
    isEventSupported(name)
      ? 'true'
      : 'false'
    ) + '
');
}

document.write('
' + isEventSupported + '

');

document.write('
Mouse events:
');

w('click');
w('dblclick');
w('mousedown');
w('mouseup');
w('mouseover');
w('mousemove');
w('mouseout');

document.write('
Key events:
');

w('keypress');
w('keydown');
w('keyup');

document.write('
HTML events
');

w('load');
w('unload');
w('abort');
w('error');

document.write('
View events
');

w('resize');
w('scroll');

document.write('
Form events:
');

w('submit');
w('reset');

document.write('
Form controls\' events:
');

w('select');
w('change');

document.write('
Activation events:
');

w('focus');
w('blur');

document.write('
MSHTML DOM events:
');

w('cut');
w('copy');
w('paste');
w('beforecut');
w('beforecopy');
w('beforepaste');
w('afterupdate');
w('beforeupdate');
w('cellchange');
w('dataavailable');
w('datasetchanged');
w('datasetcomplete');
w('errorupdate');
w('rowenter');
w('rowexit');
w('rowsdelete');
w('drag');
w('dragstart');
w('dragenter');
w('dragover');
w('dragleave');
w('dragend');
w('drop');
w('selectstart');
w('mouseenter');
w('mouseleave');
w('activate');
w('beforeactivate');
w('deactivate');
w('beforedeactivate');
w('focusin');
w('focusout');
w('stop');
w('readystatechange');

document.write('
Unexistent (most likely) events:
');

w('click2');
w('foobarbaz');

document.write('
Unexistent in Opera <=10a
');

w('contextmenu');

document.write('
iPhone touch events
');

w('touchstart');
w('touchend');
w('touchmove');
w('touchcancel');<|endoftext|>


<commit_before>var dgram = require('dgram')
var tape = require('tape')
var discovery = require('./')

freePort(function (port) {
  tape('discovery using remote server', function (t) {
    var ns = Math.random().toString(16) + '-' + process.pid
    var appName = 'dns-discovery-' + ns
    var disc1 = discovery({
      multicast: false,
      servers: ['discovery1.publicbits.org', 'discovery2.publicbits.org']
    })
    var disc2 = discovery({
      multicast: false,
      servers: ['discovery1.publicbits.org', 'discovery2.publicbits.org']
    })

    disc2.once('peer', function (id, peer) {
      disc2.destroy()
      disc1.destroy()
      t.same(peer.port, 9090)
      t.end()
    })

    disc1.announce(appName, 9090, function () {
      disc2.lookup(appName)
    })
  })

  tape('discovers', function (t) {
    var disc1 = discovery()
    var disc2 = discovery()
    var ns = Math.random().toString(16) + '-' + process.pid
    var appName = 'dns-discovery-' + ns

    disc2.on('peer', function (name, peer) {
      disc1.destroy()
      disc2.destroy()
      t.same(name, appName)
      t.same(peer.port, 8080)
      t.same(typeof peer.host, 'string')
      t.end()
    })

    disc1.announce(appName, 8080)
  })

  tape('discovers only using server', function (t) {
    t.plan(4)

    var server = discovery({multicast: false})
    var client2 = discovery({multicast: false, server: 'localhost:' + port})
    var client1 = discovery({multicast: false, server: 'localhost:' + port})

    server.on('peer', function (name, peer) {
      t.same(name, 'hello-world')
      t.same(peer.port, 8080)
    })

    client2.on('peer', function (name, peer) {
      t.same(name, 'hello-world')
      t.same(peer.port, 8080)
      server.destroy()
      client1.destroy()
      client2.destroy()
    })

    server.listen(port, function () {
      client1.announce('hello-world', 8080, function () {
        client2.lookup('hello-world')
      })
    })
  })

  tape('discovers only using server with secondary port', function (t) {
    t.plan(4)

    var server = discovery({multicast: false})
    var client2 = discovery({multicast: false, server: 'localhost:9999,' + port})
    var client1 = discovery({multicast: false, server: 'localhost:9998,' + port})

    server.on('peer', function (name, peer) {
      t.same(name, 'hello-world')
      t.same(peer.port, 8080)
    })

    client2.on('peer', function (name, peer) {
      t.same(name, 'hello-world')
      t.same(peer.port, 8080)
      server.destroy()
      client1.destroy()
      client2.destroy()
    })

    server.listen(port, function () {
      client1.announce('hello-world', 8080, function () {
        client2.lookup('hello-world')
      })
    })
  })

  tape('discovers only using multiple servers', function (t) {
    t.plan(6)

    var server = discovery({multicast: false})
    var client1 = discovery({multicast: false, server: ['localhost:' + port, 'localhost:' + port]})
    var client2 = discovery({multicast: false, server: ['localhost:' + port, 'localhost:' + port]})

    server.on('peer', function (name, peer) {
      t.same(name, 'hello-world')
      t.same(peer.port, 8080)
    })

    client2.on('peer', function (name, peer) {
      t.same(name, 'hello-world')
      t.same(peer.port, 8080)
      server.destroy()
      client1.destroy()
      client2.destroy()
    })

    server.listen(port, function () {
      client1.announce('hello-world', 8080, function () {
        client2.lookup('hello-world')
      })
    })
  })

  tape('limit', function (t) {
    var server = discovery({multicast: false, limit: 1})
    var ns = Math.random().toString(16) + '-' + process.pid

    server.announce(ns + 'hello-world', 8080)
    server.announce(ns + 'hello-world-2', 8081)

    var domains = server.toJSON()
    t.same(domains.length, 1)
    t.same(domains[0].records.length, 1)
    t.end()
  })

  tape('push', function (t) {
    var server = discovery({multicast: false})
    var client1 = discovery({multicast: false, server: 'localhost:' + port})
    var client2 = discovery({multicast: false, server: 'localhost:' + port})

    server.listen(port, function () {
      server.once('peer', function () {
        client2.announce('hello-world', 8081)
      })
      client1.lookup('hello-world')
      client1.announce('hello-world', 8080)
      client1.on('peer', function (id, peer) {
        if (peer.port === 8081) {
          client1.destroy()
          client2.destroy()
          server.destroy()
          t.pass('got peer')
          t.end()
        }
      })
    })
  })

  tape('unannounce', function (t) {
    var server = discovery({multicast: false})
    var client1 = discovery({multicast: false, server: 'localhost:' + port})
    var client2 = discovery({multicast: false, server: 'localhost:' + port})

    client2.on('peer', function () {
      t.fail('no peers should be discovered')
    })

    server.listen(port, function () {
      client1.announce('test', 8080, function () {
        client1.unannounce('test', 8080, function () {
          client2.lookup('test', function () {
            setTimeout(function () {
              client2.destroy()
              client1.destroy()
              server.destroy()
              t.end()
            }, 100)
          })
        })
      })
    })
  })

  tape('custom socket + server', function (t) {
    t.plan(5)

    var socket = dgram.createSocket('udp4')

    socket.once('message', function () {
      t.pass('used custom socket')
    })

    var server = discovery({multicast: false})
    var client2 = discovery({multicast: false, server: 'localhost:' + port, socket: socket})
    var client1 = discovery({multicast: false, server: 'localhost:' + port})

    server.on('peer', function (name, peer) {
      t.same(name, 'hello-world')
      t.same(peer.port, 8080)
    })

    client2.on('peer', function (name, peer) {
      t.same(name, 'hello-world')
      t.same(peer.port, 8080)
      server.destroy()
      client1.destroy()
      client2.destroy()
    })

    server.listen(port, function () {
      client1.announce('hello-world', 8080, function () {
        client2.lookup('hello-world')
      })
    })
  })

  tape('implied port', function (t) {
    t.plan(4)

    var socket = dgram.createSocket('udp4')

    var server = discovery({multicast: false})
    var client2 = discovery({multicast: false, server: 'localhost:' + port})
    var client1 = discovery({multicast: false, server: 'localhost:' + port, socket: socket})

    server.on('peer', function (name, peer) {
      t.same(name, 'hello-world')
      t.same(peer.port, socket.address().port)
    })

    client2.on('peer', function (name, peer) {
      t.same(name, 'hello-world')
      t.same(peer.port, socket.address().port)
      server.destroy()
      client1.destroy()
      client2.destroy()
    })

    server.listen(port, function () {
      client1.announce('hello-world', 8080, {impliedPort: true}, function () {
        client2.lookup('hello-world')
      })
    })
  })

  tape('loopback', function (t) {
    var client = discovery({loopback: true})

    client.on('peer', function () {
      client.destroy()
      t.end()
    })

    client.announce('test', 8080)
  })

  tape('public port', function (t) {
    var server = discovery({multicast: false})
    var client2 = discovery({server: 'localhost:' + port})
    var client1 = discovery({server: 'localhost:' + port})
    var ns = Math.random().toString(16) + '-' + process.pid
    var appName = 'dns-discovery-' + ns
    var missing = 2

    server.on('peer', function (name, peer) {
      t.same(name, appName)
      t.same(peer.port, 9090, 'server port')
    })

    client2.on('peer', function (name, peer) {
      t.same(name, appName)
      t.same(peer.port, peer.host === '127.0.0.1' ? 9090 : 8080)
      if (--missing) return
      server.destroy()
      client1.destroy()
      client2.destroy()
      t.end()
    })

    server.listen(port, function () {
      client1.announce(appName, 8080, {publicPort: 9090}, function () {
        client2.lookup(appName)
      })
    })
  })
})

function freePort (cb) {
  var socket = dgram.createSocket('udp4')
  socket.bind(0, function () {
    socket.on('close', cb.bind(null, socket.address().port))
    socket.close()
  })
}
<commit_msg>remove travis specific test<commit_after>var dgram = require('dgram')
var tape = require('tape')
var discovery = require('./')

freePort(function (port) {
  tape('discovers', function (t) {
    var disc1 = discovery()
    var disc2 = discovery()
    var ns = Math.random().toString(16) + '-' + process.pid
    var appName = 'dns-discovery-' + ns

    disc2.on('peer', function (name, peer) {
      disc1.destroy()
      disc2.destroy()
      t.same(name, appName)
      t.same(peer.port, 8080)
      t.same(typeof peer.host, 'string')
      t.end()
    })

    disc1.announce(appName, 8080)
  })

  tape('discovers only using server', function (t) {
    t.plan(4)

    var server = discovery({multicast: false})
    var client2 = discovery({multicast: false, server: 'localhost:' + port})
    var client1 = discovery({multicast: false, server: 'localhost:' + port})

    server.on('peer', function (name, peer) {
      t.same(name, 'hello-world')
      t.same(peer.port, 8080)
    })

    client2.on('peer', function (name, peer) {
      t.same(name, 'hello-world')
      t.same(peer.port, 8080)
      server.destroy()
      client1.destroy()
      client2.destroy()
    })

    server.listen(port, function () {
      client1.announce('hello-world', 8080, function () {
        client2.lookup('hello-world')
      })
    })
  })

  tape('discovers only using server with secondary port', function (t) {
    t.plan(4)

    var server = discovery({multicast: false})
    var client2 = discovery({multicast: false, server: 'localhost:9999,' + port})
    var client1 = discovery({multicast: false, server: 'localhost:9998,' + port})

    server.on('peer', function (name, peer) {
      t.same(name, 'hello-world')
      t.same(peer.port, 8080)
    })

    client2.on('peer', function (name, peer) {
      t.same(name, 'hello-world')
      t.same(peer.port, 8080)
      server.destroy()
      client1.destroy()
      client2.destroy()
    })

    server.listen(port, function () {
      client1.announce('hello-world', 8080, function () {
        client2.lookup('hello-world')
      })
    })
  })

  tape('discovers only using multiple servers', function (t) {
    t.plan(6)

    var server = discovery({multicast: false})
    var client1 = discovery({multicast: false, server: ['localhost:' + port, 'localhost:' + port]})
    var client2 = discovery({multicast: false, server: ['localhost:' + port, 'localhost:' + port]})

    server.on('peer', function (name, peer) {
      t.same(name, 'hello-world')
      t.same(peer.port, 8080)
    })

    client2.on('peer', function (name, peer) {
      t.same(name, 'hello-world')
      t.same(peer.port, 8080)
      server.destroy()
      client1.destroy()
      client2.destroy()
    })

    server.listen(port, function () {
      client1.announce('hello-world', 8080, function () {
        client2.lookup('hello-world')
      })
    })
  })

  tape('limit', function (t) {
    var server = discovery({multicast: false, limit: 1})
    var ns = Math.random().toString(16) + '-' + process.pid

    server.announce(ns + 'hello-world', 8080)
    server.announce(ns + 'hello-world-2', 8081)

    var domains = server.toJSON()
    t.same(domains.length, 1)
    t.same(domains[0].records.length, 1)
    t.end()
  })

  tape('push', function (t) {
    var server = discovery({multicast: false})
    var client1 = discovery({multicast: false, server: 'localhost:' + port})
    var client2 = discovery({multicast: false, server: 'localhost:' + port})

    server.listen(port, function () {
      server.once('peer', function () {
        client2.announce('hello-world', 8081)
      })
      client1.lookup('hello-world')
      client1.announce('hello-world', 8080)
      client1.on('peer', function (id, peer) {
        if (peer.port === 8081) {
          client1.destroy()
          client2.destroy()
          server.destroy()
          t.pass('got peer')
          t.end()
        }
      })
    })
  })

  tape('unannounce', function (t) {
    var server = discovery({multicast: false})
    var client1 = discovery({multicast: false, server: 'localhost:' + port})
    var client2 = discovery({multicast: false, server: 'localhost:' + port})

    client2.on('peer', function () {
      t.fail('no peers should be discovered')
    })

    server.listen(port, function () {
      client1.announce('test', 8080, function () {
        client1.unannounce('test', 8080, function () {
          client2.lookup('test', function () {
            setTimeout(function () {
              client2.destroy()
              client1.destroy()
              server.destroy()
              t.end()
            }, 100)
          })
        })
      })
    })
  })

  tape('custom socket + server', function (t) {
    t.plan(5)

    var socket = dgram.createSocket('udp4')

    socket.once('message', function () {
      t.pass('used custom socket')
    })

    var server = discovery({multicast: false})
    var client2 = discovery({multicast: false, server: 'localhost:' + port, socket: socket})
    var client1 = discovery({multicast: false, server: 'localhost:' + port})

    server.on('peer', function (name, peer) {
      t.same(name, 'hello-world')
      t.same(peer.port, 8080)
    })

    client2.on('peer', function (name, peer) {
      t.same(name, 'hello-world')
      t.same(peer.port, 8080)
      server.destroy()
      client1.destroy()
      client2.destroy()
    })

    server.listen(port, function () {
      client1.announce('hello-world', 8080, function () {
        client2.lookup('hello-world')
      })
    })
  })

  tape('implied port', function (t) {
    t.plan(4)

    var socket = dgram.createSocket('udp4')

    var server = discovery({multicast: false})
    var client2 = discovery({multicast: false, server: 'localhost:' + port})
    var client1 = discovery({multicast: false, server: 'localhost:' + port, socket: socket})

    server.on('peer', function (name, peer) {
      t.same(name, 'hello-world')
      t.same(peer.port, socket.address().port)
    })

    client2.on('peer', function (name, peer) {
      t.same(name, 'hello-world')
      t.same(peer.port, socket.address().port)
      server.destroy()
      client1.destroy()
      client2.destroy()
    })

    server.listen(port, function () {
      client1.announce('hello-world', 8080, {impliedPort: true}, function () {
        client2.lookup('hello-world')
      })
    })
  })

  tape('loopback', function (t) {
    var client = discovery({loopback: true})

    client.on('peer', function () {
      client.destroy()
      t.end()
    })

    client.announce('test', 8080)
  })

  tape('public port', function (t) {
    var server = discovery({multicast: false})
    var client2 = discovery({server: 'localhost:' + port})
    var client1 = discovery({server: 'localhost:' + port})
    var ns = Math.random().toString(16) + '-' + process.pid
    var appName = 'dns-discovery-' + ns
    var missing = 2

    server.on('peer', function (name, peer) {
      t.same(name, appName)
      t.same(peer.port, 9090, 'server port')
    })

    client2.on('peer', function (name, peer) {
      t.same(name, appName)
      t.same(peer.port, peer.host === '127.0.0.1' ? 9090 : 8080)
      if (--missing) return
      server.destroy()
      client1.destroy()
      client2.destroy()
      t.end()
    })

    server.listen(port, function () {
      client1.announce(appName, 8080, {publicPort: 9090}, function () {
        client2.lookup(appName)
      })
    })
  })
})

function freePort (cb) {
  var socket = dgram.createSocket('udp4')
  socket.bind(0, function () {
    socket.on('close', cb.bind(null, socket.address().port))
    socket.close()
  })
}
<|endoftext|>