Example #1
0
    it('should access the component with a name by app.components.name after loaded', function() {
      var key1 = 'key1', comp1 = {content: 'some thing in comp1'};
      var comp2 = {name: 'key2', content: 'some thing in comp2'};
      var key3 = 'key3';
      var comp3 = function() {
        return {content: 'some thing in comp3', name: key3};
      };

      app.init({base: mockBase});
      app.load(key1, comp1);
      app.load(comp2);
      app.load(comp3);

      app.components.key1.should.eql(comp1);
      app.components.key2.should.eql(comp2);
      app.components.key3.should.eql(comp3());
    });
  testAddCustomAssertion : function(test) {
    var client = this.client;
    client.on('selenium:session_create', function(sessionId) {
      test.done();
    });

    client.options.custom_assertions_path = './extra/assertions';
    Api.init(client);
    Api.loadCustomAssertions();

    test.expect(4);
    test.ok('customAssertion' in client.api.assert);
    test.ok('customAssertion' in client.api.verify);

    client.api.assert.customAssertion(test, true);
    client.queue.run();
  },
        it("can takeover response to a request", function () {
            var req = request.init({
                    id: "ImTotallyUniqueISwear",
                    url: "http://www.rim.com"
                });

            req.substitute();
            req.respond(204, "No Content");
            expect(message.send).toHaveBeenCalledWith("ResourceRequestedResponse", {
                id: "ImTotallyUniqueISwear",
                url: "http://www.rim.com",
                response: {
                    code: 204,
                    responseText: "No Content"
                }
            });
        });
Example #4
0
		(isDir ? fs.readdirSync(dir) : [dir]).forEach(function (filename) {
			var file = isDir ? path.join(dir, filename) : filename;
			if (fs.existsSync(file) && fs.statSync(file).isFile() && jsfile.test(filename) && (!isDir || !ignore.test(path.basename(file)))) {
				try {
					vm.runInThisContext('(function (exports, require, module, __filename, __dirname) { ' + fs.readFileSync(file).toString() + '\n});', file, 0, false);
					var mod = require(file);
					if (!this.version || !mod.cliVersion || semver.satisfies(this.version, mod.cliVersion)) {
						mod.init && mod.init(this.logger, this.config, this, appc);
						this.hooks.loadedFilenames.push(file);
					} else {
						this.hooks.incompatibleFilenames.push(file);
					}
				} catch (ex) {
					this.hooks.erroredFilenames.push(file);
				}
			}
		}, this);
      modules_list.forEach(function(module) {
	    
	    module_status = nconf.get('modules:'+module+':status');
	    
	    if(module_status === "loaded"){
	    
		var library_file = './modules/'+ module +'/main';
		logger.info('[MODULES] - File: '+ library_file);
		
		var library = require(library_file);

		library.init(module);
		library.exportModuleCommands(session);
	    
	    }
	  
      });  
Example #6
0
	var _createRepl = function () {

		var creds = _opts.insecure ? grpc.credentials.createInsecure() : grpc.credentials.createSsl();

		var connection = _opts.insecure ? 'grpc+insecure' : 'grpc+ssl';

		_opts.client = new _opts.service(_opts.host + ':' + _opts.port, creds);

		console.log('Service: '.green + '%s', _opts.serviceName.yellow);
		console.log('Host: '.green + '%s', _opts.host.yellow);
		console.log('Port: '.green + '%s', _opts.port.yellow);
		console.log('Secure: '.green + '%s', _opts.insecure ? 'No'.red : 'Yes'.yellow);

		repl.setPrompt('[' + connection + '://' + _opts.host + ':' + _opts.port + ']#');
		repl.setOpts(_opts);
		repl.init();
	};
Example #7
0
backends.forEach(function(name) {

	if(matched)
		return;//break

	var backend = require("./backends/"+name);
	
	var vars = backend.vars;

	if(!backend.init)
		exit("Backend " + name + " missing 'vars' array");

	var vals = vars.map(function(v) {
		var val = process.env[v];
		if(!val)
			backend = null;
		return val;
	});

	if(!backend)
		return;//continue

	//backend has been chosen by env vars,
	//now check its validity

	backend.name = name;

	if(!backend.init)
		exit("Backend " + name + " missing 'init(env vars...)' function");

	backend.init(config);

	if(typeof backend.upload !== "function")
		exit("Backend " + name + " missing 'upload(torrent file, callback)' function");

	if(typeof backend.remove !== "function")
		exit("Backend " + name + " missing 'remove(path, callback)' function");

	if(typeof backend.list !== "function")
		exit("Backend " + name + " missing 'list(callback)' function");

	//backend ready!
	module.exports = backend;
	matched = true;
});
  testAddCustomCommand : function(test) {
    var client = this.client;
    client.on('selenium:session_create', function(sessionId) {
      test.done();
    });

    client.options.custom_commands_path = './extra/commands';
    Api.init(client);
    Api.loadCustomCommands();

    test.ok('customCommand' in this.client.api, 'Test if the custom command was added');
    test.ok('customCommandConstructor' in this.client.api, 'Test if the custom command with constructor style was added');

    var queue = client.enqueueCommand('customCommandConstructor', []);
    var command = queue.currentNode;
    test.equal(command.name, 'customCommandConstructor');
    test.equal(command.context, client.api, 'Command should contain a reference to main client instance.');
  },
