Taken from http://stackoverflow.com/questions/11709865/nodejs-express-connect-dynamically-add-middleware-in-current-flow
174853
function (stack, req, res, next) {

  if (typeof stack === 'function') {
    stack = [stack];
  }

  var walkStack = function (i, err) {

    if (err) {
      return next(err);
    }

    if (i >= stack.length) {
      return next();
    }

    stack[i](req, res, walkStack.bind(null, i + 1));

  };

  walkStack(0);

}
968211
function middlewareFunction (req,res,next){

  return ipToLocation(req.ip)
    .then(function (location) {
      req.location = location;
      next();
    })
    .catch(function (error) {
      req.locationError = error;
      next();
    })

}
569953
function configureExpress() {

	// create configuration routes
	moduleConfig.express.get( /^\/conf.*/, checkAuth, getPath, getMiddlewareWrapper( onGetConf ) );
	moduleConfig.express.post( /^\/conf.*/, storeRequestBody, checkAuth, getPath, getMiddlewareWrapper( onPostConf ) );
	moduleConfig.express.delete( /^\/conf.*/, checkAuth, getPath, getMiddlewareWrapper( onDeleteConf ) );

	// create auth management routes
	moduleConfig.express.post( "/auth", checkAuth, getMiddlewareWrapper( onPostAuth ) );
	moduleConfig.express.delete( "/auth", checkAuth, getMiddlewareWrapper( onDeleteAuth ) );

}
165911
function connectIfNeeded() {
      // console.log('re-establishing the connect');
      websocket = null;
      socketCreationInProcess = false;

      // The token may have expired so test for it.
      getToken(determineService())
        .then(() => {
          return processSTTSocketStart(false);
        })
        .then(() => {
          //return Promise.resolve();
          return;
        })
        .catch((err) => {
          //return Promise.resolve();
          return;
        });
    }
