The Handler class, correlates the swagger paths with the handlers directory structure and adds the d
custom logic to the Express instance.
@param server
@constructor
170922
function Handlers(server) {
  var self = this;
  this.server = server;

  //Store the most recently parsed swagger data for when only the handlers get re-attached.
  this.server.on('parsed', function(err, api, parser, basePath) {
    self.api = api;
    self.parser = parser;
    self.basePath = basePath;
    self.setupHandlers();
  });
}
615268
function handler(req, res) {

  var parsedUrl = url.parse(req.url)
  var callback = qs.parse(parsedUrl.query).callback
  var filename = decodeURI(parsedUrl.path.substr(1).split('?')[0])
  var basename = path.basename(filename.split('?')[0])
  var extname = path.extname(basename)
  var response = reswrap(res);
  var notfound = function() {
    response.writeHead(404, 'text').end('');
  };

  if (req.method === 'GET' && parsedUrl.pathname === '/jsonp-request') {
    if (!!exitCountdown) {
      exitCountdown.restart();
    }

    response
      .writeHead(200, 'js')
      .end(callback +'('+ R.get('stamp') +')');

    return;
  }

  var serve;
  if (/^\/template/.test(parsedUrl.pathname)) {
    serve = check(join(__dirname, '..', filename))
  } else if (/^\/node_modules/.test(parsedUrl.pathname)) {
    serve = check(join(__dirname, '..', filename))
  }
  if (serve) {
    serve.pass(function(name, type) {
      response
        .writeHead(200, extname.substr(1))
        .pipeWith(fs.createReadStream(
          path.resolve(name)
        ))
    }).fail(notfound);
    return;
  }

  if (/^\.(md|mkd|markdown|html)$/.test(extname)) {
    check(filename)
      .pass(function() {
        response
          .writeHead(200, 'html')
          .end(template.render({
            title: basename,
            highlight: R.get('highlight') || 'default',
            theme: getTheme(R.get('css')),
            width: R.get('width'),
            body: parser.parse(read(path.resolve(filename)))
          }));
      }).fail(notfound);

    return;
  }

  // Image or some other resources.
  check(filename)
    .pass(function(name) {
      response
        .writeHead(200, name)
        .pipeWith(fs.createReadStream(name));
    }).fail(notfound)
}
440781
function MiddlewareContext (router) {
  events.EventEmitter.call(this);

  /**
   * Express routing options (e.g. `caseSensitive`, `strict`).
   * If set to an Express Application or Router, then its routing settings will be used.
   * @type {express#Router}
   */
  this.router = router || {};

  /**
   * The parsed Swagger API
   * @type {SwaggerObject}
   */
  this.api = null;

  /**
   * The {@link SwaggerParser} instance that was used to parse the API.
   * @type {SwaggerParser}
   */
  this.parser = null;

  /**
   * If the Swagger API contains errors, this will be set
   * @type {Error}
   */
  this.error = null;
}
237071
function defineRoute (server, opts) {

    server.route({
        method: 'GET',
        path: '/' + opts.plural,
        handler: handler,
        config: {
            jsonp: 'callback',
            validate: {
                query: {},
                payload: false
            }
        }
    });

    function handler (req) {
        var res = {};
        res[opts.plural] = opts.things;
        req.reply(res);
    }

}
1143684
function middlewares() {
        app.middlewares = {}
        const basePath = path.join(app.root, '/middlewares')
        let middlewares = app.config.get('express').middlewares
        if (middlewares && Array.isArray(middlewares) && middlewares.length) {
            for (let m of middlewares) {
                let middleware = require(path.join(basePath, m.dest))(app)
                app.middlewares[m.dest.toLowerCase()] = middleware

                if (middleware.length == 4) { //error handler
                    errorHandlers.push(middleware)
                    continue
                }

                if (m.src)
                    server.use(m.src, wrapper(middleware))
                else
                    server.use(wrapper(middleware))
            }
            if (middlewares.length)
                app.drivers.logger.success('Middleware', 'initialized')
        }
    }
377945
public void wrapHandler(String path, Class<?> handler) {
        Method[] methods = handler.getMethods();
        Map<Class<? extends Annotation>, Method> cache = new HashMap<>(3);
        cacheMethod(cache, methods, OnOpen.class);
        cacheMethod(cache, methods, OnMessage.class);
        cacheMethod(cache, methods, OnClose.class);
        if (cache.size() > 0) {
            methodCache.put(path, cache);
            handlers.put(path,handler);
        } else {
            throw new RuntimeException("Do not found any annotation of [@OnOpen / @OnMessage / @OnClose] in class: " + handler.getName());
        }
    }
