Ejemplo n.º 1
0
 setTimeout(function() {
   promise.emit('success');
 }, 600);
Ejemplo n.º 2
0
var events = require('events');
var eventEmitter = new events.EventEmitter();

var ringBell = function ringBell()
{
  console.log('ring ring ring');
}
eventEmitter.on('doorOpen', ringBell);

eventEmitter.emit('doorOpen');
Ejemplo n.º 3
0
function SecurePair(credentials, isServer, requestCert, rejectUnauthorized,
                    options) {
  if (!(this instanceof SecurePair)) {
    return new SecurePair(credentials,
                          isServer,
                          requestCert,
                          rejectUnauthorized,
                          options);
  }

  var self = this;

  options || (options = {});

  events.EventEmitter.call(this);

  this._secureEstablished = false;
  this._isServer = isServer ? true : false;
  this._encWriteState = true;
  this._clearWriteState = true;
  this._doneFlag = false;

  if (!credentials) {
    this.credentials = crypto.createCredentials();
  } else {
    this.credentials = credentials;
  }

  if (!this._isServer) {
    // For clients, we will always have either a given ca list or be using
    // default one
    requestCert = true;
  }

  this._rejectUnauthorized = rejectUnauthorized ? true : false;
  this._requestCert = requestCert ? true : false;

  this.ssl = new Connection(this.credentials.context,
      this._isServer ? true : false,
      this._isServer ? this._requestCert : options.servername,
      this._rejectUnauthorized);

  if (this._isServer) {
    this.ssl.onhandshakestart = onhandshakestart.bind(this);
    this.ssl.onhandshakedone = onhandshakedone.bind(this);
    this.ssl.handshakes = 0;
    this.ssl.timer = null;
  }

  if (process.features.tls_sni) {
    if (this._isServer && options.SNICallback) {
      this.ssl.setSNICallback(options.SNICallback);
    }
    this.servername = null;
  }

  if (process.features.tls_npn && options.NPNProtocols) {
    this.ssl.setNPNProtocols(options.NPNProtocols);
    this.npnProtocol = null;
  }

  /* Acts as a r/w stream to the cleartext side of the stream. */
  this.cleartext = new CleartextStream(this);

  /* Acts as a r/w stream to the encrypted side of the stream. */
  this.encrypted = new EncryptedStream(this);

  process.nextTick(function() {
    /* The Connection may be destroyed by an abort call */
    if (self.ssl) {
      self.ssl.start();
    }
    self.cycle();
  });
}
Ejemplo n.º 4
0
function WebSocketClient(config) {
    // Superclass Constructor
    EventEmitter.call(this);

    // TODO: Implement extensions

    this.config = {
        // 1MiB max frame size.
        maxReceivedFrameSize: 0x100000,

        // 8MiB max message size, only applicable if
        // assembleFragments is true
        maxReceivedMessageSize: 0x800000,

        // Outgoing messages larger than fragmentationThreshold will be
        // split into multiple fragments.
        fragmentOutgoingMessages: true,

        // Outgoing frames are fragmented if they exceed this threshold.
        // Default is 16KiB
        fragmentationThreshold: 0x4000,

        // Which version of the protocol to use for this session.  This
        // option will be removed once the protocol is finalized by the IETF
        // It is only available to ease the transition through the
        // intermediate draft protocol versions.
        // At present, it only affects the name of the Origin header.
        webSocketVersion: 13,

        // If true, fragmented messages will be automatically assembled
        // and the full message will be emitted via a 'message' event.
        // If false, each frame will be emitted via a 'frame' event and
        // the application will be responsible for aggregating multiple
        // fragmented frames.  Single-frame messages will emit a 'message'
        // event in addition to the 'frame' event.
        // Most users will want to leave this set to 'true'
        assembleFragments: true,

        // The Nagle Algorithm makes more efficient use of network resources
        // by introducing a small delay before sending small packets so that
        // multiple messages can be batched together before going onto the
        // wire.  This however comes at the cost of latency, so the default
        // is to disable it.  If you don't need low latency and are streaming
        // lots of small messages, you can change this to 'false'
        disableNagleAlgorithm: true,

        // The number of milliseconds to wait after sending a close frame
        // for an acknowledgement to come back before giving up and just
        // closing the socket.
        closeTimeout: 5000,

        // Options to pass to https.connect if connecting via TLS
        tlsOptions: {}
    };

    if (config) {
        var tlsOptions;
        if (config.tlsOptions) {
          tlsOptions = config.tlsOptions;
          delete config.tlsOptions;
        }
        else {
          tlsOptions = {};
        }
        extend(this.config, config);
        extend(this.config.tlsOptions, tlsOptions);
    }

    this._req = null;
    
    switch (this.config.webSocketVersion) {
        case 8:
        case 13:
            break;
        default:
            throw new Error('Requested webSocketVersion is not supported. Allowed values are 8 and 13.');
    }
}
Ejemplo n.º 5
0
/**
 * Recommendation model events
 */