Example #9
0
  testAddCustomCommandFullPath : function(test) {
    var client = this.client;
    client.on('selenium:session_create', function(sessionId) {
      test.done();
    });

    var absPath = path.resolve('extra/commands');
    client.options.custom_commands_path = absPath;
    Api.init(client);

    test.doesNotThrow(
      function() {
        Api.loadCustomCommands();
      }, Error, 'Exception thrown loading custom command with absolute path'
    );

    test.ok('customCommand' in this.client.api, 'Commands defined with an absolute path were not loaded properly');
  },
	async.eachSeries(pp, function (plugin, cb) {
		_t.logger('loading plugin: ' + plugin);
		var p = require(plugin);
		_t.plugins.push(p);

		if (typeof p.init !== 'function') {
			return cb();
		}

		p.init(_t, function (err, caps) {
			if (err) {
				ic.printError(ex, 'error calling plugin config:', _t.logger);
			} else if (caps !== null && typeof caps === 'object') {
				appc.util.mix(_t.capabilities, caps);
			}
			cb();
		});
	}, callback);
Example #11
0
 dat.exists(function(err, exists) {
   t.false(err, 'no err')
   t.false(exists, 'does not exist')
   dat.init(function(err, msg) {
     dat.exists(function(err, exists) {
       t.false(err, 'no err')
       t.true(exists, 'exists')
       dat.destroy(function(err) {
         t.false(err, 'no err')
         dat.exists(function(err, exists) {
           t.false(err, 'no err')
           t.false(exists, 'does not exist')
           t.end()
         })
       })
     })
   })
 })
Example #12
0
function load_plugin(plugin_name, plugin_file, app, callback) {
	Console.debug('Loading plugin:');
	Console.debug('    Name 		- ' + plugin_name);
	Console.debug('    FileName 	- ' + plugin_file);

	var Plugin = require(plugin_file);
	Plugin.init(PluginInterface, function(error, plugin_app, plugin_description) {
		if(typeof(plugin_description) == 'undefined') {
			plugin_description = 'No description for this plugin, bad developer!';
		}
		if(error) {
			Console.debug('Error loading plugin: ' + error);
			// Skip this plugin...
			callback();
		}
		else if(typeof(plugin_app) == 'undefined') {
			var app_error = 'The ' + plugin_name + ' plugin returned a null app!'; 
			Console.debug(app_error);
			// Skip this plugin too...
			callback();
		}
		else {
			if(_.contains(loaded_plugins, plugin_name) == false) {
				// Add it to the successfully loaded plugin list
				loaded_plugins.push({
					name: plugin_name,
					description: plugin_description
				});

				// If this has an icon, pull it into the main app's
				// public folder
				var icon_file = path.join(__dirname, 'plugins', plugin_name, 'icon.png');
				copy_icon_to_dynamic_dir(icon_file, plugin_name);
			}

			// Bind this plugin's namespace to its corresponding
			// app so it will handle all its own HTTP routing
			app.use('/' + plugin_name, plugin_app);

			// Done with this unit of work
			callback();
		}
	});
}
 it('should bypass any non matching route', function (done) {
   var req = { url: '/', headers: { host: 'api.domain.com' } },
     args = [
     req,
     {
       send: function (code) {
         assert.strictEqual(code, 404, 'exit code should not be 404')
         done()
       }
     },
     function () {
       assert.strictEqual(req.url, '/', 'route should be `/`')
       done()
     }
   ]
   subdomains.init();
   subdomains.domain('domain.com').use('api2')
   subdomains.middleware.apply({}, args)
 })
 it('should not bypass any non matching route if strict is set', function (done) {
   var req = { url: '/', headers: { host: 'api2.otherdomain.com' } },
     args = [
     req,
     {
       send: function (code) {
         assert.strictEqual(code, 404, 'code should be 404')
         done()
       }
     },
     function () {
       assert.fail(req.url, 'none', 'route should not match')
       done()
     }
   ]
   subdomains.init();
   subdomains.domain('otherdomain.com').use('api').strict()
   subdomains.middleware.apply({}, args)
 })