1333707
function connect() {
  console.log('Connecting client: ' + clientId + ' to url:"' + url + '"');
  client = mqtt.connect(url, { 'clientId': clientId });
}
1288192
function createMiddleware(options, archiveFormat) {
  /**
   * Express middleware handling GitHub API archive link requests
   *
   * @param {Request} req Request object
   * @param {Response} res Response object
   * @param {callback} next next middleware in chain
   *
   * @see https://developer.github.com/v3/repos/contents/#get-archive-link
   */
  return (req, res) => {
    // GET /repos/:owner/:repo/:archive_format/:ref
    const { owner } = req.params;
    const repoName = req.params.repo;
    const refName = req.params.ref || 'master';

    const host = req.mappedSubDomain ? `localhost:${options.listen[req.protocol].port}` : req.headers.host;
    const location = `${req.protocol}://${host}/codeload/${owner}/${repoName}/${archiveFormat}/${refName}`;

    res.writeHead(302, {
      Location: location,
    });
    res.end();
  };
}
376875
function Middleware(...middleware) {
    return (ctr) => {
        if (middleware != undefined) {
            let c = exports.globalKCState.getOrInsertController(ctr);
            c.middleware = middleware.concat(c.middleware);
        }
    };
}
379444
function contextMiddleware(req, res, next) {
  const currentDomain = domain.create();

  currentDomain.context = requestContext(req);
  currentDomain.logger = createLogger(req);
  res.locals.logger = currentDomain.logger.createChildLogger('http');

  currentDomain.run(next);
}
732357
function CoreApplication() {
  var preHookList = [];
  var postHookList = [];
  var routers = [];

  /**
   * Method that receive all http requests
   * @param request
   * @param response
   * @returns {Promise}
   */
  this.requestListener = function (request, response) {
    return Promise.resolve()
      .then(postDecode.bind(this, request))
      .then(runHooks.bind(this, request, response, preHookList))
      .then(dispatch.bind(this, request, response))
      .then(runHooks.bind(this, request, response, postHookList))
      .then(endResponse.bind(this, response))
      .catch(this.onError.bind(this, request, response));
  };

  /**
   * Add router to resolve uri
   * @param router
   * @returns {CoreApplication}
   */
  this.addRouter = function (router) {
    routers.push(router);
    return this;
  };

  /**
   * Add hook before calling action
   * @param callableHook
   * @returns {CoreApplication}
   */
  this.addPreHook = function (callableHook) {
    if (typeof callableHook !== 'function') {
      this.error('Post hook is not callable');
    }
    preHookList.push(callableHook);
    return this;
  };

  /**
   * Add hook after calling action
   * @param callableHook
   * @returns {CoreApplication}
   */
  this.addPostHook = function (callableHook) {
    if (typeof callableHook !== 'function') {
      this.error('Post hook is not callable');
    }
    postHookList.push(callableHook);
    return this;
  };

  /**
   * If page not found
   * @param request
   * @param response
   * @param error
   * @returns {CoreApplication}
   */
  this.onPageNotFound = function (request, response, error) {
    console.log(error);
    response.writeHead(404);
    response.end();
    return this;
  };

  /**
   * If an error occured
   * @param request
   * @param response
   * @param error
   * @returns {CoreApplication}
   */
  this.onError = function (request, response, error) {
    console.error(error);
    response.writeHead(503);
    response.end();
    return this;
  };

  return this;

  /**
   * Dispatch request in good action using routers
   * @param request
   * @param response
   * @returns {Promise}
   */
  function dispatch(request, response) {
    return Promise.resolve()
      .then(resolveRouters.bind(this, request))
      .then(callAction.bind(this, request, response));
  }

  /**
   * Resolve uri using routers
   * @param request
   * @returns {Promise}
   */
  function resolveRouters(request) {
    for (var i = 0, l = routers.length; i < l; i++) {
      var callback = routers[i].resolve(request);
      if (null != callback) {
        return Promise.resolve(callback);
      }
    }
    return Promise.reject('Route not defined for "' + request.url + '"');
  }

  /**
   * Call action and method form resolved route
   * @param request
   * @param response
   * @param callback
   * @returns {*}
   */
  function callAction(request, response, callback) {
    if (typeof callback == 'function') {
      return Promive.resolve()
        .then(callback.bind(null, request, response));
    }

    try {
      var Action = require(ACTION_PATH + '/' + callback.action + '.js');
    } catch (error) {
      if (error.message == 'Cannot find module \'' + ACTION_PATH + '/' + callback.action + '.js\'') {
        return Promise.reject('Action ' + callback.action + ' does not exist.')
          .catch(this.onPageNotFound.bind(this, request, response));
      }
      return Promise.reject(error)
        .catch(this.onError.bind(this, request, response));
    }

    var instance = new Action(request, response);
    // Test if method exists
    if (!instance[callback.method]) {
      return Promise.reject(new Error('Method "' + callback.method + '" not found in action "' + callback.action + '"'));
    }

    var promise = Promise.resolve();
    if (instance.init && 'function' == typeof instance.init) {
      promise = promise.then(function () {
        return instance.init();
      });
    }

    promise = promise.then(function () {
      return instance[callback.method].apply(instance, callback.arguments);
    });

    if (instance.onError && 'function' == typeof instance.onError) {
      promise = promise.catch(function (error) {
        return instance.onError.call(instance, error)
      });
    }

    promise = promise.catch(this.onError.bind(this, request, response));

    return promise;
  }

  /**
   * Decode post data and add input into request
   * @param request
   * @returns {Promise}
   */
  function postDecode(request) {
    return new Promise(function promisePostDecode(resolve) {
      var postData = '';
      if (request.method === 'POST') {
        request.on('data', function (chunk) {
          // append the current chunk of data to the fullBody variable
          postData += chunk.toString();
        });

        request.on('end', function () {
          request.body = qs.parse(postData);
          resolve();
        });

      } else {
        resolve();
      }
    });
  }

  /**
   * Run given hooks
   * @param request
   * @param response
   * @param hooks
   * @returns {Promise}
   */
  function runHooks(request, response, hooks) {
    var promise = Promise.resolve();
    for (var i = 0; i < hooks.length; i++) {
      promise = promise.then(hooks[i].bind(this, request, response));
    }
    return promise;
  }

  /**
   * Finalize response
   * @param response
   */
  function endResponse(response) {
    response.end();
  }
}
14685
function middlewareStrategy(metadata, dataAdapter, opts) {
    opts.filter = opts.filter || defaultFilter;
    const { filter } = opts;
    return async function magic(ctx, next) {
        const { name, key } = opts.filter.call(null, ctx);
        const obj = metadata[name];
        const { routeSwitch = {} } = obj;

        let middleware;
        if (routeSwitch[key] === true) {
            const { pres, posts } = getHooks(obj, key);
            const route = routes[key];
            middleware = route.call(null, name, dataAdapter, opts, pres, posts);
        }

        try {
            if (typeof middleware === 'function') {
                await middleware.call(null, ctx, next);
            } else {
                await next();
            }
        } catch (err) {
            throw err;
        }
    }
}
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();
    });
  }
