Serves files from the entire filesystem if enabled in settings.

@param {Object} req        - request object
@param {Object} res        - response object
@param {Function} next     - called on handler miss
@param {boolean} local - local mode
434582
function LocalFilesystemHandler(req, res, next, local = false) {
            if (!self.settings.localFilesystem) {
                return next();
            }
            return FilesystemHandler(req, res, next, self.localFilesystemUrl, undefined, local);
        }
1357319
function serveSassFiles(magnet, outputDir) {
  if (!isServingSassFiles) {
    magnet.getServer()
      .getEngine()
      .use('/css', express.static(outputDir));
  }
  isServingSassFiles = true;
}
125450
function(err, req, res, next) {
    if (err) {
        var url = req.url || '';

        log.debug(req.method, req.headers);
        log.error(('Requested url: ' + url).red, ('Error: ' + err.stack).red);

        if (req.xhr) {
            res.status(500).json({msg: 'Server error'});
        } else {
            res.status(500).send('Server error');
        }
    } else {
        next();
    }
}
586234
function rewrite(req, res) {

  /* istanbul ignore next: tough to mock fs write error */
  function onError(err) {
    this.conf.removeAllListeners('error');
    this.conf.removeAllListeners('write');
    res.send(err);
  }

  function onWrite() {
    this.conf.removeAllListeners('error');
    this.conf.removeAllListeners('write');
    res.send(null, Constants.OK);
  }

  this.conf.once('error', onError.bind(this));
  this.conf.write(this.conf.getFile(), onWrite.bind(this));
}
741977
function serveStatic(options) {
    var opts = options || {};

    if (typeof opts.appendRequestPath === 'undefined') {
        opts.appendRequestPath = true;
    }

    assert.object(opts, 'options');
    assert.string(opts.directory, 'options.directory');
    assert.optionalNumber(opts.maxAge, 'options.maxAge');
    assert.optionalObject(opts.match, 'options.match');
    assert.optionalString(opts.charSet, 'options.charSet');
    assert.optionalString(opts.file, 'options.file');
    assert.bool(opts.appendRequestPath, 'options.appendRequestPath');

    var p = path.normalize(opts.directory).replace(/\\/g, '/');
    var re = new RegExp('^' + escapeRE(p) + '/?.*');

    function serveFileFromStats(file, err, stats, isGzip, req, res, next) {

        if (typeof req.connectionState === 'function' &&
            (req.connectionState() === 'close' ||
            req.connectionState() === 'aborted')) {
            next(false);
            return;
        }

        if (err) {
            next(new ResourceNotFoundError(err, '%s', req.path()));
            return;
        } else if (!stats.isFile()) {
            next(new ResourceNotFoundError('%s does not exist', req.path()));
            return;
        }

        if (res.handledGzip && isGzip) {
            res.handledGzip();
        }

        var fstream = fs.createReadStream(file + (isGzip ? '.gz' : ''));
        var maxAge = opts.maxAge === undefined ? 3600 : opts.maxAge;
        fstream.once('open', function (fd) {
            res.cache({maxAge: maxAge});
            res.set('Content-Length', stats.size);
            res.set('Content-Type', mime.lookup(file));
            res.set('Last-Modified', stats.mtime);

            if (opts.charSet) {
                var type = res.getHeader('Content-Type') +
                    '; charset=' + opts.charSet;
                res.setHeader('Content-Type', type);
            }

            if (opts.etag) {
                res.set('ETag', opts.etag(stats, opts));
            }
            res.writeHead(200);
            fstream.pipe(res);
            fstream.once('close', function () {
                next(false);
            });
        });

        res.once('close', function () {
            fstream.close();
        });
    }

    function serveNormal(file, req, res, next) {
        fs.stat(file, function (err, stats) {
            if (!err && stats.isDirectory() && opts.default) {
                // Serve an index.html page or similar
                var filePath = path.join(file, opts.default);
                fs.stat(filePath, function (dirErr, dirStats) {
                    serveFileFromStats(filePath,
                        dirErr,
                        dirStats,
                        false,
                        req,
                        res,
                        next);
                });
            } else {
                serveFileFromStats(file,
                    err,
                    stats,
                    false,
                    req,
                    res,
                    next);
            }
        });
    }

    function serve(req, res, next) {
        var file;

        if (opts.file) {
            //serves a direct file
            file = path.join(opts.directory,
                decodeURIComponent(opts.file));
        } else {
            if (opts.appendRequestPath) {
                file = path.join(opts.directory,
                    decodeURIComponent(req.path()));
            }
            else {
                var dirBasename = path.basename(opts.directory);
                var reqpathBasename = path.basename(req.path());

                if (path.extname(req.path()) === '' &&
                    dirBasename === reqpathBasename) {

                    file = opts.directory;
                }
                else {
                    file = path.join(opts.directory,
                        decodeURIComponent(path.basename(req.path())));
                }
            }
        }

        if (req.method !== 'GET' && req.method !== 'HEAD') {
            next(new MethodNotAllowedError(req.method));
            return;
        }

        if (!re.test(file.replace(/\\/g, '/'))) {
            next(new NotAuthorizedError('%s', req.path()));
            return;
        }

        if (opts.match && !opts.match.test(file)) {
            next(new NotAuthorizedError('%s', req.path()));
            return;
        }

        if (opts.gzip && req.acceptsEncoding('gzip')) {
            fs.stat(file + '.gz', function (err, stats) {
                if (!err) {
                    res.setHeader('Content-Encoding', 'gzip');
                    serveFileFromStats(file,
                        err,
                        stats,
                        true,
                        req,
                        res,
                        next);
                } else {
                    serveNormal(file, req, res, next);
                }
            });
        } else {
            serveNormal(file, req, res, next);
        }

    }

    return (serve);
}
1198280
function requestHandler(req, res, next) {
  const start = Date.now();
  let source;

  return Promise.try(() => {
    source = core.getPublicSource(req.params.src);
    return source.getHandler().getInfoAsync().then(info => [info, infoHeaders]);
  }).spread((data, dataHeaders) => {
    core.setResponseHeaders(res, source, dataHeaders);

    if (req.query && req.query.format) {
      const escapedText = JSON.stringify(data, null, ' ').replace(/&/g, '&amp;').replace(/</g, '&lt;');
      res.send(`<pre>${escapedText}</pre>`);
    } else {
      res.json(data);
    }

    const mx = util.format('req.%s.info', req.params.src);
    core.metrics.endTiming(mx, start);
  }).catch(err => core.reportRequestError(err, res)).catch(next);
}
1206361
function serveRawSwaggerFiles (req, res, next) {
    if (req.method === "GET" || req.method === "HEAD") {
      let configPath = getConfiguredPath(options.rawFilesPath);
      configPath = util.normalizePath(configPath, router);
      let reqPath = util.normalizePath(req.path, router);

      if (_.startsWith(reqPath, configPath) && context.parser && context.parser.$refs) {
        // Get the normalized path of the requested file, relative to the baseDir
        let relativePath = req.path.substring(configPath.length);
        if (_.startsWith(relativePath, "/")) {
          relativePath = relativePath.substring(1);
        }
        relativePath = path.normalize(util.normalizePath(relativePath, router));

        // See if any of the Swagger files match this path
        let filePath = _.find(context.parser.$refs.paths(), (file) => {
          let relativeFile = path.relative(baseDir, file);
          relativeFile = util.normalizePath(relativeFile, router);
          return relativeFile === relativePath;
        });

        if (filePath) {
          // Normalize the file path (required for Windows)
          filePath = path.normalize(filePath);

          util.debug("%s %s => Sending file %s", req.method, req.path, filePath);
          res.sendFile(filePath);
          return;
        }
        else {
          util.debug("%s %s does not match any files in the Swagger API", req.method, req.path);
        }
      }
    }

    next();
  }