Example #15
0
module.exports = function (app) {
  // middleware configuration
  app.use(conditional());
  app.use(etag());
  app.use(router(app));
  app.use(logger());
  app.use(responseTime);
  app.use(cors());

  // middleware below this line is only reached if jwt token is valid
  // TODO enable jwt auth app.use(jwt({secret: config.app.secret}));

  // create all models first so controllers have them available
  let model, schema;
  for (let name of require('fs').readdirSync(__dirname+'/../models')) {
    if (name[0] === '.') return;
    name = name.substring(0, name.length - 3);
    schema = require('../models/' + name);
    model = mongoose.model(name, schema);
  };

  // auto mount all the simple routes defined in the api controllers
  // initialize complex custom defined routes
  for (let fileName of fs.readdirSync(__dirname+'/../controllers')) {
    let controller = require(__dirname+'/../controllers/' + fileName);
    fileName = fileName.substring(0, fileName.length - 3);
    for (let propName in controller) {
      if (propName === 'init') {
        controller.init(app);
      } else {
        let arr = propName.split("_");
        let methodName = arr[0];
        let handlerName = arr[1];
        app[methodName](`/${config.app.apiPrefix}/${pluralize(fileName)}/${handlerName}`, controller[propName]);
      }
    }
  };

  // mount REST routes for all models last so it doesn't override the controller methods
  for (let model of mongoose.modelNames()){
    generateApi(app, mongoose.model(model), '/' + config.app.apiPrefix);
  }
};
Example #16
0
 return _.map(_.clone(c), function(definition){
   if(definition.source){
     var fn = require(path.join(process.cwd(),definition.source))
     if(fn.init)
       return fn.init(self.plasma, definition, "/")
     if(definition.arguments)
       return fn.apply(fn, definition.arguments)
     if(fn.length == 2)
       return fn(self.plasma, self.config)
     else
       return fn(self.config)
   } else{
     var fn = require(path.join(process.cwd(),definition))
     if(fn.length == 1)
       return fn(self.config)
     else
       return fn
   }
 })
Example #17
0
ibc.prototype.switchPeer = function(index) {
	if(chaincode.details.peers[index]) {
		rest.init({																	//load default values for rest call to peer
					host: chaincode.details.peers[index].api_host,
					port: chaincode.details.peers[index].api_port,
					headers: {
								"Content-Type": "application/json",
								"Accept": "application/json",
							},
					ssl: chaincode.details.peers[index].ssl,
					timeout: 60000,
					quiet: true
		});
		ibc.selectedPeer = index;
		return true;
	} else {
		return false;
	}
};
        function () {
          var config = {};
          var mockAnswers = {
            language: 'es6',
            srcDir: './dir',
            distDir: './foo',
            testDir: './bar'
          };
          var generator = mocks.buildGenerator(config, mockAnswers);

          // Set defaults
          structure.init(generator);
          structure.prompt(generator);
          structure.configure(generator);

          Object.keys(mockAnswers).forEach(function (key) {
            expect(generator.config.get(key)).toEqual(mockAnswers[key]);
          });
        });
Example #19
0
module.exports.run = function(cli, args) {
  const instance = require(_path.join(ROOT, 'src/server/node/core/instance.js'));
  const settings = require(_path.join(ROOT, 'src/server/node/core/settings.js'));

  const opts = {
    DEBUG: cli.option('debug'),
    PORT: cli.option('port'),
    LOGLEVEL: cli.option('loglevel')
  };

  instance.init(opts).then((env) => {
    const config = settings.get();
    if ( config.tz ) {
      process.env.TZ = config.tz;
    }

    process.on('exit', () => {
      instance.destroy();
    });

    instance.run();

    process.on('uncaughtException', (error) => {
      _logger.log('UNCAUGHT EXCEPTION', error, error.stack);
    });

    ['SIGTERM', 'SIGINT'].forEach((sig) => {
      process.on(sig, () => {
        console.log('\n');
        instance.destroy((err) => {
          process.exit(err ? 1 : 0);
        });
      });
    });
  }).catch((error) => {
    _logger.log(error);
    process.exit(1);
  });

  return new Promise(() => {
    // This is one promise we can't keep! :(
  });
};
Example #20
0
            it('will be scheduled', function (done) {
                postScheduling.init({
                    apiUrl: scope.apiUrl
                }).then(function () {
                    scope.events['post.scheduled'](scope.post);
                    scope.adapter.schedule.called.should.eql(true);

                    scope.adapter.schedule.calledWith({
                        time: moment(scope.post.get('published_at')).valueOf(),
                        url: scope.apiUrl + '/schedules/posts/' + scope.post.get('id') + '?client_id=' + scope.client.get('slug') + '&client_secret=' + scope.client.get('secret'),
                        extra: {
                            httpMethod: 'PUT',
                            oldTime: null
                        }
                    }).should.eql(true);

                    done();
                }).catch(done);
            });