986441
function PushWrapper() {
    // Autobahn|JS connection object for push API (utilizes the WAMP protocol)
    this._connection = new autobahn.Connection({
        "url": POLONIEX_PUSH_URL,
        "realm": POLONIEX_PUSH_REALM
    });

    // Internally-routed callback sets for connection management events
    this._cxnCallbacksOpen = new Array();
    this._cxnCallbacksClose = new Array();

    // Internal lookup table for linking subscriptions to callbacks
    this._subLinks = {};
    this._subLinksId = 0;

    // Number of currently active subscriptions
    this._activeSubs = 0;

    // Handle connection open event
    this._connection.onopen = (session) => {
        // Loop through all open callbacks
        for (let i = 0; i < this._cxnCallbacksOpen.length; i++) {
            this._cxnCallbacksOpen[i](session);
        }
    };

    // Handle connection close event
    this._connection.onclose = (reason, details) => {
        // Loop through all close callbacks
        for (let i = 0; i < this._cxnCallbacksClose.length; i++) {
            this._cxnCallbacksClose[i](reason, details);
        }
    };
}
907701
function runMiddlewareStack(stack, req, res, callback) {
  let index = 0;
  // the middleware layer handover callback
  function next(err) {
    // get next middleware callback from stack
    const handle = stack[index++];
    // if no more layers in stack, invoke done callback and exit recursion
    if (!handle) {
      callback(err);
      return;
    }
    let error = err;
    // call the middleware handler
    try {
      if (err && handle.length === 4) {
        // there is an error and it's an error-handling middleware
        handle(err, req, res, next);
        return;
      } else if (!err && handle.length < 4) {
        // no error and it's a request-handling middleware
        handle(req, res, next);
        return;
      }
    } catch (e) {
      // if new error thrown, replace the error
      error = e;
    }
    // otherwise skip layer
    next(error);
  }
  // start going through middleware stack
  next();
}
945986
function createInternalConnection (mode) {

  var result;

  switch (mode) {
    case 'async':
      result = require('then-request');
      break;
    case 'sync':
      result = require('sync-req');
      break;
    default:
      throw new Error('Expected options.mode to be "async" or "sync" but got ' + JSON.stringify(mode));
  }

  return result;
}
926182
function callRequestMiddleware(arg2, arg3) {
        i += 1;
        if (i < self.middlewares.length) {
            var next = self.middlewares[i].request;
            if (typeof next === 'function') {
                next(req, arg2, arg3, callRequestMiddleware);
            } else {
                // skip this middleware if it doesn't implement request
                callRequestMiddleware(arg2, arg3);
            }
        } else {
            handler(req, arg2, arg3, callResponseMiddleware);
        }
    }
