apex-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From david...@apache.org
Subject [14/98] [abbrv] [partial] incubator-apex-malhar git commit: Removing all web demos
Date Mon, 30 Nov 2015 21:06:20 GMT
http://git-wip-us.apache.org/repos/asf/incubator-apex-malhar/blob/e1a45507/web/demos/package/node_modules/mongodb/lib/mongodb/connection/repl_set/repl_set.js
----------------------------------------------------------------------
diff --git a/web/demos/package/node_modules/mongodb/lib/mongodb/connection/repl_set/repl_set.js b/web/demos/package/node_modules/mongodb/lib/mongodb/connection/repl_set/repl_set.js
deleted file mode 100644
index c2d1df4..0000000
--- a/web/demos/package/node_modules/mongodb/lib/mongodb/connection/repl_set/repl_set.js
+++ /dev/null
@@ -1,811 +0,0 @@
-var ReadPreference = require('../read_preference').ReadPreference
-  , DbCommand = require('../../commands/db_command').DbCommand
-  , inherits = require('util').inherits
-  , format = require('util').format
-  , timers = require('timers')
-  , Server = require('../server').Server
-  , utils = require('../../utils')
-  , PingStrategy = require('./strategies/ping_strategy').PingStrategy
-  , StatisticsStrategy = require('./strategies/statistics_strategy').StatisticsStrategy
-  , Options = require('./options').Options
-  , ReplSetState = require('./repl_set_state').ReplSetState
-  , HighAvailabilityProcess = require('./ha').HighAvailabilityProcess
-  , Base = require('../base').Base;
-
-var STATE_STARTING_PHASE_1 = 0;
-var STATE_PRIMARY = 1;
-var STATE_SECONDARY = 2;
-var STATE_RECOVERING = 3;
-var STATE_FATAL_ERROR = 4;
-var STATE_STARTING_PHASE_2 = 5;
-var STATE_UNKNOWN = 6;
-var STATE_ARBITER = 7;
-var STATE_DOWN = 8;
-var STATE_ROLLBACK = 9;
-
-// Set processor, setImmediate if 0.10 otherwise nextTick
-var processor = require('../../utils').processor();
-
-/**
- * ReplSet constructor provides replicaset functionality
- *
- * Options
- *  - **ha** {Boolean, default:true}, turn on high availability.
- *  - **haInterval** {Number, default:2000}, time between each replicaset status check.
- *  - **reconnectWait** {Number, default:1000}, time to wait in miliseconds before attempting reconnect.
- *  - **retries** {Number, default:30}, number of times to attempt a replicaset reconnect.
- *  - **rs_name** {String}, the name of the replicaset to connect to.
- *  - **socketOptions** {Object, default:null}, an object containing socket options to use (noDelay:(boolean), keepAlive:(number), connectTimeoutMS:(number), socketTimeoutMS:(number))
- *  - **readPreference** {String}, the prefered read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).
- *  - **strategy** {String, default:'ping'}, selection strategy for reads choose between (ping, statistical and none, default is ping)
- *  - **secondaryAcceptableLatencyMS** {Number, default:15}, sets the range of servers to pick when using NEAREST (lowest ping ms + the latency fence, ex: range of 1 to (1 + 15) ms)
- *  - **connectWithNoPrimary** {Boolean, default:false}, sets if the driver should connect even if no primary is available
- *  - **connectArbiter** {Boolean, default:false}, sets if the driver should connect to arbiters or not.
- *  - **logger** {Object, default:null}, an object representing a logger that you want to use, needs to support functions debug, log, error **({error:function(message, object) {}, log:function(message, object) {}, debug:function(message, object) {}})**.
- *  - **poolSize** {Number, default:5}, number of connections in the connection pool for each server instance, set to 5 as default for legacy reasons.
- *  - **ssl** {Boolean, default:false}, use ssl connection (needs to have a mongod server with ssl support)
- *  - **sslValidate** {Boolean, default:false}, validate mongod server certificate against ca (needs to have a mongod server with ssl support, 2.4 or higher)
- *  - **sslCA** {Array, default:null}, Array of valid certificates either as Buffers or Strings (needs to have a mongod server with ssl support, 2.4 or higher)
- *  - **sslCert** {Buffer/String, default:null}, String or buffer containing the certificate we wish to present (needs to have a mongod server with ssl support, 2.4 or higher)
- *  - **sslKey** {Buffer/String, default:null}, String or buffer containing the certificate private key we wish to present (needs to have a mongod server with ssl support, 2.4 or higher)
- *  - **sslPass** {Buffer/String, default:null}, String or buffer containing the certificate password (needs to have a mongod server with ssl support, 2.4 or higher)
- *
- * @class Represents a 
- Replicaset Configuration
- * @param {Array} list of server objects participating in the replicaset.
- * @param {Object} [options] additional options for the replicaset connection.
- */
-var ReplSet = exports.ReplSet = function(servers, options) {
-  // Set up basic
-  if(!(this instanceof ReplSet))
-    return new ReplSet(servers, options);
-
-  // Set up event emitter
-  Base.call(this);
-
-  // Ensure we have a list of servers
-  if(!Array.isArray(servers)) throw Error("The parameter must be an array of servers and contain at least one server");
-  // Ensure no Mongos's
-  for(var i = 0; i < servers.length; i++) {
-    if(!(servers[i] instanceof Server)) throw new Error("list of servers must be of type Server");
-  }
-
-  // Save the options
-  this.options = new Options(options);
-  // Ensure basic validation of options
-  this.options.init();
-
-  // Server state
-  this._serverState = ReplSet.REPLSET_DISCONNECTED;
-  // Add high availability process
-  this._haProcess = new HighAvailabilityProcess(this, this.options);
-
-  // Let's iterate over all the provided server objects and decorate them
-  this.servers = this.options.decorateAndClean(servers, this._callBackStore);
-  // Throw error if no seed servers
-  if(this.servers.length == 0) throw new Error("No valid seed servers in the array");
-
-  // Let's set up our strategy object for picking secondaries
-  if(this.options.strategy == 'ping') {
-    // Create a new instance
-    this.strategyInstance = new PingStrategy(this, this.options.secondaryAcceptableLatencyMS);
-  } else if(this.options.strategy == 'statistical') {
-    // Set strategy as statistical
-    this.strategyInstance = new StatisticsStrategy(this);
-    // Add enable query information
-    this.enableRecordQueryStats(true);
-  }
-
-  this.emitOpen = this.options.emitOpen || true;
-  // Set up a clean state
-  this._state = new ReplSetState(this);
-  // Current round robin selected server
-  this._currentServerChoice = 0;
-  // Ensure up the server callbacks
-  for(var i = 0; i < this.servers.length; i++) {
-    this.servers[i]._callBackStore = this._callBackStore;
-    this.servers[i].name = format("%s:%s", this.servers[i].host, this.servers[i].port)
-    this.servers[i].replicasetInstance = this;
-    this.servers[i].options.auto_reconnect = false;
-    this.servers[i].inheritReplSetOptionsFrom(this);
-  }
-
-  // Allow setting the socketTimeoutMS on all connections
-  // to work around issues such as secondaries blocking due to compaction
-  utils.setSocketTimeoutProperty(this, this.options.socketOptions);
-}
-
-/**
- * @ignore
- */
-inherits(ReplSet, Base);
-
-// Replicaset states
-ReplSet.REPLSET_CONNECTING = 'connecting';
-ReplSet.REPLSET_DISCONNECTED = 'disconnected';
-ReplSet.REPLSET_CONNECTED = 'connected';
-ReplSet.REPLSET_RECONNECTING = 'reconnecting';
-ReplSet.REPLSET_DESTROYED = 'destroyed';
-ReplSet.REPLSET_READ_ONLY = 'readonly';
-
-ReplSet.prototype.isAutoReconnect = function() {
-  return true;
-}
-
-ReplSet.prototype.canWrite = function() {
-  return this._state.master && this._state.master.isConnected();
-}
-
-ReplSet.prototype.canRead = function(read) {
-  if((read == ReadPreference.PRIMARY 
-      || read == null || read == false) && (this._state.master == null || !this._state.master.isConnected())) return false;
-  return Object.keys(this._state.secondaries).length > 0;
-}
-
-/**
- * @ignore
- */
-ReplSet.prototype.enableRecordQueryStats = function(enable) {
-  // Set the global enable record query stats
-  this.recordQueryStats = enable;
-
-  // Enable all the servers
-  for(var i = 0; i < this.servers.length; i++) {
-    this.servers[i].enableRecordQueryStats(enable);
-  }
-}
-
-/**
- * @ignore
- */
-ReplSet.prototype.setReadPreference = function(preference) {
-  this.options.readPreference = preference;
-}
-
-ReplSet.prototype.connect = function(parent, options, callback) {
-  if(this._serverState != ReplSet.REPLSET_DISCONNECTED) 
-    return callback(new Error("in process of connection"));
-
-  // If no callback throw
-  if(!(typeof callback == 'function')) 
-    throw new Error("cannot call ReplSet.prototype.connect with no callback function");
-
-  var self = this;
-  // Save db reference
-  this.options.db = parent;
-  // Set replicaset as connecting
-  this._serverState = ReplSet.REPLSET_CONNECTING
-  // Copy all the servers to our list of seeds
-  var candidateServers = this.servers.slice(0);
-  // Pop the first server
-  var server = candidateServers.pop();
-  server.name = format("%s:%s", server.host, server.port);
-  // Set up the options
-  var opts = {
-    returnIsMasterResults: true,
-    eventReceiver: server
-  }
-
-  // Register some event listeners
-  this.once("fullsetup", function(err, db, replset) {
-    // Set state to connected
-    self._serverState = ReplSet.REPLSET_CONNECTED;
-    // Stop any process running
-    if(self._haProcess) self._haProcess.stop();
-    // Start the HA process
-    self._haProcess.start();
-
-    // Emit fullsetup
-    processor(function() {
-      if(self.emitOpen)
-        self._emitAcrossAllDbInstances(self, null, "open", null, null, null);        
-
-      self._emitAcrossAllDbInstances(self, null, "fullsetup", null, null, null);        
-    });
-
-    // If we have a strategy defined start it
-    if(self.strategyInstance) {
-      self.strategyInstance.start();
-    }
-
-    // Finishing up the call
-    callback(err, db, replset);
-  });
-
-  // Errors
-  this.once("connectionError", function(err, result) {
-    callback(err, result);
-  });
-
-  // Attempt to connect to the server
-  server.connect(this.options.db, opts, _connectHandler(this, candidateServers, server));
-}
-
-ReplSet.prototype.close = function(callback) {  
-  var self = this;
-  // Set as destroyed
-  this._serverState = ReplSet.REPLSET_DESTROYED;
-  // Stop the ha
-  this._haProcess.stop();
-  
-  // If we have a strategy stop it
-  if(this.strategyInstance) {
-    this.strategyInstance.stop();
-  }
-
-  // Kill all servers available
-  for(var name in this._state.addresses) {
-    this._state.addresses[name].close();
-  }
-
-  // Clean out the state
-  this._state = new ReplSetState(this); 
-  
-  // Emit close event
-  processor(function() {
-    self._emitAcrossAllDbInstances(self, null, "close", null, null, true)    
-  });
-
-  // Flush out any remaining call handlers
-  self._flushAllCallHandlers(utils.toError("Connection Closed By Application"));
-
-  // Callback
-  if(typeof callback == 'function') 
-    return callback(null, null);
-}
-
-/**
- * Creates a new server for the `replset` based on `host`.
- *
- * @param {String} host - host:port pair (localhost:27017)
- * @param {ReplSet} replset - the ReplSet instance
- * @return {Server}
- * @ignore
- */
-var createServer = function(self, host, options) {
-  // copy existing socket options to new server
-  var socketOptions = {}
-  if(options.socketOptions) {
-    var keys = Object.keys(options.socketOptions);
-    for(var k = 0; k < keys.length; k++) {
-      socketOptions[keys[k]] = options.socketOptions[keys[k]];
-    }
-  }
-
-  var parts = host.split(/:/);
-  if(1 === parts.length) {
-    parts[1] = Connection.DEFAULT_PORT;
-  }
-
-  socketOptions.host = parts[0];
-  socketOptions.port = parseInt(parts[1], 10);
-
-  var serverOptions = {
-    readPreference: options.readPreference,
-    socketOptions: socketOptions,
-    poolSize: options.poolSize,
-    logger: options.logger,
-    auto_reconnect: false,
-    ssl: options.ssl,
-    sslValidate: options.sslValidate,
-    sslCA: options.sslCA,
-    sslCert: options.sslCert,
-    sslKey: options.sslKey,
-    sslPass: options.sslPass
-  }
-
-  var server = new Server(socketOptions.host, socketOptions.port, serverOptions);
-  // Set up shared state
-  server._callBackStore = self._callBackStore;
-  server.replicasetInstance = self;
-  server.enableRecordQueryStats(self.recordQueryStats);
-  // Set up event handlers
-  server.on("close", _handler("close", self, server));
-  server.on("error", _handler("error", self, server));
-  server.on("timeout", _handler("timeout", self, server));
-  return server;
-}
-
-var _handler = function(event, self, server) {
-  return function(err, doc) {
-    // The event happened to a primary
-    // Remove it from play
-    if(self._state.isPrimary(server)) {    
-      // Emit that the primary left the replicaset
-      self.emit('left', 'primary', server);
-      // Get the current master
-      var current_master = self._state.master;
-      self._state.master = null;
-      self._serverState = ReplSet.REPLSET_READ_ONLY;
-    
-      if(current_master != null) {
-        // Unpack variables
-        var host = current_master.socketOptions.host;
-        var port = current_master.socketOptions.port;
-
-        // Fire error on any unknown callbacks
-        self.__executeAllServerSpecificErrorCallbacks(host, port, err);        
-      }
-    } else if(self._state.isSecondary(server)) {
-      // Emit that a secondary left the replicaset
-      self.emit('left', 'secondary', server);
-      // Delete from the list
-      delete self._state.secondaries[server.name];
-    }
-
-    // If there is no more connections left and the setting is not destroyed
-    // set to disconnected
-    if(Object.keys(self._state.addresses).length == 0 
-      && self._serverState != ReplSet.REPLSET_DESTROYED) {
-        self._serverState = ReplSet.REPLSET_DISCONNECTED;
-
-        // Emit close across all the attached db instances
-        self._dbStore.emit("close", new Error("replicaset disconnected, no valid servers contactable over tcp"), null, true);
-    }
-
-    // Unpack variables
-    var host = server.socketOptions.host;
-    var port = server.socketOptions.port;
-
-    // Fire error on any unknown callbacks
-    self.__executeAllServerSpecificErrorCallbacks(host, port, err);
-  }
-}
-
-var locateNewServers = function(self, state, candidateServers, ismaster) {
-  // Retrieve the host
-  var hosts = ismaster.hosts;
-  // In candidate servers
-  var inCandidateServers = function(name, candidateServers) {
-    for(var i = 0; i < candidateServers.length; i++) {
-      if(candidateServers[i].name == name) return true;
-    }
-
-    return false;
-  }
-
-  // New servers
-  var newServers = [];
-  if(Array.isArray(hosts)) {
-    // Let's go over all the hosts
-    for(var i = 0; i < hosts.length; i++) {
-      if(!state.contains(hosts[i]) 
-        && !inCandidateServers(hosts[i], candidateServers)) {
-          newServers.push(createServer(self, hosts[i], self.options));
-      }
-    }    
-  }
-
-  // Return list of possible new servers
-  return newServers;
-}
-
-var _connectHandler = function(self, candidateServers, instanceServer) {
-  return function(err, doc) {
-    // If we have an error add to the list
-    if(err) {
-      self._state.errors[instanceServer.name] = instanceServer;
-    } else {
-      delete self._state.errors[instanceServer.name];
-    }
-
-    if(!err) {      
-      var ismaster = doc.documents[0]
-
-      // Error the server if 
-      if(!ismaster.ismaster
-        && !ismaster.secondary) {
-        self._state.errors[instanceServer.name] = instanceServer;
-      }
-    }
-
-
-    // No error let's analyse the ismaster command
-    if(!err && self._state.errors[instanceServer.name] == null) {
-      var ismaster = doc.documents[0]
-
-      // If no replicaset name exists set the current one
-      if(self.options.rs_name == null) {
-        self.options.rs_name = ismaster.setName;
-      }
-
-      // If we have a member that is not part of the set let's finish up
-      if(typeof ismaster.setName == 'string' && ismaster.setName != self.options.rs_name) {
-        return self.emit("connectionError", new Error("Replicaset name " + ismaster.setName + " does not match specified name " + self.options.rs_name));
-      }
-
-      // Add the error handlers
-      instanceServer.on("close", _handler("close", self, instanceServer));
-      instanceServer.on("error", _handler("error", self, instanceServer));
-      instanceServer.on("timeout", _handler("timeout", self, instanceServer));
-      
-      // Set any tags on the instance server
-      instanceServer.name = ismaster.me;
-      instanceServer.tags = ismaster.tags;
-
-      // Add the server to the list
-      self._state.addServer(instanceServer, ismaster);
-
-      // Check if we have more servers to add (only check when done with initial set)
-      if(candidateServers.length == 0) {
-        // Get additional new servers that are not currently in set
-        var new_servers = locateNewServers(self, self._state, candidateServers, ismaster);
-
-        // Locate any new servers that have not errored out yet
-        for(var i = 0; i < new_servers.length; i++) {
-          if(self._state.errors[new_servers[i].name] == null) {
-            candidateServers.push(new_servers[i])            
-          }
-        }
-      }
-    }
-
-    // If the candidate server list is empty and no valid servers
-    if(candidateServers.length == 0 &&
-      !self._state.hasValidServers()) {
-        return self.emit("connectionError", new Error("No valid replicaset instance servers found"));
-    } else if(candidateServers.length == 0) {      
-      if(!self.options.connectWithNoPrimary && (self._state.master == null || !self._state.master.isConnected())) {
-        return self.emit("connectionError", new Error("No primary found in set"));
-      }
-      return self.emit("fullsetup", null, self.options.db, self);
-    }
-        
-    // Let's connect the next server    
-    var nextServer = candidateServers.pop();
-  
-    // Set up the options
-    var opts = {
-      returnIsMasterResults: true,
-      eventReceiver: nextServer
-    }
-
-    // Attempt to connect to the server
-    nextServer.connect(self.options.db, opts, _connectHandler(self, candidateServers, nextServer));
-  }
-}
-
-ReplSet.prototype.isDestroyed = function() {
-  return this._serverState == ReplSet.REPLSET_DESTROYED;
-}
-
-ReplSet.prototype.isConnected = function(read) {
-  var isConnected = false;  
-
-  if(read == null || read == ReadPreference.PRIMARY || read == false)
-    isConnected = this._state.master != null && this._state.master.isConnected();
-
-  if((read == ReadPreference.PRIMARY_PREFERRED || read == ReadPreference.SECONDARY_PREFERRED || read == ReadPreference.NEAREST)
-    && ((this._state.master != null && this._state.master.isConnected())
-    || (this._state && this._state.secondaries && Object.keys(this._state.secondaries).length > 0))) {
-      isConnected = true;
-  } else if(read == ReadPreference.SECONDARY) {
-    isConnected = this._state && this._state.secondaries && Object.keys(this._state.secondaries).length > 0;
-  }
-
-  // No valid connection return false
-  return isConnected;
-}
-
-ReplSet.prototype.isMongos = function() {
-  return false;
-}
-
-ReplSet.prototype.checkoutWriter = function() {
-  if(this._state.master) return this._state.master.checkoutWriter();
-  return new Error("no writer connection available");
-}
-
-ReplSet.prototype.processIsMaster = function(_server, _ismaster) {
-  // Server in recovery mode, remove it from available servers
-  if(!_ismaster.ismaster && !_ismaster.secondary) {
-    // Locate the actual server
-    var server = this._state.addresses[_server.name];
-    // Close the server, simulating the closing of the connection
-    // to get right removal semantics
-    if(server) server.close();
-    // Execute any callback errors
-    _handler(null, this, server)(new Error("server is in recovery mode"));
-  }
-}
-
-ReplSet.prototype.allRawConnections = function() {
-  var connections = [];
-
-  for(var name in this._state.addresses) {
-    connections = connections.concat(this._state.addresses[name].allRawConnections());
-  }
-
-  return connections;
-}
-
-/**
- * @ignore
- */
-ReplSet.prototype.allServerInstances = function() {
-  var self = this;
-  // If no state yet return empty
-  if(!self._state) return [];
-  // Close all the servers (concatenate entire list of servers first for ease)
-  var allServers = self._state.master != null ? [self._state.master] : [];
-
-  // Secondary keys
-  var keys = Object.keys(self._state.secondaries);
-  // Add all secondaries
-  for(var i = 0; i < keys.length; i++) {
-    allServers.push(self._state.secondaries[keys[i]]);
-  }
-
-  // Return complete list of all servers
-  return allServers;
-}
-
-/**
- * @ignore
- */
-ReplSet.prototype.checkoutReader = function(readPreference, tags) {
-  var connection = null;
-
-  // If we have a read preference object unpack it
-  if(typeof readPreference == 'object' && readPreference['_type'] == 'ReadPreference') {
-    // Validate if the object is using a valid mode
-    if(!readPreference.isValid()) throw new Error("Illegal readPreference mode specified, " + readPreference.mode);
-    // Set the tag
-    tags = readPreference.tags;
-    readPreference = readPreference.mode;
-  } else if(typeof readPreference == 'object' && readPreference['_type'] != 'ReadPreference') {
-    return new Error("read preferences must be either a string or an instance of ReadPreference");
-  }
-
-  // Set up our read Preference, allowing us to override the readPreference
-  var finalReadPreference = readPreference != null ? readPreference : this.options.readPreference;
-
-  // Ensure we unpack a reference
-  if(finalReadPreference != null && typeof finalReadPreference == 'object' && finalReadPreference['_type'] == 'ReadPreference') {
-    // Validate if the object is using a valid mode
-    if(!finalReadPreference.isValid()) throw new Error("Illegal readPreference mode specified, " + finalReadPreference.mode);
-    // Set the tag
-    tags = finalReadPreference.tags;
-    readPreference = finalReadPreference.mode;
-  }
-
-  // Finalize the read preference setup
-  finalReadPreference = finalReadPreference == true ? ReadPreference.SECONDARY_PREFERRED : finalReadPreference;
-  finalReadPreference = finalReadPreference == null ? ReadPreference.PRIMARY : finalReadPreference;
-
-  // If we are reading from a primary
-  if(finalReadPreference == 'primary') {
-    // If we provide a tags set send an error
-    if(typeof tags == 'object' && tags != null) {
-      return new Error("PRIMARY cannot be combined with tags");
-    }
-
-    // If we provide a tags set send an error
-    if(this._state.master == null) {
-      return new Error("No replica set primary available for query with ReadPreference PRIMARY");
-    }
-
-    // Checkout a writer
-    return this.checkoutWriter();
-  }
-
-  // If we have specified to read from a secondary server grab a random one and read
-  // from it, otherwise just pass the primary connection
-  if((this.options.readSecondary || finalReadPreference == ReadPreference.SECONDARY_PREFERRED || finalReadPreference == ReadPreference.SECONDARY) && Object.keys(this._state.secondaries).length > 0) {
-    // If we have tags, look for servers matching the specific tag
-    if(this.strategyInstance != null) {
-      // Only pick from secondaries
-      var _secondaries = [];
-      for(var key in this._state.secondaries) {
-        _secondaries.push(this._state.secondaries[key]);
-      }
-
-      if(finalReadPreference == ReadPreference.SECONDARY) {
-        // Check out the nearest from only the secondaries
-        connection = this.strategyInstance.checkoutConnection(tags, _secondaries);
-      } else {
-        connection = this.strategyInstance.checkoutConnection(tags, _secondaries);
-        // No candidate servers that match the tags, error
-        if(connection == null || connection instanceof Error) {
-          // No secondary server avilable, attemp to checkout a primary server
-          connection = this.checkoutWriter();
-          // If no connection return an error
-          if(connection == null || connection instanceof Error) {
-            return new Error("No replica set members available for query");
-          }
-        }
-      }
-    } else if(tags != null && typeof tags == 'object') {
-      // Get connection
-      connection = _pickFromTags(this, tags);// = function(self, readPreference, tags) {
-      // No candidate servers that match the tags, error
-      if(connection == null) {
-        return new Error("No replica set members available for query");
-      }
-    } else {
-      connection = _roundRobin(this, tags);
-    }
-  } else if(finalReadPreference == ReadPreference.PRIMARY_PREFERRED) {
-    // Check if there is a primary available and return that if possible
-    connection = this.checkoutWriter();
-    // If no connection available checkout a secondary
-    if(connection == null || connection instanceof Error) {
-      // If we have tags, look for servers matching the specific tag
-      if(tags != null && typeof tags == 'object') {
-        // Get connection
-        connection = _pickFromTags(this, tags);// = function(self, readPreference, tags) {
-        // No candidate servers that match the tags, error
-        if(connection == null) {
-          return new Error("No replica set members available for query");
-        }
-      } else {
-        connection = _roundRobin(this, tags);
-      }
-    }
-  } else if(finalReadPreference == ReadPreference.SECONDARY_PREFERRED) {
-    // If we have tags, look for servers matching the specific tag
-    if(this.strategyInstance != null) {
-      connection = this.strategyInstance.checkoutConnection(tags);
-      
-      // No candidate servers that match the tags, error
-      if(connection == null || connection instanceof Error) {
-        // No secondary server avilable, attemp to checkout a primary server
-        connection = this.checkoutWriter();
-        // If no connection return an error
-        if(connection == null || connection instanceof Error) {
-          var preferenceName = finalReadPreference == ReadPreference.SECONDARY ? 'secondary' : finalReadPreference;
-          return new Error("No replica set member available for query with ReadPreference " + preferenceName + " and tags " + JSON.stringify(tags));
-        }
-      }
-    } else if(tags != null && typeof tags == 'object') {
-      // Get connection
-      connection = _pickFromTags(this, tags);// = function(self, readPreference, tags) {
-      // No candidate servers that match the tags, error
-      if(connection == null) {
-        // No secondary server avilable, attemp to checkout a primary server
-        connection = this.checkoutWriter();
-        // If no connection return an error
-        if(connection == null || connection instanceof Error) {
-          var preferenceName = finalReadPreference == ReadPreference.SECONDARY ? 'secondary' : finalReadPreference;
-          return new Error("No replica set member available for query with ReadPreference " + preferenceName + " and tags " + JSON.stringify(tags));
-        }
-      }
-    }
-  } else if(finalReadPreference == ReadPreference.NEAREST && this.strategyInstance != null) {
-    connection = this.strategyInstance.checkoutConnection(tags);
-  } else if(finalReadPreference == ReadPreference.NEAREST && this.strategyInstance == null) {
-    return new Error("A strategy for calculating nearness must be enabled such as ping or statistical");
-  } else if(finalReadPreference == ReadPreference.SECONDARY && Object.keys(this._state.secondaries).length == 0) {
-    if(tags != null && typeof tags == 'object') {
-      var preferenceName = finalReadPreference == ReadPreference.SECONDARY ? 'secondary' : finalReadPreference;
-      return new Error("No replica set member available for query with ReadPreference " + preferenceName + " and tags " + JSON.stringify(tags));
-    } else {
-      return new Error("No replica set secondary available for query with ReadPreference SECONDARY");
-    }
-  } else {
-    connection = this.checkoutWriter();
-  }
-
-  // Return the connection
-  return connection;
-}
-
-/**
- * @ignore
- */
-var _pickFromTags = function(self, tags) {
-  // If we have an array or single tag selection
-  var tagObjects = Array.isArray(tags) ? tags : [tags];
-  // Iterate over all tags until we find a candidate server
-  for(var _i = 0; _i < tagObjects.length; _i++) {
-    // Grab a tag object
-    var tagObject = tagObjects[_i];
-    // Matching keys
-    var matchingKeys = Object.keys(tagObject);
-    // Match all the servers that match the provdided tags
-    var keys = Object.keys(self._state.secondaries);
-    var candidateServers = [];
-
-    for(var i = 0; i < keys.length; i++) {
-      var server = self._state.secondaries[keys[i]];
-      // If we have tags match
-      if(server.tags != null) {
-        var matching = true;
-        // Ensure we have all the values
-        for(var j = 0; j < matchingKeys.length; j++) {
-          if(server.tags[matchingKeys[j]] != tagObject[matchingKeys[j]]) {
-            matching = false;
-            break;
-          }
-        }
-
-        // If we have a match add it to the list of matching servers
-        if(matching) {
-          candidateServers.push(server);
-        }
-      }
-    }
-
-    // If we have a candidate server return
-    if(candidateServers.length > 0) {
-      if(self.strategyInstance) return self.strategyInstance.checkoutConnection(tags, candidateServers);
-      // Set instance to return
-      return candidateServers[Math.floor(Math.random() * candidateServers.length)].checkoutReader();
-    }
-  }
-
-  // No connection found
-  return null;
-}
-
-/**
- * Pick a secondary using round robin
- *
- * @ignore
- */
-function _roundRobin (replset, tags) {
-  var keys = Object.keys(replset._state.secondaries);
-  // Update index
-  replset._currentServerChoice = replset._currentServerChoice + 1;
-  // Pick a server
-  var key = keys[replset._currentServerChoice % keys.length];
-
-  var conn = null != replset._state.secondaries[key]
-    ? replset._state.secondaries[key].checkoutReader()
-    : null;
-
-  // If connection is null fallback to first available secondary
-  if(null == conn) {
-    conn = pickFirstConnectedSecondary(replset, tags);
-  }
-
-  return conn;
-}
-
-/**
- * @ignore
- */
-var pickFirstConnectedSecondary = function pickFirstConnectedSecondary(self, tags) {
-  var keys = Object.keys(self._state.secondaries);
-  var connection;
-
-  // Find first available reader if any
-  for(var i = 0; i < keys.length; i++) {
-    connection = self._state.secondaries[keys[i]].checkoutReader();
-    if(connection) return connection;
-  }
-
-  // If we still have a null, read from primary if it's not secondary only
-  if(self._readPreference == ReadPreference.SECONDARY_PREFERRED) {
-    connection = self._state.master.checkoutReader();
-    if(connection) return connection;
-  }
-
-  var preferenceName = self._readPreference == ReadPreference.SECONDARY_PREFERRED
-    ? 'secondary'
-    : self._readPreference;
-
-  return new Error("No replica set member available for query with ReadPreference "
-                  + preferenceName + " and tags " + JSON.stringify(tags));
-}
-
-/**
- * Get list of secondaries
- * @ignore
- */
-Object.defineProperty(ReplSet.prototype, "secondaries", {enumerable: true
-  , get: function() {
-      return utils.objectToArray(this._state.secondaries);
-    }
-});
-
-/**
- * Get list of secondaries
- * @ignore
- */
-Object.defineProperty(ReplSet.prototype, "arbiters", {enumerable: true
-  , get: function() {
-      return utils.objectToArray(this._state.arbiters);
-    }
-});
-