702992
function(_gulp, _config) {
  if (!_gulp) {
    throw 'Error: A Gulp instance should be passed to the gulpConfig method.';
  }
  gulp = _gulp;
  config = _config || { paths: { src: {}, out: {} } };

  plugins = elaboratePlugins();
  paths = elaboratePaths();

  lrport = _config.liveReloadPort || lrport;
  server = _config.server || (console.error(
      'An Express server should be passed in the configuration.')),
  serverport = _config.port || serverport;

  cleanTmp = function(done) {
    del(paths.src.tmp, { force: _config.forceClean || false }, done);
  };
}
589821
function HyperServer($){

    //setup
    $ = Object.assign( defaults, $ ); 

    //injection
    let gx   = $.generator;
    let hx   = $.handler;

    //prototype
    let $ns, $n = proto();
    let dev  = ( 'development' == $n.get('env') || process.env.NODE_ENV  == 'development' );
    let port = (( dev ? $.LOCAL_PORT : $.APP_PORT ) || process.env.NODE_PORT );
 
    //config mapping
    $n.set( 'port', port );
    $n.set( 'view engine', $.VIEW_ENGINE );

    //middleware in out next
    if( dev ) $n.use( errorHandler({ dumpExceptions: true, showStack: true }) );
    $n.use( bodyParser.json() );
    $n.use( bodyParser.urlencoded({ extended:true }) );
    $n.use( override() );
    $n.use( cookieParser() );
    $n.use( sss({secret: 'secret', key:$.SESSION_ID, resave:true, saveUninitialized:true }));
    $n.use( ( i, o, n ) => { o.set('X-Powered-By', $.SERVER_ID ); n(); });
    $n.use( ( i, o, n ) => { i.baseUrl = i.originalUrl.split("?").shift(); n(); });
    $n.use( ( i, o, n ) => { console.info( `[${i.method} ${i.baseUrl}]`) || n(); }); //| q:${k(i.query)} \t | c:${k(i.cookies)}` ) || n(); });
    $n.use( favicon( $.PUBLIC_WWW + '/favicon.ico') );
    $n.use( proto.static( $.PUBLIC_WWW, {  
        setHeaders: ( res, path, stat ) => res.set('X-Timestamp', Date.now())
    }));

    //route stubs
    $.router.route( $n );

    //boot
    $ns = http.createServer($n)
          .on( 'close', ()=> {
            console.error( $.SERVER_ID + " - Shutting Down..");
          })
          .listen( port, data => {
            console.info( `Env  : [ ${( dev ? "DEV" : "UAT" )} ] \nPort : [ ${port} ]` );
            console.info( `URL  :  http://localhost:${port}` );
          });

    //termsigs
    process.once( 'SIGUSR2', ()=> {
            console.warn( 'Attempting to graceful kill...' );
            process.kill( process.pid, 'SIGUSR2');
          })
          .once( 'EADDRINUSE', ()=> {
            console.warn( 'Required port unavailable' );
            process.exit(1);
          });

    return $n;
  }
910030
function createServer(options) {
    var opt = new Options(options || {});

    var app = express();
    // Import configuration
    for (var o in opt) {
	app.set(o, opt[o]);
    }
    // Default middleware
    app.use(express.favicon())
	.use(express.query())
	.use(express.bodyParser())
	.use(express.cookieParser())
	.use(express.session( {secret: opt.secret } ))
	.use(opt.static_mount, express.static(opt.static_dir))
    // Template engines
    app.engine('mustache', cons.hogan)
	.engine('mu', cons.hogan)
	.set('view engine', 'mustache')
	.set('views', opt.template_dir);
    // Custom middleware
    app.use(exports.logger(opt.separator))
	.use(set_cookie)
	.use(exports.multi_render(app))
	.use(exports.fun_router(app));
    
    // Specify default page
    if (opt.default_route)
	app.get('/', function(req, res) { res.redirect(opt.default_route); });

    // Create http server
    app.http_server = http.createServer(app);
    if (app.get('socket_io')) {
	app.io = require('socket.io').listen(app.http_server);
    }

    app.listen = function() {
	app.http_server.listen.apply(app.http_server, arguments);
    };

    app.start = startServer;
    
    return app;
}
1263196
function(app, serverType, handlerMap) {
  let p = pathUtil.getHandlerPath(app.getBase(), serverType);
  if(p) {
    handlerMap[serverType] = Loader.load(p, app);
  }
}
1107809
function WebServer(data) {
  // Use a closure to preserve `this`
  var self = this;
  self.data = data;

  this.RequestHandler = bind(this.RequestHandler, this);
  this.callbackExecutor = bind(this.callbackExecutor, this);

  self.server = http.createServer(self.RequestHandler);

  // Use random port if port settings is not provided.
  if (!self.data.port) {
    self.data.port = 0;
  }

  // Use address if provided.
  if (self.data.hostname) {
    self.server.listen(self.data.port, self.data.hostname);
  } else {
    self.server.listen(self.data.port);
  }

  self.server.on('listening', function() {
    self.debug.log('Listen on :%s', self.server.address().port);
  });
}
820060
function (method, endpoint, routerMiddelware) {
		var self = this;

		if (typeof routerMiddelware == 'object'){
			this.app[method](endpoint, function (req, res, next) {
				var middlewareFunction = []
				routerMiddelware.forEach(function (m) {
					middlewareFunction.push(function (cb) {
						self.__exec__middlewares(m, req, res, cb);
					});
				});

				async.waterfall(middlewareFunction);
			});
		} else {
			this.app[method](endpoint, function (req, res, next) {
				self.__exec__middleware(routerMiddelware)(req, res, next);
			});
		}
	}