Example #21
0
Tesebo.prototype.loadPlugin = function(name, options) {
    var path = __dirname + "/plugins/" + name;
    console.log("Loading plugin: ", name);
    var plugin = require(path);
    plugin.bot = this;
    plugin.options = options;
    var listeners = plugin.listeners;
    if (listeners) {
        for (var type in listeners) {
            var listener = listeners[type];
            this.client.addListener(type, listener);
            this.listeners.push(listener);
        }
    }
    if (plugin.init) {
        plugin.init();
    }
    this.plugins.push(plugin);
};
Example #22
0
ibc.prototype.switchPeer = function(index) {
    if(ibc.chaincode.details.peers[index]) {
        rest.init({                                                                        //load default values for rest call to peer
                    host: ibc.chaincode.details.peers[index].api_host,
                    port: pick_port(index),
                    headers: {
                                'Content-Type': 'application/json',
                                'Accept': 'application/json',
                            },
                    ssl: ibc.chaincode.details.peers[index].tls,
                    timeout: ibc.chaincode.details.options.timeout,
                    quiet: ibc.chaincode.details.options.quiet
        });
        ibc.selectedPeer = index;
        return true;
    } else {
        return false;
    }
};
Example #23
0
  this.loadExtensions = function (module) {
    var route = '/modules/' + module.name;
    var info = module.getExtension('debugger');
    if (info) {
      // mount dynamic routes
      if (info.routes) {
        try {
          var moduleRoutes = express();
          var routes = require(path.join(module.path, info.routes));
          if (routes.init) {
            routes.init(api, this.app.toJSON(), moduleRoutes);
            this.expressApp.use(route, moduleRoutes);
          } else {
            logger.warn('expecting an init function for the routes of',
                module.path + ', but init was not found!');
          }
        } catch (e) {
          console.error('Unable to load debugger extension from', module.name);
          console.error(e.stack || e);
        }
      }

      // setup a main file
      if (info.main) {
        var mainFile = info.main;
        var ext = path.extname(mainFile).toLowerCase();
        if (!ext) {
          mainFile += '.js';
          ext = '.js';
        }

        // simulator will init all urls in this.debuggerURLs
        var routeName = route + '/' + mainFile;
        this.debuggerURLs[module.name] = '/apps/' + this.id + routeName;
      }

      // mount static routes
      if (info.static) {
        var staticPath = path.join(module.path, info.static);
        this.expressApp.use(route, express.static(staticPath));
      }
    }
  };