'use strict';

var EventEmitter = require('events').EventEmitter;
var Recommendation = require('./recommendation.model');
var RecommendationEvents = new EventEmitter();

// Set max event listeners (0 == unlimited)
RecommendationEvents.setMaxListeners(0);

// Model events
var events = {
  'save': 'save',
  'remove': 'remove'
};

// Register the event emitter to the model events
for (var e in events) {
  var event = events[e];
  Recommendation.schema.post(e, emitEvent(event));
}

function emitEvent(event) {
  return function(doc) {
    RecommendationEvents.emit(event + ':' + doc._id, doc);
    RecommendationEvents.emit(event, doc);
  }
}
Ejemplo n.º 6
0
RoleEnvironment.listeners = function (event) {
  validateNodeVersion();

  return eventEmitter.listeners(event);
};
Ejemplo n.º 7
0
Archivo: index.js Proyecto: NHQ/film
	function snapShot(){
    	var reflection = mirror.getContext('2d');
    	reflection.drawImage(video, 0, 0);
	    var p = reflection.getImageData(0, 0, mirror.width, mirror.height)
        app.emit('snapshot', p)
	}
Ejemplo n.º 8
0
						.drop(function(err){
							promise.emit("success",err);
						});
Ejemplo n.º 9
0
				.insert({a:2,nested:{deeply:{under:{the:{sea:'tresure'}}}}}, function(err,doc){
					promiseResult.insertResult = {err: err, doc: doc};
					promise.emit("success", promiseResult);
				})
Ejemplo n.º 10
0
				.remove({_id: testContext.objID}, function(err, doc){
					promise.emit("success", err, doc);
				})
Ejemplo n.º 11
0
				.find({'nested.deeply.under.the.sea': "found"}, function(err, cursor){
					promise.emit("success", err, cursor);
				})
Ejemplo n.º 12
0
			mongodm.withDatabase("testdb",function(err,dbfacade){
						promise.emit("success",err,dbfacade);
					})
Ejemplo n.º 13
0
				.find({}, function(err, results){
					promise.emit("success", err, results);
				})
Ejemplo n.º 14
0
				.count({}, function(err,c){
					promise.emit("success", err, c);
				})
Ejemplo n.º 15
0
RoleEnvironment.once = function (event, listener) {
  validateNodeVersion();

  return eventEmitter.once(event, listener);
};
Ejemplo n.º 16
0
				.update({_id: testContext.objID}, {$set: obj}, function(err,doc){
					promise.emit("success", err, doc);
				})
Ejemplo n.º 17
0
RoleEnvironment.setMaxListeners = function (n) {
  validateNodeVersion();

  return eventEmitter.setMaxListeners(n);
};
Ejemplo n.º 18
0
console.log("File Reading Ended.");

fs.readFile('input.txt', function(err, data){
	if(err) return console.error(err);
	console.log(data.toString());
});


console.log("File Reading Ended.")

// import events module

var events = require('events');
// create an eventEmitter object

var eventEmitter = new events.EventEmitter();

// create an event handler
var connectHandler = function connected(){
	console.log('connnection successful');

	// fire the data_received event
	eventEmitter.emit('data_received');
}

// bind the connection event with handler
eventEmitter.on('connection', connectHandler);