533453
public void addHandler(AbstractHandler handler) {
    HandlerList handlers = new HandlerList();
    handlers.addHandler(handler);
    for (Handler h : mServer.getHandlers()) {
      handlers.addHandler(h);
    }
    mServer.setHandler(handlers);
  }
772280
public void prepareServer() {
        try {
            server = new Server(0);
            jettyHandler = new AbstractHandler() {
                public void handle(String target, Request req, HttpServletRequest request,
                                   HttpServletResponse response) throws IOException, ServletException {
                    response.setContentType("text/plain");

                    String[] operands = request.getRequestURI().split("/");

                    String name = "";
                    String command = "";
                    String value = "";

                    //operands[0] = "", request starts with a "/"

                    if (operands.length >= 2) {
                        name = operands[1];
                    }

                    if (operands.length >= 3) {
                        command = operands[2];
                    }

                    if (operands.length >= 4) {
                        value = operands[3];
                    }

                    if (command.equals("report")) { //report a number of lines written
                        response.getWriter().write(makeReport(name, value));
                    } else if (command.equals("request") && value.equals("block")) { //request a new block of work
                        response.getWriter().write(requestBlock(name));
                    } else if (command.equals("request") && value.equals("name")) { //request a new name to report with
                        response.getWriter().write(requestName());
                    } else { //non recognized response
                        response.getWriter().write("exit");
                    }

                    ((Request) request).setHandled(true);
                }
            };

            server.setHandler(jettyHandler);

            // Select any available port
            server.start();
            Connector[] connectors = server.getConnectors();
            NetworkConnector nc = (NetworkConnector) connectors[0];
            listeningPort = nc.getLocalPort();
            hostName = InetAddress.getLocalHost().getHostName();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
507324
@ExceptionHandler(Exception.class)
    @RequestMapping(value = "api/edit/server/{id}", method = RequestMethod.POST)
    public
    @ResponseBody
    ServerRedirect updateServer(Model model, @PathVariable int id,
                                @RequestParam(required = false) Boolean enabled) throws Exception {
        logger.info("updating Server");
        if (enabled != null) {
            if (enabled) {
                Client.enableHost(ServerRedirectService.getInstance().getRedirect(id).getSrcUrl());
            } else {
                Client.disableHost(ServerRedirectService.getInstance().getRedirect(id).getSrcUrl());
            }
        }
        return ServerRedirectService.getInstance().getRedirect(id);
    }
1326847
function createTreeListener({ handler, restPath }) {
    const newHandler = function treeListener(changeEvent) {
        const extendedChangeEvent = {
            restPath,
            ...changeEvent
        };
        const { previousValue, value } = changeEvent;

        // removes listener for all branches of the path on old object
        if (previousValue && typeof previousValue === 'object') {
            removeTreeListener(previousValue, restPath, handler);
        }

        // adds listener for all branches of "restPath" path on newly assigned object
        if (value && typeof value === 'object') {
            addTreeListener(value, restPath, handler);
        }

        // call original handler
        handler.call(this, extendedChangeEvent);
    };

    newHandler._callback = handler;

    return newHandler;
}
937019
function Server(svc, opts) {
  opts = opts || {};
  events.EventEmitter.call(this);

  this.service = svc;
  this._handlers = {};
  this._fns = []; // Middleware functions.
  this._channels = {}; // Active channels.
  this._nextChannelId = 1;

  this._cache = opts.cache || {}; // Deprecated.
  this._defaultHandler = opts.defaultHandler;
  this._sysErrFormatter = opts.systemErrorFormatter;
  this._silent = !!opts.silent;
  this._strict = !!opts.strictTypes;

  if (opts.remoteProtocols) {
    insertRemoteProtocols(this._cache, opts.remoteProtocols, svc, false);
  }

  svc.messages.forEach(function (msg) {
    var name = msg.name;
    if (!opts.noCapitalize) {
      name = utils.capitalize(name);
    }
    this['on' + name] = this._createMessageHandler(msg);
  }, this);
}