173594
function router(req, resp, next) {
    const routerPath = req.routePath || '';

    const beforeRunMiddleware = (route) => {
      const match = matchRoute(routerPath, req, route);
      if (!match) return false;

      const { params, path: matchPath } = match;

      if (options.params) req.params = { ...options.params, ...params };
      else req.params = params;

      // dynamically set req.routePath for the route
      req.routePath = routerPath + matchPath;
      return true;
    };
    const routeStack = compose(router.routes, { beforeRunMiddleware });

    return routeStack.call(this, req, resp, () => {
      req.routePath = routerPath;// restore routePath
      return next && next();
    });
  }
211056
public function runMiddleware(Request $req, Response $res)
    {
        $this->initMiddleware()->rewind();

        return $this->nextMiddleware($req, $res);
    }
1338646
function nextCreate(
  filesPromise,
  serveStaticFile,
  serveFile,
  injector,
  basePath,
  urlRoot,
  upstreamProxy
) {
  var prevMiddleware = prevCreate(
    filesPromise,
    serveStaticFile,
    serveFile,
    injector,
    basePath,
    urlRoot,
    upstreamProxy
  );
  return function nextMiddleware(request, response, next) {
    var requestUrl = request.normalizedUrl.replace(/\?.*/, '');
    var prevWrite;
    var prevEnd;
    requestUrl = requestUrl.substr(urlRoot.length - 1);
    if (requestUrl === '/context.html' &&
        toplevelScriptIntegrity &&
        toplevelScriptIntegrity.startsWith('sha') &&
        stylesheetIntegrity &&
        stylesheetIntegrity.startsWith('sha')) {
      prevWrite = response.write;
      prevEnd = response.end;
      // eslint-disable-next-line no-param-reassign
      response.write = function nextWrite(chunk, encoding, callback) {
        prevWrite.call(response, addIntegrityTags(chunk), encoding, callback);
      };
      response.end = function nextEnd(chunk, encoding, callback) {
        prevEnd.call(response, addIntegrityTags(chunk), encoding, callback);
      };
    }
    return prevMiddleware(request, response, next);
  };
}
612222
function handler(req, res, next) {
  var userAgent = req.headers["user-agent"];

  //-- set device
  req.device = new Device(userAgent);

  return next();
}
1213190
function (req, res, next) {
                    req.mounted = true
                    req.url     = req.url.replace(remove, '')

                    // clear cached req.path
                    delete req._path
                    delete req._pathLength

                    next()
                }