http://git-wip-us.apache.org/repos/asf/incubator-apex-malhar/blob/e1a45507/web/demos/package/node_modules/mongodb/lib/mongodb/connection/repl_set/repl_set_state.js
----------------------------------------------------------------------
diff --git a/web/demos/package/node_modules/mongodb/lib/mongodb/connection/repl_set/repl_set_state.js b/web/demos/package/node_modules/mongodb/lib/mongodb/connection/repl_set/repl_set_state.js
deleted file mode 100644
index 1fbd9c0..0000000
--- a/web/demos/package/node_modules/mongodb/lib/mongodb/connection/repl_set/repl_set_state.js
+++ /dev/null
@@ -1,74 +0,0 @@
-/**
- * Interval state object constructor
- *
- * @ignore
- */
-var ReplSetState = function ReplSetState (replset) {
-  this.errorMessages = [];
-  this.secondaries = {};
-  this.addresses = {};
-  this.arbiters = {};
-  this.passives = {};
-  this.members = [];
-  this.errors = {};
-  this.setName = null;
-  this.master = null;
-  this.replset = replset;
-}
-
-ReplSetState.prototype.hasValidServers = function() {
-  var validServers = [];
-  if(this.master && this.master.isConnected()) return true;
-
-  if(this.secondaries) {
-    var keys = Object.keys(this.secondaries)
-    for(var i = 0; i < keys.length; i++) {
-      if(this.secondaries[keys[i]].isConnected())
-        return true;
-    }
-  }
-
-  return false;
-}
-
-ReplSetState.prototype.getAllReadServers = function() {
-  var candidate_servers = [];
-  for(var name in this.addresses) {
-    candidate_servers.push(this.addresses[name]);
-  }
-
-  // Return all possible read candidates
-  return candidate_servers;
-}
-
-ReplSetState.prototype.addServer = function(server, master) {
-  server.name = master.me;
-
-  if(master.ismaster) {
-    this.master = server;
-    this.addresses[server.name] = server;
-    this.replset.emit('joined', "primary", master, server);
-  } else if(master.secondary) {
-    this.secondaries[server.name] = server;
-    this.addresses[server.name] = server;
-    this.replset.emit('joined', "secondary", master, server);
-  } else if(master.arbiters) {
-    this.arbiters[server.name] = server;
-    this.addresses[server.name] = server;
-    this.replset.emit('joined', "arbiter", master, server);
-  }
-}
-
-ReplSetState.prototype.contains = function(host) {
-  return this.addresses[host] != null;
-}
-
-ReplSetState.prototype.isPrimary = function(server) {
-  return this.master && this.master.name == server.name;
-}
-
-ReplSetState.prototype.isSecondary = function(server) {
-  return this.secondaries[server.name] != null;
-}
-
-exports.ReplSetState = ReplSetState;