Example #24
0
		}, function () {
			var currentPath = path.join(this.getPath(addon), "index.js");
			if (!fs.existsSync(currentPath)) {
				logger.warn("Couldn't find index.js! Your addon may break.",
					"Contact the addon's creator for more information.");
			} else {
				try {
					//try to include the file and execute init()
					var idx = require(currentPath);
					if (typeof idx.init === "function") {
						idx.init(common);
					}
				} catch (e) {
					logger.error("Error loading [" + currentPath + "] : init():");
					console.error(e);
					console.error(e.stack);
				}
			}
		}).error(function (e) {
Example #25
0
    exports.lodashify = function(options) {
      var lodashbuilder = require(require.resolve('grunt-lodashbuilder').replace('grunt.js', '') + '/lib/builder.js');
      var lodash = lodashbuilder.init(grunt);

      if (options.config.builder && options.config.builder.lodash) {
        grunt.log.writeln('Running Lo-Dash custom build');
        lodash.build({config: options.config.builder.lodash, debug: true}, function (transport) {
          // display error
          if (transport.type === 'error') {
            grunt.log.error(transport.content);
          }

          // proceed with file content
          if (transport.type === 'content') {
            // prepare builder transport
            if (!options.config.__builderOutput) options.config.__builderOutput = [];
            options.config.__builderOutput.push({
              name: 'lodash',
              alias: (options.config.builder.lodash.alias ? options.config.builder.lodash.alias : 'lodash'),
              content: transport.content
            });

            // call the almondify callback helper
            options.cb({
                config: options.config,
                done: options.done,
                cb: options.Helper.optimize(options.config, options.done, options.Helper.replaceAlmond(options.config, options.done))
            });
          }

        });
      } else {
        // call the almondify callback helper
        options.cb({
            config: options.config,
            done: options.done,
            cb: options.Helper.optimize(options.config, options.done, options.Helper.replaceAlmond(options.config, options.done))
        });
      }

      // return traced informations
      return true;
    };
Example #26
0
      it('adds default config content', done => {
        const expected = {
          "endpoints": {
            "5000": {
              "get": [],
              "default": true
            }
          }
        }

        project.init(initErr => {
          fs.readFile(config.configName, 'utf8', (err, data) => {
            assert.notOk(err)

            assert.deepEqual(JSON.parse(data), expected)
            done()
          })
        })
      })
Example #27
0
process.on("message", function(message) {

	// console.log(message);

	switch(message.cmd){

		case "init":
			visualiser.init(message.front.width, message.front.height, message.side.width, message.side.height);
			postProcessing.init(message.front.width, message.front.height, message.side.width, message.side.height, message.options);

			
		break;

		case "connect":
			socket_address = message.address;
			socket_transmit.bindSync(socket_address);

			postProcessing.fadeIn();
			
		break;

		case "fadeOut":
			postProcessing.fadeOut();
		break;

		case "disconnect":
			socket_transmit.disconnect(socket_address);

		break;

		case "render":
			visualiser.render();
			if (socket_transmit){
				postProcessing.processCanvases(visualiser.faces.front, visualiser.faces.side);
				socket_transmit.send(postProcessing.getBuffer());
			}

		break;

	}

});
Example #28
0
bonobo.init = function(rootDir, cb) {
  
  
  bonobo.pluginDir = rootDir;
  
  var readDirs = fs.readdirSync(rootDir);
  
  models.init(bonobo);
        
  var errs = []
    , msgs = []
    , i = 0;
    
  //load and init plugins
  for(var idx in readDirs) {
    
    var pluginName = readDirs[i];
    
    var filename = path.join(rootDir, pluginName);
    
    require(filename).init(bonobo, function(err, plugin) {
      if(err) errs.push({message: err, css: 'fail'});
      
      if(!err) msgs.push({message: 'initing '+pluginName+' plugin success', css: 'win'});
      
      bonobo.plugins[pluginName] = plugin;
      
      i++;
      if(i >= utils.count(readDirs) ) {
        
        setup.init(bonobo); //starts the setup of the base and the plugins that request autosetup
        routes.init(bonobo); //sets the routes for the application
        middleware.init(bonobo); //adds middleware from plugins
        pluginsettings.init(bonobo); // gets and sets pluginsettings
        menuitems.init(bonobo); //gets and sets menuitems
        
        
        cb(null, msgs);
      }
    });
  }
}
Example #29
0
    it('should load the component and fire their lifecircle callback by app.start, app.afterStart, app.stop', function(done) {
      var startCount = 0, afterStartCount = 0, stopCount = 0;

      var mockComponent = {
        start: function(cb) {
          console.log('start invoked');
          startCount++;
          cb();
        },

        afterStart: function(cb) {
          console.log('afterStart invoked');
          afterStartCount++;
          cb();
        },

        stop: function(force, cb) {
          console.log('stop invoked');
          stopCount++;
          cb();
        }
      };

      app.init({base: mockBase});
      app.load(mockComponent);
      app.start(function(err) {
        should.not.exist(err);
      });

      setTimeout(function() {
        // wait for after start
        app.stop(false);

        setTimeout(function() {
          // wait for stop
          startCount.should.equal(1);
          afterStartCount.should.equal(1);
          stopCount.should.equal(1);
          done();
        }, WAIT_TIME);
      }, WAIT_TIME);
    });
Example #30
0
 scripts.forEach(function(script) {
     console.log("Loading script " + script);
     var s = require("../scripts/" + script);
     var name = mergeConfigs(s.defaultConfig);
     s.init(config.scripts[name]);
     if(s.enabled) {
         console.log("Starting up script " + s.name);
         var exec = function () {
             s.run(pool);
             setTimeout(
                 function () {
                     exec();
                 },
                 s.interval
             );
         };
         exec();
         scripts.push(s);
     }
 });