1301141
function createMiddleware(options, urlType) {
  /**
   * Express middleware handling html requests
   *
   * @param {Request} req Request object
   * @param {Response} res Response object
   * @param {callback} next next middleware in chain
   */
  return async (req, res, next) => {
    const { owner } = req.params;
    const repoName = req.params.repo;
    let refName = req.params.ref || 'master';
    let fpath = req.params[0] || '';

    const repPath = resolveRepositoryPath(options, owner, repoName);

    // issue: #53: handle branch names containing '/' (e.g. 'foo/bar')
    const parsed = await determineRefPathName(repPath, `${req.params.ref}/${req.params[0]}`);
    if (parsed) {
      refName = parsed.ref;
      fpath = parsed.pathName;
    }

    // issue #247: lenient handling of redundant leading slashes in path
    while (fpath.length && fpath[0] === '/') {
      // trim leading slash
      fpath = fpath.substr(1);
    }

    // set response content type
    res.header('Content-Type', 'text/html');

    resolveCommit(repPath, refName)
      .then(commitOid => git.readObject({ dir: repPath, oid: commitOid, filepath: fpath })
        .catch(() => null))
      .then((blobOrTree) => {
        if (!blobOrTree) {
          if (!fpath.length && urlType === 'tree') {
            // 'tree' view
            res.send(`<!DOCTYPE html><html><body>owner: ${escape(owner)}<br>repo: ${escape(repoName)}<br>ref: ${escape(refName)}<p>tree view not implemented yet.</body></html>`);
          } else {
            res.status(404).send(`not found: ${escape(fpath)}`);
          }
          return;
        }

        const { type } = blobOrTree;
        if (!fpath.length && type === 'tree' && urlType === 'root') {
          // 'root' view
          res.send(`<!DOCTYPE html><html><body>owner: ${escape(owner)}<br>repo: ${escape(repoName)}<br>ref: ${escape(refName)}<p>root view not implemented yet.</body></html>`);
        } else if (type === 'tree' && urlType === 'tree') {
          // directory view
          res.send(`<!DOCTYPE html><html><body>owner: ${escape(owner)}<br>repo: ${escape(repoName)}<br>ref: ${escape(refName)}<br>path: ${escape(fpath)}<p>directory view not implemented yet.</body></html>`);
        } else if (type === 'blob' && urlType === 'blob') {
          // single file view
          res.send(`<!DOCTYPE html><html><body>owner: ${escape(owner)}<br>repo: ${escape(repoName)}<br>ref: ${escape(refName)}<br>path: ${escape(fpath)}<p>file view not implemented yet.</body></html>`);
        } else {
          res.status(404).send(`not found: ${escape(fpath)}`);
        }
      })
      .catch((err) => {
        options.logger.debug(`[htmlHandler] code: ${err.code} message: ${err.message} stack: ${err.stack}`);
        next(err);
      });
  };
}
785349
function(connect, options) {
            var base = "./";//(typeof options.base == "string") ? options.base : options.base[0];
            if (!Array.isArray(options.base)) {
                options.base = [options.base];
            }
            var base = path.resolve(options.base[0]);
            //return [serveStatic(base),serveIndex(base)];
            return [
                // connect.compress({
                //     level: 9
                // }),
                //require('connect-livereload')(),
                function(req, res, next) {
                    if (req.headers.origin === undefined) {
                        res.setHeader('Access-Control-Allow-Origin', "*");
                    } else {
                        res.setHeader('Access-Control-Allow-Origin', req.headers.origin);
                    }
                    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
                    console.log(req.method + " on " + req.originalUrl);
                    if (req.method === "OPTIONS") {
                        res.setHeader('Access-Control-Allow-Headers', 'content-type');
                        res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
                        res.setHeader('Content-Length', '0');
                        res.setHeader('Content-Type', 'application/json; charset=utf-8');
                        grunt.file.read(req.originalUrl.split("?")[0]);
                        //res.write(body);
                        res.end("200");
                        //next();
                    } else {
                        next();
                    }
                },
                serveStatic(base),
                function(req, res, next) {
                    if (showIndex(req.originalUrl)) {
                        var body = grunt.file.read("index.html");
                        res.write(body);
                        res.end();
                    } else {
                        res.setHeader('Access-Control-Allow-Headers', 'content-type');
                        res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
                        //res.setHeader('Content-Length', '0');
                        res.setHeader('Content-Type', 'application/json; charset=utf-8');
                        datahandler(req, res, STUBS_URL, function() {
                            console.log("first end");
                            res.end();
                            //next();
                        });
                    }
                },
                function(req, res, next) {
                    if (req.headers.origin === undefined) {
                        res.setHeader('Access-Control-Allow-Origin', "*");
                    } else {
                        res.setHeader('Access-Control-Allow-Origin', req.headers.origin);
                    }
                    if (showIndex(req.originalUrl)) {
                        var body = grunt.file.read("index.html");
                        res.write(body);
                        console.log("2nd end");
                        res.end();
                    } else {
                        next();
                    }
                },
                serveIndex(base)
            ];
        }