1203091
private void sendDirectory(final YokeRequest request, final String dir, final Handler<Object> next) {
        final FileSystem fileSystem = vertx().fileSystem();

        fileSystem.readDir(dir, new AsyncResultHandler<List<String>>() {
            @Override
            public void handle(AsyncResult<List<String>> asyncResult) {
                if (asyncResult.failed()) {
                    next.handle(asyncResult.cause());
                } else {
                    String accept = request.getHeader("accept", "text/plain");

                    if (accept.contains("html")) {
                        String normalizedDir = dir.substring(root.length());
                        if (!normalizedDir.endsWith("/")) {
                            normalizedDir += "/";
                        }

                        String file;
                        StringBuilder files = new StringBuilder("<ul id=\"files\">");

                        for (String s : asyncResult.result()) {
                            file = s.substring(s.lastIndexOf('/') + 1);
                            // skip dot files
                            if (!includeHidden && file.charAt(0) == '.') {
                                continue;
                            }
                            files.append("<li><a href=\"");
                            files.append(normalizedDir);
                            files.append(file);
                            files.append("\" title=\"");
                            files.append(file);
                            files.append("\">");
                            files.append(file);
                            files.append("</a></li>");
                        }

                        files.append("</ul>");

                        StringBuilder directory = new StringBuilder();
                        // define access to root
                        directory.append("<a href=\"/\">/</a> ");

                        StringBuilder expandingPath = new StringBuilder();
                        String[] dirParts = normalizedDir.split("/");
                        for (int i = 1; i < dirParts.length; i++) {
                            // dynamic expansion
                            expandingPath.append("/");
                            expandingPath.append(dirParts[i]);
                            // anchor building
                            if (i > 1) {
                                directory.append(" / ");
                            }
                            directory.append("<a href=\"");
                            directory.append(expandingPath.toString());
                            directory.append("\">");
                            directory.append(dirParts[i]);
                            directory.append("</a>");
                        }

                        request.response().setContentType("text/html");
                        request.response().end(
                                directoryTemplate.replace("{title}", (String) request.get("title")).replace("{directory}", normalizedDir)
                                        .replace("{linked-path}", directory.toString())
                                        .replace("{files}", files.toString()));
                    } else if (accept.contains("json")) {
                        String file;
                        JsonArray json = new JsonArray();

                        for (String s : asyncResult.result()) {
                            file = s.substring(s.lastIndexOf('/') + 1);
                            // skip dot files
                            if (!includeHidden && file.charAt(0) == '.') {
                                continue;
                            }
                            json.add(file);
                        }

                        request.response().end(json);
                    } else {
                        String file;
                        StringBuilder buffer = new StringBuilder();

                        for (String s : asyncResult.result()) {
                            file = s.substring(s.lastIndexOf('/') + 1);
                            // skip dot files
                            if (!includeHidden && file.charAt(0) == '.') {
                                continue;
                            }
                            buffer.append(file);
                            buffer.append('\n');
                        }

                        request.response().setContentType("text/plain");
                        request.response().end(buffer.toString());
                    }
                }
            }
        });
    }
605475
function processFileResponse(req, res, next) {
  var fileDetails = req.appformsResultPayload.data;
  if (fileDetails.stream) {
    var headers = {};
    headers["Content-Type"] = fileDetails.type;//Setting the file content type. Mime types are set by the file handler.
    headers["Content-Disposition"] = "attachment; filename=" + fileDetails.name;
    res.writeHead(200, headers);
    fileDetails.stream.pipe(res);
    fileDetails.stream.resume(); //Unpausing the stream as it was paused by the file handler
  } else {
    return next('Error getting submitted file - result: ' + JSON.stringify(fileDetails));
  }
}
553739
function handleUserMe(req, res, next) {
		Promise.resolve(req.locals.user || {})
		.then(function (me) {
			debug(`Handling user/me request for ${me.display_name}.`);
			res.json({
				me
			});
			next();
		}).catch(function (err) {
			debug(`Error during user/me request`, err);
			next(err);
		});
	}
785636
function execute(req, res) {
  var t = systime();
  res.send(null, [t.s, t.m]);
}
1085153
function execute(req, res) {
  var proxy = req.exec ? req.exec.proxy : this.proxy;
  res.send(null, proxy(req, res));
}