http://git-wip-us.apache.org/repos/asf/incubator-apex-malhar/blob/e1a45507/web/demos/package/node_modules/mongodb/lib/mongodb/connection/repl_set/strategies/ping_strategy.js
----------------------------------------------------------------------
diff --git a/web/demos/package/node_modules/mongodb/lib/mongodb/connection/repl_set/strategies/ping_strategy.js b/web/demos/package/node_modules/mongodb/lib/mongodb/connection/repl_set/strategies/ping_strategy.js
deleted file mode 100644
index 15a3a88..0000000
--- a/web/demos/package/node_modules/mongodb/lib/mongodb/connection/repl_set/strategies/ping_strategy.js
+++ /dev/null
@@ -1,333 +0,0 @@
-var Server = require("../../server").Server
-  , format = require('util').format;
-
-// The ping strategy uses pings each server and records the
-// elapsed time for the server so it can pick a server based on lowest
-// return time for the db command {ping:true}
-var PingStrategy = exports.PingStrategy = function(replicaset, secondaryAcceptableLatencyMS) {
-  this.replicaset = replicaset;
-  this.secondaryAcceptableLatencyMS = secondaryAcceptableLatencyMS;
-  this.state = 'disconnected';
-  this.pingInterval = 5000;
-  // Class instance
-  this.Db = require("../../../db").Db;
-  // Active db connections
-  this.dbs = {};
-  // Current server index
-  this.index = 0;
-  // Logger api
-  this.Logger = null;
-}
-
-// Starts any needed code
-PingStrategy.prototype.start = function(callback) {
-  // already running?
-  if ('connected' == this.state) return;
-
-  this.state = 'connected';
-
-  // Start ping server
-  this._pingServer(callback);
-}
-
-// Stops and kills any processes running
-PingStrategy.prototype.stop = function(callback) {
-  // Stop the ping process
-  this.state = 'disconnected';
-
-  // Stop all the server instances
-  for(var key in this.dbs) {
-    this.dbs[key].close();
-  }
-
-  // optional callback
-  callback && callback(null, null);
-}
-
-PingStrategy.prototype.checkoutConnection = function(tags, secondaryCandidates) {
-  // Servers are picked based on the lowest ping time and then servers that lower than that + secondaryAcceptableLatencyMS
-  // Create a list of candidat servers, containing the primary if available
-  var candidateServers = [];
-  var self = this;
-
-  // If we have not provided a list of candidate servers use the default setup
-  if(!Array.isArray(secondaryCandidates)) {
-    candidateServers = this.replicaset._state.master != null ? [this.replicaset._state.master] : [];
-    // Add all the secondaries
-    var keys = Object.keys(this.replicaset._state.secondaries);
-    for(var i = 0; i < keys.length; i++) {
-      candidateServers.push(this.replicaset._state.secondaries[keys[i]])
-    }
-  } else {
-    candidateServers = secondaryCandidates;
-  }
-
-  // Final list of eligable server
-  var finalCandidates = [];
-
-  // If we have tags filter by tags
-  if(tags != null && typeof tags == 'object') {
-    // If we have an array or single tag selection
-    var tagObjects = Array.isArray(tags) ? tags : [tags];
-    // Iterate over all tags until we find a candidate server
-    for(var _i = 0; _i < tagObjects.length; _i++) {
-      // Grab a tag object
-      var tagObject = tagObjects[_i];
-      // Matching keys
-      var matchingKeys = Object.keys(tagObject);
-      // Remove any that are not tagged correctly
-      for(var i = 0; i < candidateServers.length; i++) {
-        var server = candidateServers[i];
-        // If we have tags match
-        if(server.tags != null) {
-          var matching = true;
-
-          // Ensure we have all the values
-          for(var j = 0; j < matchingKeys.length; j++) {
-            if(server.tags[matchingKeys[j]] != tagObject[matchingKeys[j]]) {
-              matching = false;
-              break;
-            }
-          }
-
-          // If we have a match add it to the list of matching servers
-          if(matching) {
-            finalCandidates.push(server);
-          }
-        }
-      }
-    }
-  } else {
-    // Final array candidates
-    var finalCandidates = candidateServers;
-  }
-
-  // Sort by ping time
-  finalCandidates.sort(function(a, b) {
-    return a.runtimeStats['pingMs'] > b.runtimeStats['pingMs'];
-  });
-
-  if(0 === finalCandidates.length)
-    return new Error("No replica set members available for query");
-
-  // find lowest server with a ping time
-  var lowest = finalCandidates.filter(function (server) {
-    return undefined != server.runtimeStats.pingMs;
-  })[0];
-
-  if(!lowest) {
-    lowest = finalCandidates[0];
-  }
-
-  // convert to integer
-  var lowestPing = lowest.runtimeStats.pingMs | 0;
-  
-  // determine acceptable latency
-  var acceptable = lowestPing + this.secondaryAcceptableLatencyMS;
-
-  // remove any server responding slower than acceptable
-  var len = finalCandidates.length;
-  while(len--) {
-    if(finalCandidates[len].runtimeStats['pingMs'] > acceptable) {
-      finalCandidates.splice(len, 1);
-    }
-  }
-
-  if(self.logger && self.logger.debug) {    
-    self.logger.debug("Ping strategy selection order for tags", tags);
-    finalCandidates.forEach(function(c) {
-      self.logger.debug(format("%s:%s = %s ms", c.host, c.port, c.runtimeStats['pingMs']), null);
-    })    
-  }
-
-  // If no candidates available return an error
-  if(finalCandidates.length == 0)
-    return new Error("No replica set members available for query");
-
-  // Ensure no we don't overflow
-  this.index = this.index % finalCandidates.length
-  // Pick a random acceptable server  
-  var connection = finalCandidates[this.index].checkoutReader();
-  // Point to next candidate (round robin style)
-  this.index = this.index + 1;
-
-  if(self.logger && self.logger.debug) {    
-    if(connection)
-      self.logger.debug("picked server %s:%s", connection.socketOptions.host, connection.socketOptions.port);
-  }
-
-  return connection;
-}
-
-PingStrategy.prototype._pingServer = function(callback) {
-  var self = this;
-
-  // Ping server function
-  var pingFunction = function() {
-    // Our state changed to disconnected or destroyed return
-    if(self.state == 'disconnected' || self.state == 'destroyed') return;
-    // If the replicaset is destroyed return
-    if(self.replicaset.isDestroyed() || self.replicaset._serverState == 'disconnected') return
-
-    // Create a list of all servers we can send the ismaster command to
-    var allServers = self.replicaset._state.master != null ? [self.replicaset._state.master] : [];
-
-    // Secondary keys
-    var keys = Object.keys(self.replicaset._state.secondaries);
-    // Add all secondaries
-    for(var i = 0; i < keys.length; i++) {
-      allServers.push(self.replicaset._state.secondaries[keys[i]]);
-    }
-
-    // Number of server entries
-    var numberOfEntries = allServers.length;
-
-    // We got keys
-    for(var i = 0; i < allServers.length; i++) {
-
-      // We got a server instance
-      var server = allServers[i];
-
-      // Create a new server object, avoid using internal connections as they might
-      // be in an illegal state
-      new function(serverInstance) {
-        var _db = self.dbs[serverInstance.host + ":" + serverInstance.port];
-        // If we have a db
-        if(_db != null) {
-          // Startup time of the command
-          var startTime = Date.now();
-
-          // Execute ping command in own scope
-          var _ping = function(__db, __serverInstance) {
-            // Execute ping on this connection
-            __db.executeDbCommand({ping:1}, {failFast:true}, function(err) {
-              if(err) {
-                delete self.dbs[__db.serverConfig.host + ":" + __db.serverConfig.port];
-                __db.close();
-                return done();
-              }
-
-              if(null != __serverInstance.runtimeStats && __serverInstance.isConnected()) {
-                __serverInstance.runtimeStats['pingMs'] = Date.now() - startTime;
-              }
-
-              __db.executeDbCommand({ismaster:1}, {failFast:true}, function(err, result) {
-                if(err) {
-                  delete self.dbs[__db.serverConfig.host + ":" + __db.serverConfig.port];
-                  __db.close();
-                  return done();
-                }
-
-                // Process the ismaster for the server
-                if(result && result.documents && self.replicaset.processIsMaster) {
-                  self.replicaset.processIsMaster(__serverInstance, result.documents[0]);
-                }
-
-                // Done with the pinging
-                done();
-              });
-            });            
-          };
-          // Ping
-          _ping(_db, serverInstance);
-        } else {
-          var connectTimeoutMS = self.replicaset.options.socketOptions 
-            ? self.replicaset.options.socketOptions.connectTimeoutMS : 0
-
-          // Create a new master connection
-          var _server = new Server(serverInstance.host, serverInstance.port, {
-            auto_reconnect: false,
-            returnIsMasterResults: true,
-            slaveOk: true,
-            poolSize: 1,
-            socketOptions: { connectTimeoutMS: connectTimeoutMS },
-            ssl: self.replicaset.options.ssl,
-            sslValidate: self.replicaset.options.sslValidate,
-            sslCA: self.replicaset.options.sslCA,
-            sslCert: self.replicaset.options.sslCert,
-            sslKey: self.replicaset.options.sslKey,
-            sslPass: self.replicaset.options.sslPass
-          });
-
-          // Create Db instance        
-          var _db = new self.Db('local', _server, { safe: true });
-          _db.on("close", function() {
-            delete self.dbs[this.serverConfig.host + ":" + this.serverConfig.port];
-          })
-
-          var _ping = function(__db, __serverInstance) {
-            if(self.state == 'disconnected') {
-              self.stop();
-              return;
-            }
-
-            __db.open(function(err, db) {  
-              if(self.state == 'disconnected' && __db != null) {
-                return __db.close();
-              }
-
-              if(err) {
-                delete self.dbs[__db.serverConfig.host + ":" + __db.serverConfig.port];
-                __db.close();
-                return done();
-              }
-
-              // Save instance
-              self.dbs[__db.serverConfig.host + ":" + __db.serverConfig.port] = __db;
-
-              // Startup time of the command
-              var startTime = Date.now();
-
-              // Execute ping on this connection
-              __db.executeDbCommand({ping:1}, {failFast:true}, function(err) {
-                if(err) {
-                  delete self.dbs[__db.serverConfig.host + ":" + __db.serverConfig.port];
-                  __db.close();
-                  return done();
-                }
-
-                if(null != __serverInstance.runtimeStats && __serverInstance.isConnected()) {
-                  __serverInstance.runtimeStats['pingMs'] = Date.now() - startTime;
-                }
-
-                __db.executeDbCommand({ismaster:1}, {failFast:true}, function(err, result) {
-                  if(err) {
-                    delete self.dbs[__db.serverConfig.host + ":" + __db.serverConfig.port];
-                    __db.close();
-                    return done();
-                  }
-    
-                  // Process the ismaster for the server
-                  if(result && result.documents && self.replicaset.processIsMaster) {
-                    self.replicaset.processIsMaster(__serverInstance, result.documents[0]);
-                  }
-
-                  // Done with the pinging
-                  done();
-                });
-              });
-            });            
-          };
-
-          // Ping the server
-          _ping(_db, serverInstance);
-        }
-
-        function done() {
-          // Adjust the number of checks
-          numberOfEntries--;
-
-          // If we are done with all results coming back trigger ping again
-          if(0 === numberOfEntries && 'connected' == self.state) {
-            setTimeout(pingFunction, self.pingInterval);
-          }
-        }
-      }(server);
-    }
-  }
-
-  // Start pingFunction
-  pingFunction();
-
-  callback && callback(null);
-}