// bind the data_received event with anonymous function
eventEmitter.on('data_received', function(){
	console.log('data received successfully');
Ejemplo n.º 19
0
RoleEnvironment.addListener = function (event, listener) {
  validateNodeVersion();

  return eventEmitter.addListener(event, listener);
};
Ejemplo n.º 20
0
var connectHandler = function connected(){
	console.log('connnection successful');

	// fire the data_received event
	eventEmitter.emit('data_received');
}
Ejemplo n.º 21
0
Archivo: index.js Proyecto: NHQ/film
module.exports = function(stream, video, mirror, film){
	
	
	video.src = window.URL.createObjectURL(stream)
    
	var app = new emitter();
	app.snapShot = snapShot;
	app.record = record;
	app.expose = expose;

    var recording = false;
	var frames = [];
	
	return app 
	
	function snapShot(){
    	var reflection = mirror.getContext('2d');
    	reflection.drawImage(video, 0, 0);
	    var p = reflection.getImageData(0, 0, mirror.width, mirror.height)
        app.emit('snapshot', p)
	}

    function record(){
        if(recording){
            app.emit('record', frames)
            recording = false
        }
        recording = true;
        frames = [];
        var reflection = mirror.getContext('2d');
        window.requestAnimationFrame(rec)		
    	
        function rec(time){
        	window.requestAnimationFrame(rec)
        	reflection.drawImage(video, 0, 0)
    	    var frame = reflection.getImageData(0, 0, mirror.width, mirror.height)
    	    frames.push(frame)
    	}
    	
    }
    
    function expose(params){
        
        var defaults = {
            shutterSpeed: 1000 / 24,
            invert: false,
            filmSpeed: {
                r: 5,
                g: 5,
                b: 5
            },
            r: 0,
            g: 0,
            b: 0,
            a: 255
        }
        
        if(!params){
            params = defaults
        }
            	
        else {
            for (var attrname in defaults) {
                if(typeof params.filmSpeed == 'number'){
                    var n = params.filmSpeed;
                    params.filmSpeed = {
                        r: n,
                        g: n,
                        b: n
                    }
                }
                if(!params[attrname] && params[attrname] != 0) params[attrname] = defaults[attrname]
            }
        }
        var d = 0;
    	var reflection = mirror.getContext('2d')
    	var render = film.getContext('2d')

    	var pos = render.getImageData(0,0,film.width, film.height)
        
        if(params.blob){
            var positive = params.blob           
        }
        else{
            var positive = new Uint8ClampedArray(pos.data.length)

        	for(var m = 0; m < mirror.width * mirror.height; m++){
        	    var index = m * 4;
        	    positive[index] = params.r;
        	    positive[index + 1] = params.g;
                positive[index + 2] = params.b;
                positive[index + 3] = params.a
        	}   
        }
        
    	window.requestAnimationFrame(function(time){
    	    d = time + params.shutterSpeed
    	    window.requestAnimationFrame(f)
    	})
    	
        function f(time){
        	if(time > d) {
        	    var p = reflection.getImageData(0,0,mirror.width, mirror.height)
                p.data.set(positive)
                app.emit('expose', p)
        	    window.cancelAnimationFrame(f)
    	        return
    	    }
        	window.requestAnimationFrame(f)
        	reflection.drawImage(video, 0, 0)
        	var negative = reflection.getImageData(0,0,mirror.width,mirror.height);  
                for(n=0; n<negative.width*negative.height; n++) {  
                    var index = n*4;   
                    positive[index+0] =  vert(positive[index+0], (negative.data[index] / params.filmSpeed.r));
                    positive[index+1] =  vert(positive[index+1], (negative.data[index+1] / params.filmSpeed.g));
                    positive[index+2] =  vert(positive[index+2], (negative.data[index+2] / params.filmSpeed.b));
                    positive[index + 3] = params.a;
                }
    //        pos.data.set(positive)
      //      render.putImageData(pos, 0, 0)
        }
        
        function vert(a, b){
            if(params.invert){
                return a - b
            }
            else return a + b
        }
    }
    
    function animate(time){
    	window.requestAnimationFrame(animate)
    	render = mirror.getContext('2d')
    	render.drawImage(video, 0, 0)	
	}    
	
		
}
Ejemplo n.º 22
0
function Core() {
	EventEmitter.apply(this, arguments)

	E2.core = this
	
	E2.dt = this.datatypes = {
		FLOAT: { id: 0, name: 'Float' },
		SHADER: { id: 1, name: 'Shader' },
		TEXTURE: { id: 2, name: 'Texture' },
		COLOR: { id: 3, name: 'Color' },
		MATRIX: { id: 4, name: 'Matrix' },
		VECTOR: { id: 5, name: 'Vector' },
		CAMERA: { id: 6, name: 'Camera' },
		BOOL: { id: 7, name: 'Boolean' },
		ANY: { id: 8, name: 'Arbitrary' },
		MESH: { id: 9, name: 'Mesh' },
		AUDIO: { id: 10, name: 'Audio' },
		SCENE: { id: 11, name: 'Scene' },
		MATERIAL: { id: 12, name: 'Material' },
		LIGHT: { id: 13, name: 'Light' },
		DELEGATE: { id: 14, name: 'Delegate' },
		TEXT: { id: 15, name: 'Text' },
		VIDEO: { id: 16, name: 'Video' },
		ARRAY: { id: 17, name: 'Typed Array' },
		OBJECT: { id: 18, name: 'Object' },

		GEOMETRY: { id: 19, name: 'Geometry' },
		QUATERNION: { id: 20, name: 'Quaternion' },
		OBJECT3D: { id: 21, name: 'Object3D' },
		
		VECTOR4: { id: 22, name: 'Vector 4' },

		ENVIRONMENTSETTINGS: { id: 23, name: 'Environment Settings' },

		CUBETEXTURE: { id: 24, name: 'CubeTexture' },
	}

	this.renderer = { // compat for old plugins
		matrix_identity: new THREE.Matrix4().identity(),
		vector_origin: new THREE.Vector3(),
		material_default: new THREE.MeshBasicMaterial(),
		color_white: new THREE.Color(0xffffff),
		color_black: new THREE.Color(0x000000),
		blend_mode: {
			NORMAL: 1
		}
	}

	this._listeners = {};
	
	this.runtimeEvents = new EventEmitter()

	this.assetLoader = new AssetLoader()

	// relay events from AssetLoader
	this.assetLoader.on('progress', function(pct) {
		if (pct % 10 === 0)
			console.log('core progress', pct)
		E2.core.emit('progress', pct)
	})

	this.webVRAdapter = new VizorWebVRAdapter()

	this.active_graph_dirty = true;

	this.active_graph = this.root_graph = null
	this.graphs = []
	
	this.abs_t = 0.0;
	this.delta_t = 0.0;
	this.graph_uid = this.get_uid()
	this.uidCounter = 0

	this.pluginManager = new PluginManager(this, '/plugins');

	this.pluginManager.on('ready', function() {
		this.onPluginsLoaded()
	}.bind(this))

	this.aux_scripts = {};
	this.aux_styles = {};
	this.resolve_dt = []; // Table for easy reverse lookup of dt reference by id.
	this.audioContext = null;
	
	for(var i in this.datatypes) {
		var dt = this.datatypes[i];
		
		this.resolve_dt[dt.id] = dt;
	}
	
	// HTML5 audio context initialisation
	if(window.AudioContext)
		this.audioContext = new AudioContext();
	else if(window.webkitAudioContext)
		this.audioContext = new webkitAudioContext();
	else
		msg('NOTE: This host has no AudioContext support.');
}
Ejemplo n.º 23
0
var Logger = exports.Logger = function (options) {
  events.EventEmitter.call(this);
  options = options || {};

  var self = this,
      handleExceptions = false;

  //
  // Set Levels and default logging level
  //
  this.padLevels = options.padLevels || false;
  this.setLevels(options.levels);
  if (options.colors) {
    config.addColors(options.colors);
  }

  //
  // Hoist other options onto this instance.
  //
  this.level       = options.level || 'info';
  this.emitErrs    = options.emitErrs || false;
  this.stripColors = options.stripColors || false;
  this.exitOnError = typeof options.exitOnError !== 'undefined'
    ? options.exitOnError
    : true;

  //
  // Setup other intelligent default settings.
  //
  this.transports        = {};
  this.rewriters         = [];
  this.exceptionHandlers = {};
  this.profilers         = {};
  this._names            = [];
  this._hnames           = [];

  if (options.transports) {
    options.transports.forEach(function (transport) {
      self.add(transport, null, true);

      if (transport.handleExceptions) {
        handleExceptions = true;
      }
    });
  }

  if (options.rewriters) {
    options.rewriters.forEach(function (rewriter) {
      self.addRewriter(rewriter);
    });
  }

  if (options.exceptionHandlers) {
    handleExceptions = true;
    options.exceptionHandlers.forEach(function (handler) {
      self._hnames.push(handler.name);
      self.exceptionHandlers[handler.name] = handler;
    });
  }

  if (options.handleExceptions || handleExceptions) {
    this.handleExceptions();
  }
};
Ejemplo n.º 24
0
(function () {
  "use strict";

  var os = require('os');
  var dslib = require('./decisionstorage.js');
  var JSV = require('JSV').JSV;
  var fs = require('fs');
  var xml2js = require('xml2js');
  var schema = require('./schema.json');
  var env = JSV.createEnvironment("json-schema-draft-03");
  var xmlParser = new xml2js.Parser(xml2js.defaults["0.2"]);
  var logger = require('webinos-utilities').webinosLogging(__filename) || console;

  var decisionStorage = null;
  var promptTimeout = 30000;
  var pmrlib = require('./rootPm.js');

  var events = require('events');
  var eventEmitter = new events.EventEmitter();
  
  var policyManager = function(policyFilename) {
    //Root policy file location
    this.policyFile = policyFilename;

    this.pmr;
    this.genericURI = {};
    this.promptCallbacks = {};

    var self = this;

    try {
      var PzpAPI = require(require('path').join(require.main.paths[0], '..', 'lib', 'pzp_sessionHandling.js'));

      var getOwnerId = function() {
        var owner = PzpAPI.getInstance().getPzhId();
        if (!owner) {
          owner = PzpAPI.getDeviceName();
        }
        return owner;
      }
      this.genericURI = {
        'http://webinos.org/subject/id/PZ-Owner': getOwnerId(),
        'http://webinos.org/subject/id/known': PzpAPI.getInstance().getTrustedList('pzh')
      }

      var updateEnrollmentStatus = function () {
        self.genericURI['http://webinos.org/subject/id/PZ-Owner'] = getOwnerId();
        self.genericURI['http://webinos.org/subject/id/known'] = PzpAPI.getInstance().getTrustedList('pzh');
        self.pmr.reloadPolicy(self.genericURI);
      }

      var updateFriends = function () {
        self.genericURI['http://webinos.org/subject/id/known'] = PzpAPI.getInstance().getTrustedList('pzh');
        self.pmr.reloadPolicy(self.genericURI);
      }
    
      eventEmitter.on('updateEnrollmentStatus', updateEnrollmentStatus);
      eventEmitter.on('updateFriends', updateFriends);
    } catch(e) {
        logger.log("Cannot get info about PZ-Owner and Known PZHs");
    }

    checkPolicyFileExists(this.policyFile, function(err) {
      if (err) {
        logger.log("Error reading/creating policy file: " + err);
      } else {
// TODO: at the moment validation of root policy file fails
//        self.isAWellFormedPolicyFile(policyFile
//          , function () {
            self.pmr = new pmrlib.rootPm(self.policyFile, self.genericURI);
            //Loads decision storage module
            decisionStorage = new dslib.decisionStorage(self.policyFile);
            logger.log("Policy file loaded");
//          }
//          , function () {
//            logger.log("Policy file is not valid");
//          }
//        );
      }
    });
  };

  /**
   * This function checks that a policy file exists at the given path.  If it
   * does not exist, a copy of the default root policy is place in this location.
   */
  function checkPolicyFileExists(policyFile, cb) {
    var path = require('path');
    var existsSync = fs.existsSync || path.existsSync;
    if (!existsSync(policyFile)) {
      logger.log("No policy file found, copying default policy instead");
      var defaultPolicyFile = path.resolve(path.join( __dirname , "..", "defaultRootPolicy.xml" ));
      if (!existsSync(defaultPolicyFile)) {
        return cb("No policy file exists, and no default policy exists either.");
      }
      copy(defaultPolicyFile, policyFile, cb);
    } else {
      return cb();
    }
  }

  /**
   * Copy file 'from' to 'to', returns by calling 'cb' exactly once, either
   * with no arguments or with an error.
   */
  function copy(from, to, cb) {
    var called = false;
    var readStream = fs.createReadStream(from);
    var writeStream = fs.createWriteStream(to);

    readStream.on('error', function(err) { once(err) });
    writeStream.on('error', function(err) { once(err) });
    writeStream.on('close', function() { once() });

    readStream.pipe(writeStream);

    function once(err) {
      if (!called) {
        if (typeof err === "undefined") {
          cb();
        } else {
          cb(err);
        }
        called = true;
      }
    }
  }

  policyManager.prototype.initialisePrompts = function(notificationManager) {
    var _self = this;
    this.notificationManager = notificationManager;

    // Register to receive notifications of prompt responses.
    this.notificationManager.on(this.notificationManager.notifyType.permissionResponse, promptResponse.bind(_self));
  }

  policyManager.prototype.getPolicyFilePath = function() {
    return this.policyFile;
  }
  policyManager.prototype.testRequest = function(request, cb){
    var result = {};
    if (!this.pmr) {
      logger.log("Invalid policy file: request denied");
      result["effect"] = false;
      cb(result);
      return;
    }
    var  path = {};
    var res = this.pmr.testRequest(request, path);
    result = path;
    result['effect'] = res;
    cb(result);
  }
  policyManager.prototype.enforceRequest = function(request, sessionId, noprompt, cb) {
    if (!this.pmr) {
      logger.log("Invalid policy file: request denied")
      cb(false);
      return;
    }

    var res = this.pmr.enforceRequest(request);

    if(res > 1 && res < 5 && decisionStorage && noprompt == false) {
      var storedDecision = decisionStorage.checkDecision(request, sessionId);
      if(storedDecision == 0 || storedDecision == 1) {
        cb(storedDecision);
      } else {
        this.notifyPermissionRequest(res, request, sessionId, cb);
      }
    } else {
      //logger.log("Policy Manager enforce request: "+JSON.stringify(request)+" - result is "+res);
      cb(res);
    }
  };

  policyManager.prototype.reloadPolicy = function () {
    //TODO: at the moment validation of root policy file fails
//    self.isAWellFormedPolicyFile(policyFile
//      , function () {
        this.pmr.reloadPolicy(self.genericURI);
//      }
//      , function () {
//        logger.log("Policy file is not valid");
//      }
//    );
  };

  policyManager.prototype.isAWellFormedPolicyFile = function (policyFilename, successCB, errorCB) {
    var data = fs.readFileSync(policyFilename);

    xmlParser.parseString(data, function (err, jsonData) {
      if (!err) {
        (env.validate(jsonData, schema).errors.length === 0) ? successCB() : errorCB();
      } else {
        errorCB();
      }
    });
  }

  policyManager.prototype.notifyPermissionRequest = function(promptType, request, sessionId, cb) {
    var _self = this;

    // Add permission request to notifications list.
    var notification = this.notificationManager.addNotification(this.notificationManager.notifyType.permissionRequest, { promptType: promptType, request: request, sessionId: sessionId });

    // Store the callback with the notification id.
    this.promptCallbacks[notification.id] = {
      callback: cb,
      request: request,
      sessionId: sessionId
    };

    // Create a timeout - deny permission after 20 secs.
    setTimeout(function() {
      // Prompt has timed out - check that the user didn't respond in the meantime.
      if (_self.promptCallbacks.hasOwnProperty(notification.id)) {
        // Callback still exists => no user response received.
        var cb = _self.promptCallbacks[notification.id].callback;
        delete _self.promptCallbacks[notification.id];

        // Callback with 'denied'
        cb(1);
      }
    }, promptTimeout);
  }

	var storePermissionResponse = function(request, sessionId, reply) {
    var permit = false;
    var storeSession = false;
    var storePermanent = false;

    // Determine the policy decision and storage required based on the response.
    switch (reply) {
      case 0:
        // Deny always.
        permit = false;
        storePermanent = true;
        break;
      case 1:
        // Deny this session.
        permit = false;
        storeSession = true;
        break;
      case 2:
        // Deny this time.
        permit = false;
        break;
      case 3:
        // Allow this time.
        permit = true;
        break;
      case 4:
        // Allow this session.
        permit = true;
        storeSession = true;
        break;
      case 5:
        // Allow always.
        permit = true;
        storePermanent = true;
        break;
      default:
        permit = false;
        break;
    }
    if (storeSession || storePermanent) {
      decisionStorage.addDecision(request, sessionId, permit ? 0 : 1, storePermanent ? 0 : 1);
    }

    return permit;
  }

  var promptResponse = function(notify) {
    // Response from prompt received from user.
    var token = notify.data.responseTo;
    var reply = notify.data.response;

    // Get the original request notification.
    var requestNotification = this.notificationManager.getNotification(notify.data.responseTo);

    if (typeof requestNotification !== "undefined") {
      var request = requestNotification.data.request;
      var sessionId = requestNotification.data.sessionId;

      // Store the permission request response.
      var permit = storePermissionResponse(request, sessionId, reply);

      // Check if there's an outstanding callback (it may have timed out).
      if (this.promptCallbacks.hasOwnProperty(token)) {
        // Prompt still valid - get the details.
        var cb = this.promptCallbacks[token].callback;
        delete this.promptCallbacks[token];

        // Callback requires PERMIT == 0 and DENY == 1
        cb(permit === true ? 0 : 1);
      }
    } else {
      logger.error("Request notification missing for response " + token);
    }
  };

  exports.policyManager = policyManager;
  exports.updatePolicyVersion = pmrlib.updatePolicyVersion;
  exports.policyEvent = eventEmitter;

}());
Ejemplo n.º 25
0
 return function(doc) {
   RecommendationEvents.emit(event + ':' + doc._id, doc);
   RecommendationEvents.emit(event, doc);
 }
Ejemplo n.º 26
0
  var policyManager = function(policyFilename) {
    //Root policy file location
    this.policyFile = policyFilename;

    this.pmr;
    this.genericURI = {};
    this.promptCallbacks = {};

    var self = this;

    try {
      var PzpAPI = require(require('path').join(require.main.paths[0], '..', 'lib', 'pzp_sessionHandling.js'));

      var getOwnerId = function() {
        var owner = PzpAPI.getInstance().getPzhId();
        if (!owner) {
          owner = PzpAPI.getDeviceName();
        }
        return owner;
      }
      this.genericURI = {
        'http://webinos.org/subject/id/PZ-Owner': getOwnerId(),
        'http://webinos.org/subject/id/known': PzpAPI.getInstance().getTrustedList('pzh')
      }

      var updateEnrollmentStatus = function () {
        self.genericURI['http://webinos.org/subject/id/PZ-Owner'] = getOwnerId();
        self.genericURI['http://webinos.org/subject/id/known'] = PzpAPI.getInstance().getTrustedList('pzh');
        self.pmr.reloadPolicy(self.genericURI);
      }

      var updateFriends = function () {
        self.genericURI['http://webinos.org/subject/id/known'] = PzpAPI.getInstance().getTrustedList('pzh');
        self.pmr.reloadPolicy(self.genericURI);
      }
    
      eventEmitter.on('updateEnrollmentStatus', updateEnrollmentStatus);
      eventEmitter.on('updateFriends', updateFriends);
    } catch(e) {
        logger.log("Cannot get info about PZ-Owner and Known PZHs");
    }

    checkPolicyFileExists(this.policyFile, function(err) {
      if (err) {
        logger.log("Error reading/creating policy file: " + err);
      } else {
// TODO: at the moment validation of root policy file fails
//        self.isAWellFormedPolicyFile(policyFile
//          , function () {
            self.pmr = new pmrlib.rootPm(self.policyFile, self.genericURI);
            //Loads decision storage module
            decisionStorage = new dslib.decisionStorage(self.policyFile);
            logger.log("Policy file loaded");
//          }
//          , function () {
//            logger.log("Policy file is not valid");
//          }
//        );
      }
    });
  };
Ejemplo n.º 27
0
var EventEmitter = require('events').EventEmitter;

var emitter = new EventEmitter();
emitter.on('some event', function(msg) {
	console.log('I got some event: %j', msg);
});

emitter.emit('some event', 'hello');
Ejemplo n.º 28
0
var Server = function(options) {
  options = options || {};

  // Add event listener
  EventEmitter.call(this);

  // Server instance id
  this.id = id++;

  // Internal state
  this.s = {
    // Options
    options: options,
    // Logger
    logger: Logger('Server', options),
    // Factory overrides
    Cursor: options.cursorFactory || BasicCursor,
    // BSON instance
    bson: options.bson || new BSON([BSON.Binary, BSON.Code, BSON.DBRef, BSON.Decimal128,
      BSON.Double, BSON.Int32, BSON.Long, BSON.Map, BSON.MaxKey, BSON.MinKey,
      BSON.ObjectId, BSON.BSONRegExp, BSON.Symbol, BSON.Timestamp]),
    // Pool
    pool: null,
    // Disconnect handler
    disconnectHandler: options.disconnectHandler,
    // Monitor thread (keeps the connection alive)
    monitoring: typeof options.monitoring == 'boolean' ? options.monitoring : true,
    // Is the server in a topology
    inTopology: typeof options.inTopology == 'boolean' ? options.inTopology : false,
    // Monitoring timeout
    monitoringInterval: typeof options.monitoringInterval == 'number'
      ? options.monitoringInterval
      : 5000,
    // Topology id
    topologyId: -1
  }

  // Curent ismaster
  this.ismaster = null;
  // Current ping time
  this.lastIsMasterMS = -1;
  // The monitoringProcessId
  this.monitoringProcessId = null;
  // Initial connection
  this.initalConnect = true;
  // Wire protocol handler, default to oldest known protocol handler
  // this gets changed when the first ismaster is called.
  this.wireProtocolHandler = new PreTwoSixWireProtocolSupport();
  // Default type
  this._type = 'server';
  // Set the client info
  this.clientInfo = createClientInfo(options);

  // Max Stalleness values
  // last time we updated the ismaster state
  this.lastUpdateTime = 0;
  // Last write time
  this.lastWriteDate = 0;
  // Stalleness
  this.staleness = 0;
}
Ejemplo n.º 29
0
 "watchCallback": function(event, file) {
   console.log('Got change in %s', file);
   stopWatchingFiles();
   master.reload();
 }
Ejemplo n.º 30
0
 topic: function() {
   
   storage = app.storages.redis;
   
   var out = {};
   var promise = new EventEmitter();
   var multi = storage.multi({parallel: true});
   
   multi.set('cache1', 1);
   multi.set('cache2', 2);
   multi.set('cache3', 3);
   multi.set('cache4', 4);
   
   multi.exec(function(err, results) {
     if (err) {
       
       // This means the values were set
       throw err;
       
     } else {
       
       // Set the cache
       app.invalidateCacheInterval({
         key: 'my_cache_key',
         cacheID: ['cache1', 'cache2', 'cache3', 'cache4'],
         storage: storage,
         interval: 100
       });
       
       // Invalidate the cache
       app.invalidateCacheKey('my_cache_key');
       
       setTimeout(function() {
         
         // Ok, cache should have been invalidated by now
         
         multi.get('cache1');
         multi.get('cache2');
         multi.get('cache3');
         multi.get('cache4');
         
         multi.exec(function(err, results) {
           
           if (err) {
             
             // This means no errors retrieving values
             throw err;
             
           } else {
             
             // Store first check
             out.firstCheck = results;
             
             // Set the values again
             
             multi.set('cache1', 1);
             multi.set('cache2', 2);
             multi.set('cache3', 3);
             multi.set('cache4', 4);
             
             multi.exec(function(err, results) {
               
               if (err) {
                 
                 // There were errors saving the values
                 throw err;
                 
               } else {
                 
                 // Ok,  values set again, invalidate...
                 app.invalidateCacheKey('my_cache_key');
                 
                 // ... Immediately clear interval ...
                 app.clearCacheKeyInterval('my_cache_key');
                 
                 // Sleep for 200 ms again
                 
                 setTimeout(function() {
                   
                   // Get values again
                   
                   multi.get('cache1');
                   multi.get('cache2');
                   multi.get('cache3');
                   multi.get('cache4');
                   
                   multi.exec(function(err, results) {
                     
                     if (err) {
                       
                       // There were errors retrieving values
                       throw err;
                       
                     } else {
                       
                       // Set second check
                       out.secondCheck = results;
                       
                       // Test cache purge
                       
                       multi.set('cache1', 1);
                       multi.set('cache2', 2);
                       multi.set('cache3', 3);
                       multi.set('cache4', 4);
                       
                       multi.exec(function(err, results) {
                         
                         if (err) {
                           
                           // There were errors retrieving values
                           throw err;
                           
                         } else {
                           
                           app.purgeCacheKey('my_cache_key', function() {
                             
                             multi.get('cache1');
                             multi.get('cache2');
                             multi.get('cache3');
                             multi.get('cache4');
                             
                             multi.exec(function(err, results) {
                               
                               if (err) {
                                 
                                 // Error retrieving results
                                 throw err;
                                 
                               } else {
                                 
                                 // Set third check
                                 out.thirdCheck = results;
                                 
                                 // Exit test case
                                 promise.emit('success', out);
                                 
                               }
                               
                             });
                             
                           });
                           
                         }
                         
                       });
                       
                     }
                     
                   });
                   
                 }, 200);
                 
               }
               
             });
             
           }
           
         });
         
       }, 200);
       
     }
   });
   
   return promise;
   
 },