http://git-wip-us.apache.org/repos/asf/incubator-apex-malhar/blob/e1a45507/web/demos/package/node_modules/mongodb/lib/mongodb/connection/repl_set/strategies/statistics_strategy.js
----------------------------------------------------------------------
diff --git a/web/demos/package/node_modules/mongodb/lib/mongodb/connection/repl_set/strategies/statistics_strategy.js b/web/demos/package/node_modules/mongodb/lib/mongodb/connection/repl_set/strategies/statistics_strategy.js
deleted file mode 100644
index f9b8c46..0000000
--- a/web/demos/package/node_modules/mongodb/lib/mongodb/connection/repl_set/strategies/statistics_strategy.js
+++ /dev/null
@@ -1,80 +0,0 @@
-// The Statistics strategy uses the measure of each end-start time for each
-// query executed against the db to calculate the mean, variance and standard deviation
-// and pick the server which the lowest mean and deviation
-var StatisticsStrategy = exports.StatisticsStrategy = function(replicaset) {
-  this.replicaset = replicaset;
-  // Logger api
-  this.Logger = null;  
-}
-
-// Starts any needed code
-StatisticsStrategy.prototype.start = function(callback) {
-  callback && callback(null, null);
-}
-
-StatisticsStrategy.prototype.stop = function(callback) {
-  callback && callback(null, null);
-}
-
-StatisticsStrategy.prototype.checkoutConnection = function(tags, secondaryCandidates) {
-  // Servers are picked based on the lowest ping time and then servers that lower than that + secondaryAcceptableLatencyMS
-  // Create a list of candidat servers, containing the primary if available
-  var candidateServers = [];
-
-  // If we have not provided a list of candidate servers use the default setup
-  if(!Array.isArray(secondaryCandidates)) {
-    candidateServers = this.replicaset._state.master != null ? [this.replicaset._state.master] : [];
-    // Add all the secondaries
-    var keys = Object.keys(this.replicaset._state.secondaries);
-    for(var i = 0; i < keys.length; i++) {
-      candidateServers.push(this.replicaset._state.secondaries[keys[i]])
-    }
-  } else {
-    candidateServers = secondaryCandidates;
-  }
-
-  // Final list of eligable server
-  var finalCandidates = [];
-
-  // If we have tags filter by tags
-  if(tags != null && typeof tags == 'object') {
-    // If we have an array or single tag selection
-    var tagObjects = Array.isArray(tags) ? tags : [tags];
-    // Iterate over all tags until we find a candidate server
-    for(var _i = 0; _i < tagObjects.length; _i++) {
-      // Grab a tag object
-      var tagObject = tagObjects[_i];
-      // Matching keys
-      var matchingKeys = Object.keys(tagObject);
-      // Remove any that are not tagged correctly
-      for(var i = 0; i < candidateServers.length; i++) {
-        var server = candidateServers[i];
-        // If we have tags match
-        if(server.tags != null) {
-          var matching = true;
-
-          // Ensure we have all the values
-          for(var j = 0; j < matchingKeys.length; j++) {
-            if(server.tags[matchingKeys[j]] != tagObject[matchingKeys[j]]) {
-              matching = false;
-              break;
-            }
-          }
-
-          // If we have a match add it to the list of matching servers
-          if(matching) {
-            finalCandidates.push(server);
-          }
-        }
-      }
-    }
-  } else {
-    // Final array candidates
-    var finalCandidates = candidateServers;
-  }
-
-  // If no candidates available return an error
-  if(finalCandidates.length == 0) return new Error("No replica set members available for query");
-  // Pick a random server
-  return finalCandidates[Math.round(Math.random(1000000) * (finalCandidates.length - 1))].checkoutReader();
-}

http://git-wip-us.apache.org/repos/asf/incubator-apex-malhar/blob/e1a45507/web/demos/package/node_modules/mongodb/lib/mongodb/connection/server.js
----------------------------------------------------------------------
diff --git a/web/demos/package/node_modules/mongodb/lib/mongodb/connection/server.js b/web/demos/package/node_modules/mongodb/lib/mongodb/connection/server.js
deleted file mode 100644
index 36a3bc0..0000000
--- a/web/demos/package/node_modules/mongodb/lib/mongodb/connection/server.js
+++ /dev/null
@@ -1,940 +0,0 @@
-var Connection = require('./connection').Connection,
-  ReadPreference = require('./read_preference').ReadPreference,
-  DbCommand = require('../commands/db_command').DbCommand,
-  MongoReply = require('../responses/mongo_reply').MongoReply,
-  ConnectionPool = require('./connection_pool').ConnectionPool,
-  EventEmitter = require('events').EventEmitter,
-  ServerCapabilities = require('./server_capabilities').ServerCapabilities,
-  Base = require('./base').Base,
-  format = require('util').format,
-  utils = require('../utils'),
-  timers = require('timers'),
-  inherits = require('util').inherits;
-
-// Set processor, setImmediate if 0.10 otherwise nextTick
-var processor = require('../utils').processor();
-
-/**
- * Class representing a single MongoDB Server connection
- *
- * Options
- *  - **readPreference** {String, default:null}, set's the read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST)
- *  - **ssl** {Boolean, default:false}, use ssl connection (needs to have a mongod server with ssl support)
- *  - **sslValidate** {Boolean, default:false}, validate mongod server certificate against ca (needs to have a mongod server with ssl support, 2.4 or higher)
- *  - **sslCA** {Array, default:null}, Array of valid certificates either as Buffers or Strings (needs to have a mongod server with ssl support, 2.4 or higher)
- *  - **sslCert** {Buffer/String, default:null}, String or buffer containing the certificate we wish to present (needs to have a mongod server with ssl support, 2.4 or higher)
- *  - **sslKey** {Buffer/String, default:null}, String or buffer containing the certificate private key we wish to present (needs to have a mongod server with ssl support, 2.4 or higher)
- *  - **sslPass** {Buffer/String, default:null}, String or buffer containing the certificate password (needs to have a mongod server with ssl support, 2.4 or higher)
- *  - **poolSize** {Number, default:5}, number of connections in the connection pool, set to 5 as default for legacy reasons.
- *  - **socketOptions** {Object, default:null}, an object containing socket options to use (noDelay:(boolean), keepAlive:(number), connectTimeoutMS:(number), socketTimeoutMS:(number))
- *  - **logger** {Object, default:null}, an object representing a logger that you want to use, needs to support functions debug, log, error **({error:function(message, object) {}, log:function(message, object) {}, debug:function(message, object) {}})**.
- *  - **auto_reconnect** {Boolean, default:false}, reconnect on error.
- *  - **disableDriverBSONSizeCheck** {Boolean, default:false}, force the server to error if the BSON message is to big
- *
- * @class Represents a Server connection.
- * @param {String} host the server host
- * @param {Number} port the server port
- * @param {Object} [options] optional options for insert command
- */
-function Server(host, port, options) {
-  // Set up Server instance
-  if(!(this instanceof Server)) return new Server(host, port, options);
-
-  // Set up event emitter
-  Base.call(this);
-
-  // Ensure correct values
-  if(port != null && typeof port == 'object') {
-    options = port;
-    port = Connection.DEFAULT_PORT;
-  }
-
-  var self = this;
-  this.host = host;
-  this.port = port;
-  this.options = options == null ? {} : options;
-  this.internalConnection;
-  this.internalMaster = false;
-  this.connected = false;  
-  this.poolSize = this.options.poolSize == null ? 5 : this.options.poolSize;
-  this.disableDriverBSONSizeCheck = this.options.disableDriverBSONSizeCheck != null ? this.options.disableDriverBSONSizeCheck : false;
-  this._used = false;
-  this.replicasetInstance = null;
-
-  // Emit open setup
-  this.emitOpen = this.options.emitOpen || true;
-  // Set ssl as connection method
-  this.ssl = this.options.ssl == null ? false : this.options.ssl;
-  // Set ssl validation
-  this.sslValidate = this.options.sslValidate == null ? false : this.options.sslValidate;
-  // Set the ssl certificate authority (array of Buffer/String keys)
-  this.sslCA = Array.isArray(this.options.sslCA) ? this.options.sslCA : null;
-  // Certificate to present to the server
-  this.sslCert = this.options.sslCert;
-  // Certificate private key if in separate file
-  this.sslKey = this.options.sslKey;
-  // Password to unlock private key
-  this.sslPass = this.options.sslPass;
-  // Server capabilities
-  this.serverCapabilities = null;
-  // Set server name
-  this.name = format("%s:%s", host, port);
-
-  // Ensure we are not trying to validate with no list of certificates
-  if(this.sslValidate && (!Array.isArray(this.sslCA) || this.sslCA.length == 0)) {
-    throw new Error("The driver expects an Array of CA certificates in the sslCA parameter when enabling sslValidate");
-  }
-
-  // Get the readPreference
-  var readPreference = this.options['readPreference'];
-  // If readPreference is an object get the mode string
-  var validateReadPreference = readPreference != null && typeof readPreference == 'object' ? readPreference.mode : readPreference;
-  // Read preference setting
-  if(validateReadPreference != null) {
-    if(validateReadPreference != ReadPreference.PRIMARY && validateReadPreference != ReadPreference.SECONDARY && validateReadPreference != ReadPreference.NEAREST
-      && validateReadPreference != ReadPreference.SECONDARY_PREFERRED && validateReadPreference != ReadPreference.PRIMARY_PREFERRED) {
-        throw new Error("Illegal readPreference mode specified, " + validateReadPreference);
-    }
-
-    // Set read Preference
-    this._readPreference = readPreference;
-  } else {
-    this._readPreference = null;
-  }
-
-  // Contains the isMaster information returned from the server
-  this.isMasterDoc;
-
-  // Set default connection pool options
-  this.socketOptions = this.options.socketOptions != null ? this.options.socketOptions : {};
-  if(this.disableDriverBSONSizeCheck) this.socketOptions.disableDriverBSONSizeCheck = this.disableDriverBSONSizeCheck;
-
-  // Set ssl up if it's defined
-  if(this.ssl) {
-    this.socketOptions.ssl = true;
-    // Set ssl validation
-    this.socketOptions.sslValidate = this.sslValidate == null ? false : this.sslValidate;
-    // Set the ssl certificate authority (array of Buffer/String keys)
-    this.socketOptions.sslCA = Array.isArray(this.sslCA) ? this.sslCA : null;
-    // Set certificate to present
-    this.socketOptions.sslCert = this.sslCert;
-    // Set certificate to present
-    this.socketOptions.sslKey = this.sslKey;
-    // Password to unlock private key
-    this.socketOptions.sslPass = this.sslPass;
-  }
-
-  // Set up logger if any set
-  this.logger = this.options.logger != null
-    && (typeof this.options.logger.debug == 'function')
-    && (typeof this.options.logger.error == 'function')
-    && (typeof this.options.logger.log == 'function')
-      ? this.options.logger : {error:function(message, object) {}, log:function(message, object) {}, debug:function(message, object) {}};
-
-  // Just keeps list of events we allow
-  this.eventHandlers = {error:[], parseError:[], poolReady:[], message:[], close:[], timeout:[]};
-  // Internal state of server connection
-  this._serverState = 'disconnected';
-  // Contains state information about server connection
-  this._state = {'runtimeStats': {'queryStats':new RunningStats()}};
-  // Do we record server stats or not
-  this.recordQueryStats = false;
-
-  // Allow setting the socketTimeoutMS on all connections
-  // to work around issues such as secondaries blocking due to compaction
-  utils.setSocketTimeoutProperty(this, this.socketOptions);
-};
-
-/**
- * @ignore
- */
-inherits(Server, Base);
-
-//
-//  Deprecated, USE ReadPreferences class
-//
-Server.READ_PRIMARY = ReadPreference.PRIMARY;
-Server.READ_SECONDARY = ReadPreference.SECONDARY_PREFERRED;
-Server.READ_SECONDARY_ONLY = ReadPreference.SECONDARY;
-
-/**
- * Always ourselves
- * @ignore
- */
-Server.prototype.setReadPreference = function(readPreference) {
-  this._readPreference = readPreference;  
-}
-
-/**
- * @ignore
- */
-Server.prototype.isMongos = function() {
-  return this.isMasterDoc != null && this.isMasterDoc['msg'] == "isdbgrid" ? true : false;
-}
-
-/**
- * @ignore
- */
-Server.prototype._isUsed = function() {
-  return this._used;
-}
-
-/**
- * @ignore
- */
-Server.prototype.close = function(callback) {
-  // Set server status as disconnected
-  this._serverState = 'destroyed';
-  // Remove all local listeners
-  this.removeAllListeners();
-
-  if(this.connectionPool != null) {
-    // Remove all the listeners on the pool so it does not fire messages all over the place
-    this.connectionPool.removeAllEventListeners();
-    // Close the connection if it's open
-    this.connectionPool.stop(true);
-  }
-
-  // Emit close event
-  if(this.db && !this.isSetMember()) {
-    var self = this;
-    processor(function() {
-      self._emitAcrossAllDbInstances(self, null, "close", null, null, true)
-    })
-
-    // Flush out any remaining call handlers
-    self._flushAllCallHandlers(utils.toError("Connection Closed By Application"));
-  }
-
-  // Peform callback if present
-  if(typeof callback === 'function') callback(null);
-};
-
-Server.prototype.isDestroyed = function() {
-  return this._serverState == 'destroyed';
-}
-
-/**
- * @ignore
- */
-Server.prototype.isConnected = function() {
-  return this.connectionPool != null && this.connectionPool.isConnected();
-}
-
-/**
- * @ignore
- */
-Server.prototype.canWrite = Server.prototype.isConnected;
-Server.prototype.canRead = Server.prototype.isConnected;
-
-Server.prototype.isAutoReconnect = function() {
-  if(this.isSetMember()) return false;
-  return this.options.auto_reconnect != null ? this.options.auto_reconnect : true;
-}
-
-/**
- * @ignore
- */
-Server.prototype.allServerInstances = function() {
-  return [this];
-}
-
-/**
- * @ignore
- */
-Server.prototype.isSetMember = function() {
-  return this.replicasetInstance != null || this.mongosInstance != null;
-}
-
-/**
- * Assigns a replica set to this `server`.
- *
- * @param {ReplSet} replset
- * @ignore
- */
-Server.prototype.assignReplicaSet = function (replset) {
-  this.replicasetInstance = replset;
-  this.inheritReplSetOptionsFrom(replset);
-  this.enableRecordQueryStats(replset.recordQueryStats);
-}
-
-/**
- * Takes needed options from `replset` and overwrites
- * our own options.
- *
- * @param {ReplSet} replset
- * @ignore
- */
-Server.prototype.inheritReplSetOptionsFrom = function (replset) {
-  this.socketOptions = {};
-  this.socketOptions.connectTimeoutMS = replset.options.socketOptions.connectTimeoutMS || 30000;
-
-  if(replset.options.ssl) {
-    // Set ssl on
-    this.socketOptions.ssl = true;
-    // Set ssl validation
-    this.socketOptions.sslValidate = replset.options.sslValidate == null ? false : replset.options.sslValidate;
-    // Set the ssl certificate authority (array of Buffer/String keys)
-    this.socketOptions.sslCA = Array.isArray(replset.options.sslCA) ? replset.options.sslCA : null;
-    // Set certificate to present
-    this.socketOptions.sslCert = replset.options.sslCert;
-    // Set certificate to present
-    this.socketOptions.sslKey = replset.options.sslKey;
-    // Password to unlock private key
-    this.socketOptions.sslPass = replset.options.sslPass;
-  }
-
-  // If a socket option object exists clone it
-  if(utils.isObject(replset.options.socketOptions)) {
-    var keys = Object.keys(replset.options.socketOptions);
-    for(var i = 0; i < keys.length; i++)
-      this.socketOptions[keys[i]] = replset.options.socketOptions[keys[i]];
-  }
-}
-
-/**
- * Opens this server connection.
- *
- * @ignore
- */
-Server.prototype.connect = function(dbInstance, options, callback) {
-  if('function' === typeof options) callback = options, options = {};
-  if(options == null) options = {};
-  if(!('function' === typeof callback)) callback = null;
-  var self = this;
-  // Save the options
-  this.options = options;
-
-  // Currently needed to work around problems with multiple connections in a pool with ssl
-  // TODO fix if possible
-  if(this.ssl == true) {
-    // Set up socket options for ssl
-    this.socketOptions.ssl = true;
-    // Set ssl validation
-    this.socketOptions.sslValidate = this.sslValidate == null ? false : this.sslValidate;
-    // Set the ssl certificate authority (array of Buffer/String keys)
-    this.socketOptions.sslCA = Array.isArray(this.sslCA) ? this.sslCA : null;
-    // Set certificate to present
-    this.socketOptions.sslCert = this.sslCert;
-    // Set certificate to present
-    this.socketOptions.sslKey = this.sslKey;
-    // Password to unlock private key
-    this.socketOptions.sslPass = this.sslPass;
-  }
-
-  // Let's connect
-  var server = this;
-  // Let's us override the main receiver of events
-  var eventReceiver = options.eventReceiver != null ? options.eventReceiver : this;
-  // Save reference to dbInstance
-  this.db = dbInstance;  // `db` property matches ReplSet and Mongos
-  this.dbInstances = [dbInstance];
-
-  // Force connection pool if there is one
-  if(server.connectionPool) server.connectionPool.stop();
-  // Set server state to connecting
-  this._serverState = 'connecting';
-
-  if(server.connectionPool != null) {
-    // Remove all the listeners on the pool so it does not fire messages all over the place
-    this.connectionPool.removeAllEventListeners();
-    // Close the connection if it's open
-    this.connectionPool.stop(true);    
-  }
-
-  this.connectionPool = new ConnectionPool(this.host, this.port, this.poolSize, dbInstance.bson, this.socketOptions);
-  var connectionPool = this.connectionPool;
-  // If ssl is not enabled don't wait between the pool connections
-  if(this.ssl == null || !this.ssl) connectionPool._timeToWait = null;
-  // Set logger on pool
-  connectionPool.logger = this.logger;
-  connectionPool.bson = dbInstance.bson;
-
-  // Set basic parameters passed in
-  var returnIsMasterResults = options.returnIsMasterResults == null ? false : options.returnIsMasterResults;
-
-  // Create a default connect handler, overriden when using replicasets
-  var connectCallback = function(_server) {
-    return function(err, reply) {  
-      // ensure no callbacks get called twice
-      var internalCallback = callback;
-      callback = null;
-      
-      // Assign the server
-      _server = _server != null ? _server : server;
-      
-      // If something close down the connection and removed the callback before
-      // proxy killed connection etc, ignore the erorr as close event was isssued
-      if(err != null && internalCallback == null) return;
-      // Internal callback
-      if(err != null) return internalCallback(err, null, _server);
-      _server.master = reply.documents[0].ismaster == 1 ? true : false;
-      _server.connectionPool.setMaxBsonSize(reply.documents[0].maxBsonObjectSize);
-      _server.connectionPool.setMaxMessageSizeBytes(reply.documents[0].maxMessageSizeBytes);
-      // Set server state to connEcted
-      _server._serverState = 'connected';
-      // Set server as connected
-      _server.connected = true;
-      // Save document returned so we can query it
-      _server.isMasterDoc = reply.documents[0];
-      
-      if(self.emitOpen) {        
-        _server._emitAcrossAllDbInstances(_server, eventReceiver, "open", null, returnIsMasterResults ? reply : null, null);        
-        self.emitOpen = false;
-      } else {
-        _server._emitAcrossAllDbInstances(_server, eventReceiver, "reconnect", null, returnIsMasterResults ? reply : null, null);        
-      }
-
-      // Set server capabilities
-      server.serverCapabilities = new ServerCapabilities(_server.isMasterDoc);      
-
-      // If we have it set to returnIsMasterResults
-      if(returnIsMasterResults) {
-        internalCallback(null, reply, _server);
-      } else {
-        internalCallback(null, dbInstance, _server);
-      }
-    }
-  };
-
-  // Let's us override the main connect callback
-  var connectHandler = options.connectHandler == null ? connectCallback(server) : options.connectHandler;
-
-  // Set up on connect method
-  connectionPool.on("poolReady", function() {
-    // Create db command and Add the callback to the list of callbacks by the request id (mapping outgoing messages to correct callbacks)
-    var db_command = DbCommand.NcreateIsMasterCommand(dbInstance, dbInstance.databaseName);
-    // Check out a reader from the pool
-    var connection = connectionPool.checkoutConnection();
-    // Register handler for messages
-    server._registerHandler(db_command, false, connection, connectHandler);
-    // Write the command out
-    connection.write(db_command);
-  })
-
-  // Set up item connection
-  connectionPool.on("message", function(message) {
-    // Attempt to parse the message
-    try {
-      // Create a new mongo reply
-      var mongoReply = new MongoReply()
-      // Parse the header
-      mongoReply.parseHeader(message, connectionPool.bson)
-
-      // If message size is not the same as the buffer size
-      // something went terribly wrong somewhere
-      if(mongoReply.messageLength != message.length) {
-        // Emit the error
-        if(eventReceiver.listeners("error") && eventReceiver.listeners("error").length > 0) eventReceiver.emit("error", new Error("bson length is different from message length"), server);
-        // Remove all listeners
-        server.removeAllListeners();
-      } else {
-        var startDate = new Date().getTime();
-
-        // Callback instance
-        var callbackInfo = server._findHandler(mongoReply.responseTo.toString());
-
-        // The command executed another request, log the handler again under that request id
-        if(mongoReply.requestId > 0 && mongoReply.cursorId.toString() != "0" 
-          && callbackInfo && callbackInfo.info && callbackInfo.info.exhaust) {
-            server._reRegisterHandler(mongoReply.requestId, callbackInfo);
-        }
-        // Parse the body
-        mongoReply.parseBody(message, connectionPool.bson, callbackInfo.info.raw, function(err) {
-          if(err != null) {
-            // If pool connection is already closed
-            if(server._serverState === 'disconnected') return;
-            // Set server state to disconnected
-            server._serverState = 'disconnected';
-            // Remove all listeners and close the connection pool
-            server.removeAllListeners();
-            connectionPool.stop(true);
-
-            // If we have a callback return the error
-            if(typeof callback === 'function') {
-              // ensure no callbacks get called twice
-              var internalCallback = callback;
-              callback = null;
-              // Perform callback
-              internalCallback(err, null, server);
-            } else if(server.isSetMember()) {
-              if(server.listeners("parseError") && server.listeners("parseError").length > 0) server.emit("parseError", utils.toError(err), server);
-            } else {
-              if(eventReceiver.listeners("parseError") && eventReceiver.listeners("parseError").length > 0) eventReceiver.emit("parseError", utils.toError(err), server);
-            }
-
-            // If we are a single server connection fire errors correctly
-            if(!server.isSetMember()) {
-              // Fire all callback errors
-              server.__executeAllCallbacksWithError(err);
-              // Emit error
-              server._emitAcrossAllDbInstances(server, eventReceiver, "parseError", server, null, true);
-            }
-            // Short cut
-            return;
-          }
-
-          // Let's record the stats info if it's enabled
-          if(server.recordQueryStats == true && server._state['runtimeStats'] != null
-            && server._state.runtimeStats['queryStats'] instanceof RunningStats) {
-            // Add data point to the running statistics object
-            server._state.runtimeStats.queryStats.push(new Date().getTime() - callbackInfo.info.start);
-          }
-
-          // Dispatch the call
-          server._callHandler(mongoReply.responseTo, mongoReply, null);
-
-          // If we have an error about the server not being master or primary
-          if((mongoReply.responseFlag & (1 << 1)) != 0
-            && mongoReply.documents[0].code
-            && mongoReply.documents[0].code == 13436) {
-              server.close();
-          }
-        });
-      }
-    } catch (err) {
-      // Throw error in next tick
-      processor(function() {
-        throw err;
-      })
-    }
-  });
-
-  // Handle timeout
-  connectionPool.on("timeout", function(err) {
-    // If pool connection is already closed
-    if(server._serverState === 'disconnected' 
-      || server._serverState === 'destroyed') return;
-    // Set server state to disconnected
-    server._serverState = 'disconnected';
-    // If we have a callback return the error
-    if(typeof callback === 'function') {
-      // ensure no callbacks get called twice
-      var internalCallback = callback;
-      callback = null;
-      // Perform callback
-      internalCallback(err, null, server);
-    } else if(server.isSetMember()) {
-      if(server.listeners("timeout") && server.listeners("timeout").length > 0) server.emit("timeout", err, server);
-    } else {
-      if(eventReceiver.listeners("timeout") && eventReceiver.listeners("timeout").length > 0) eventReceiver.emit("timeout", err, server);
-    }
-
-    // If we are a single server connection fire errors correctly
-    if(!server.isSetMember()) {
-      // Fire all callback errors
-      server.__executeAllCallbacksWithError(err);
-      // Emit error
-      server._emitAcrossAllDbInstances(server, eventReceiver, "timeout", err, server, true);
-    }
-
-    // If we have autoConnect enabled let's fire up an attempt to reconnect
-    if(server.isAutoReconnect() 
-      && !server.isSetMember()
-      && (server._serverState != 'destroyed')
-      && !server._reconnectInProgreess) {
-      // Set the number of retries
-      server._reconnect_retries = server.db.numberOfRetries;
-      // Attempt reconnect
-      server._reconnectInProgreess = true;
-      setTimeout(__attemptReconnect(server), server.db.retryMiliSeconds);
-    }    
-  });
-
-  // Handle errors
-  connectionPool.on("error", function(message, connection, error_options) {
-    // If pool connection is already closed
-    if(server._serverState === 'disconnected' 
-      || server._serverState === 'destroyed') return;
-    
-    // Set server state to disconnected
-    server._serverState = 'disconnected';
-    // Error message
-    var error_message = new Error(message && message.err ? message.err : message);
-    // Error message coming from ssl
-    if(error_options && error_options.ssl) error_message.ssl = true;
-
-    // If we have a callback return the error
-    if(typeof callback === 'function') {
-      // ensure no callbacks get called twice
-      var internalCallback = callback;
-      callback = null;
-      // Perform callback
-      internalCallback(error_message, null, server);
-    } else if(server.isSetMember()) {
-      if(server.listeners("error") && server.listeners("error").length > 0) server.emit("error", error_message, server);
-    } else {
-      if(eventReceiver.listeners("error") && eventReceiver.listeners("error").length > 0) eventReceiver.emit("error", error_message, server);
-    }
-
-    // If we are a single server connection fire errors correctly
-    if(!server.isSetMember()) {
-      // Fire all callback errors
-      server.__executeAllCallbacksWithError(error_message);
-      // Emit error
-      server._emitAcrossAllDbInstances(server, eventReceiver, "error", error_message, server, true);
-    }
-
-    // If we have autoConnect enabled let's fire up an attempt to reconnect
-    if(server.isAutoReconnect() 
-      && !server.isSetMember()
-      && (server._serverState != 'destroyed')
-      && !server._reconnectInProgreess) {
-
-      // Set the number of retries
-      server._reconnect_retries = server.db.numberOfRetries;
-      // Attempt reconnect
-      server._reconnectInProgreess = true;
-      setTimeout(__attemptReconnect(server), server.db.retryMiliSeconds);
-    }    
-  });
-
-  // Handle close events
-  connectionPool.on("close", function() {
-    // If pool connection is already closed
-    if(server._serverState === 'disconnected' 
-      || server._serverState === 'destroyed') return;
-    // Set server state to disconnected
-    server._serverState = 'disconnected';
-    // If we have a callback return the error
-    if(typeof callback == 'function') {
-      // ensure no callbacks get called twice
-      var internalCallback = callback;
-      callback = null;
-      // Perform callback
-      internalCallback(new Error("connection closed"), null, server);
-    } else if(server.isSetMember()) {
-      if(server.listeners("close") && server.listeners("close").length > 0) server.emit("close", new Error("connection closed"), server);
-    } else {
-      if(eventReceiver.listeners("close") && eventReceiver.listeners("close").length > 0) eventReceiver.emit("close", new Error("connection closed"), server);
-    }
-
-    // If we are a single server connection fire errors correctly
-    if(!server.isSetMember()) {
-      // Fire all callback errors
-      server.__executeAllCallbacksWithError(new Error("connection closed"));
-      // Emit error
-      server._emitAcrossAllDbInstances(server, eventReceiver, "close", server, null, true);
-    }
-
-    // If we have autoConnect enabled let's fire up an attempt to reconnect
-    if(server.isAutoReconnect() 
-      && !server.isSetMember()
-      && (server._serverState != 'destroyed')
-      && !server._reconnectInProgreess) {
-
-      // Set the number of retries
-      server._reconnect_retries = server.db.numberOfRetries;  
-      // Attempt reconnect
-      server._reconnectInProgreess = true;
-      setTimeout(__attemptReconnect(server), server.db.retryMiliSeconds);
-    }    
-  });
-
-  /**
-   * @ignore
-   */
-  var __attemptReconnect = function(server) {
-    return function() {
-      // Attempt reconnect
-      server.connect(server.db, server.options, function(err, result) {
-        server._reconnect_retries = server._reconnect_retries - 1;
-
-        if(err) {
-          // Retry
-          if(server._reconnect_retries == 0 || server._serverState == 'destroyed') {
-            server._serverState = 'connected';
-            server._reconnectInProgreess = false
-            // Fire all callback errors
-            return server.__executeAllCallbacksWithError(new Error("failed to reconnect to server"));
-          } else {
-            return setTimeout(__attemptReconnect(server), server.db.retryMiliSeconds);
-          }
-        } else {
-          // Set as authenticating (isConnected will be false)
-          server._serverState = 'authenticating';
-          // Apply any auths, we don't try to catch any errors here
-          // as there are nowhere to simply propagate them to
-          self._apply_auths(server.db, function(err, result) {            
-            server._serverState = 'connected';
-            server._reconnectInProgreess = false;
-            server._commandsStore.execute_queries();
-            server._commandsStore.execute_writes();
-          });
-        } 
-      });      
-    }
-  }
-
-  // If we have a parser error we are in an unknown state, close everything and emit
-  // error
-  connectionPool.on("parseError", function(err) {
-    // If pool connection is already closed
-    if(server._serverState === 'disconnected' 
-      || server._serverState === 'destroyed') return;
-    // Set server state to disconnected
-    server._serverState = 'disconnected';
-    // If we have a callback return the error
-    if(typeof callback === 'function') {
-      // ensure no callbacks get called twice
-      var internalCallback = callback;
-      callback = null;
-      // Perform callback
-      internalCallback(utils.toError(err), null, server);
-    } else if(server.isSetMember()) {
-      if(server.listeners("parseError") && server.listeners("parseError").length > 0) server.emit("parseError", utils.toError(err), server);
-    } else {
-      if(eventReceiver.listeners("parseError") && eventReceiver.listeners("parseError").length > 0) eventReceiver.emit("parseError", utils.toError(err), server);
-    }
-
-    // If we are a single server connection fire errors correctly
-    if(!server.isSetMember()) {
-      // Fire all callback errors
-      server.__executeAllCallbacksWithError(utils.toError(err));
-      // Emit error
-      server._emitAcrossAllDbInstances(server, eventReceiver, "parseError", server, null, true);
-    }
-  });
-
-  // Boot up connection poole, pass in a locator of callbacks
-  connectionPool.start();
-}
-
-/**
- * @ignore
- */
-Server.prototype.allRawConnections = function() {
-  return this.connectionPool != null ? this.connectionPool.getAllConnections() : [];
-}
-
-/**
- * Check if a writer can be provided
- * @ignore
- */
-var canCheckoutWriter = function(self, read) {
-  // We cannot write to an arbiter or secondary server
-  if(self.isMasterDoc && self.isMasterDoc['arbiterOnly'] == true) {
-    return new Error("Cannot write to an arbiter");
-  } if(self.isMasterDoc && self.isMasterDoc['secondary'] == true) {
-    return new Error("Cannot write to a secondary");
-  } else if(read == true && self._readPreference == ReadPreference.SECONDARY && self.isMasterDoc && self.isMasterDoc['ismaster'] == true) {
-    return new Error("Cannot read from primary when secondary only specified");
-  } else if(!self.isMasterDoc) {
-    return new Error("Cannot determine state of server");
-  }
-
-  // Return no error
-  return null;
-}
-
-/**
- * @ignore
- */
-Server.prototype.checkoutWriter = function(read) {
-  if(read == true) return this.connectionPool.checkoutConnection();
-  // Check if are allowed to do a checkout (if we try to use an arbiter f.ex)
-  var result = canCheckoutWriter(this, read);
-  // If the result is null check out a writer
-  if(result == null && this.connectionPool != null) {
-    var connection = this.connectionPool.checkoutConnection();
-    // Add server capabilities to the connection
-    if(connection)
-      connection.serverCapabilities = this.serverCapabilities;
-    return connection;
-  } else if(result == null) {
-    return null;
-  } else {
-    return result;
-  }
-}
-
-/**
- * Check if a reader can be provided
- * @ignore
- */
-var canCheckoutReader = function(self) {
-  // We cannot write to an arbiter or secondary server
-  if(self.isMasterDoc && self.isMasterDoc['arbiterOnly'] == true) {
-    return new Error("Cannot write to an arbiter");
-  } else if(self._readPreference != null) {
-    // If the read preference is Primary and the instance is not a master return an error
-    if((self._readPreference == ReadPreference.PRIMARY) && self.isMasterDoc && self.isMasterDoc['ismaster'] != true) {
-      return new Error("Read preference is Server.PRIMARY and server is not master");
-    } else if(self._readPreference == ReadPreference.SECONDARY && self.isMasterDoc && self.isMasterDoc['ismaster'] == true) {
-      return new Error("Cannot read from primary when secondary only specified");
-    }
-  } else if(!self.isMasterDoc) {
-    return new Error("Cannot determine state of server");
-  }
-
-  // Return no error
-  return null;
-}
-
-/**
- * @ignore
- */
-Server.prototype.checkoutReader = function(read) {
-  // Check if are allowed to do a checkout (if we try to use an arbiter f.ex)
-  var result = canCheckoutReader(this);
-  // If the result is null check out a writer
-  if(result == null && this.connectionPool != null) {
-    var connection = this.connectionPool.checkoutConnection();
-    // Add server capabilities to the connection
-    if(connection)
-      connection.serverCapabilities = this.serverCapabilities;
-    return connection;
-  } else if(result == null) {
-    return null;
-  } else {
-    return result;
-  }
-}
-
-/**
- * @ignore
- */
-Server.prototype.enableRecordQueryStats = function(enable) {
-  this.recordQueryStats = enable;
-}
-
-/**
- * Internal statistics object used for calculating average and standard devitation on
- * running queries
- * @ignore
- */
-var RunningStats = function() {
-  var self = this;
-  this.m_n = 0;
-  this.m_oldM = 0.0;
-  this.m_oldS = 0.0;
-  this.m_newM = 0.0;
-  this.m_newS = 0.0;
-
-  // Define getters
-  Object.defineProperty(this, "numDataValues", { enumerable: true
-    , get: function () { return this.m_n; }
-  });
-
-  Object.defineProperty(this, "mean", { enumerable: true
-    , get: function () { return (this.m_n > 0) ? this.m_newM : 0.0; }
-  });
-
-  Object.defineProperty(this, "variance", { enumerable: true
-    , get: function () { return ((this.m_n > 1) ? this.m_newS/(this.m_n - 1) : 0.0); }
-  });
-
-  Object.defineProperty(this, "standardDeviation", { enumerable: true
-    , get: function () { return Math.sqrt(this.variance); }
-  });
-
-  Object.defineProperty(this, "sScore", { enumerable: true
-    , get: function () {
-      var bottom = this.mean + this.standardDeviation;
-      if(bottom == 0) return 0;
-      return ((2 * this.mean * this.standardDeviation)/(bottom));
-    }
-  });
-}
-
-/**
- * @ignore
- */
-RunningStats.prototype.push = function(x) {
-  // Update the number of samples
-  this.m_n = this.m_n + 1;
-  // See Knuth TAOCP vol 2, 3rd edition, page 232
-  if(this.m_n == 1) {
-    this.m_oldM = this.m_newM = x;
-    this.m_oldS = 0.0;
-  } else {
-    this.m_newM = this.m_oldM + (x - this.m_oldM) / this.m_n;
-    this.m_newS = this.m_oldS + (x - this.m_oldM) * (x - this.m_newM);
-
-    // set up for next iteration
-    this.m_oldM = this.m_newM;
-    this.m_oldS = this.m_newS;
-  }
-}
-
-/**
- * @ignore
- */
-Object.defineProperty(Server.prototype, "autoReconnect", { enumerable: true
-  , get: function () {
-      return this.options['auto_reconnect'] == null ? false : this.options['auto_reconnect'];
-    }
-});
-
-/**
- * @ignore
- */
-Object.defineProperty(Server.prototype, "connection", { enumerable: true
-  , get: function () {
-      return this.internalConnection;
-    }
-  , set: function(connection) {
-      this.internalConnection = connection;
-    }
-});
-
-/**
- * @ignore
- */
-Object.defineProperty(Server.prototype, "master", { enumerable: true
-  , get: function () {
-      return this.internalMaster;
-    }
-  , set: function(value) {
-      this.internalMaster = value;
-    }
-});
-
-/**
- * @ignore
- */
-Object.defineProperty(Server.prototype, "primary", { enumerable: true
-  , get: function () {
-      return this;
-    }
-});
-
-/**
- * Getter for query Stats
- * @ignore
- */
-Object.defineProperty(Server.prototype, "queryStats", { enumerable: true
-  , get: function () {
-      return this._state.runtimeStats.queryStats;
-    }
-});
-
-/**
- * @ignore
- */
-Object.defineProperty(Server.prototype, "runtimeStats", { enumerable: true
-  , get: function () {
-      return this._state.runtimeStats;
-    }
-});
-
-/**
- * Get Read Preference method
- * @ignore
- */
-Object.defineProperty(Server.prototype, "readPreference", { enumerable: true
-  , get: function () {
-      if(this._readPreference == null && this.readSecondary) {
-        return Server.READ_SECONDARY;
-      } else if(this._readPreference == null && !this.readSecondary) {
-        return Server.READ_PRIMARY;
-      } else {
-        return this._readPreference;
-      }
-    }
-});
-
-/**
- * @ignore
- */
-exports.Server = Server;

http://git-wip-us.apache.org/repos/asf/incubator-apex-malhar/blob/e1a45507/web/demos/package/node_modules/mongodb/lib/mongodb/connection/server_capabilities.js
----------------------------------------------------------------------
diff --git a/web/demos/package/node_modules/mongodb/lib/mongodb/connection/server_capabilities.js b/web/demos/package/node_modules/mongodb/lib/mongodb/connection/server_capabilities.js
deleted file mode 100644
index 88bdf9f..0000000
--- a/web/demos/package/node_modules/mongodb/lib/mongodb/connection/server_capabilities.js
+++ /dev/null
@@ -1,48 +0,0 @@
-var ServerCapabilities = function(isMasterResult) {  
-  // Capabilities
-  var aggregationCursor = false;
-  var writeCommands = false;
-  var textSearch = false;
-  var authCommands = false;
-  var maxNumberOfDocsInBatch = 1000;
-
-  if(isMasterResult.minWireVersion >= 0) {
-  	textSearch = true;
-  }
-
-  if(isMasterResult.maxWireVersion >= 1) {
-  	aggregationCursor = true;
-    authCommands = true;
-  }
-
-  if(isMasterResult.maxWireVersion >= 2) {
-    writeCommands = true;
-  }
-
-  // If no min or max wire version set to 0
-  if(isMasterResult.minWireVersion == null) {
-    isMasterResult.minWireVersion = 0;
-  }
-
-  if(isMasterResult.maxWireVersion == null) {
-    isMasterResult.maxWireVersion = 0;
-  }
-
-  // Map up read only parameters
-  setup_get_property(this, "hasAggregationCursor", aggregationCursor);
-  setup_get_property(this, "hasWriteCommands", writeCommands);
-  setup_get_property(this, "hasTextSearch", textSearch);
-  setup_get_property(this, "hasAuthCommands", authCommands);
-  setup_get_property(this, "minWireVersion", isMasterResult.minWireVersion);
-  setup_get_property(this, "maxWireVersion", isMasterResult.maxWireVersion);
-  setup_get_property(this, "maxNumberOfDocsInBatch", maxNumberOfDocsInBatch);
-}
-
-var setup_get_property = function(object, name, value) {
-  Object.defineProperty(object, name, {
-      enumerable: true
-    , get: function () { return value; }
-  });  
-}
-
-exports.ServerCapabilities = ServerCapabilities;
\ No newline at end of file



Mime
View raw message