Install specified middleware
962818
def install_middleware(middleware_name, lookup_names=None):
    
    if lookup_names is None:
        lookup_names = (middleware_name,)
    # default settings.MIDDLEWARE is None
    middleware_attr = 'MIDDLEWARE' if getattr(settings,
                                              'MIDDLEWARE',
                                              None) is not None \
        else 'MIDDLEWARE_CLASSES'
    # make sure to get an empty tuple when attr is None
    middleware = getattr(settings, middleware_attr, ()) or ()
    if set(lookup_names).isdisjoint(set(middleware)):
        setattr(settings,
                middleware_attr,
                type(middleware)((middleware_name,)) + middleware)
1053745
def _local_install(self, args, pkg_name=None):
        '''
        
        '''
        if len(args) < 2:
            raise SPMInvocationError('A package file must be specified')

        self._install(args)
446940
function bindMiddlewares() {
		var modelName,
			_this = this;

		for(modelName in Rhapsody.models) {

			(function(model) {

				model.options.middlewares.forEach(function(middleware) {
					if(typeof middleware !== 'function') {
						middleware = require(path.join(Rhapsody.root, '/app/middlewares/' + middleware));
					}

					modelName = '/' + modelName;

					_this.router.post(modelName, middleware);
					_this.router.post(modelName + '/:id/:relationship', middleware);
					_this.router.get(modelName + '/:id?', middleware);
					_this.router.get(modelName + '/:id/:relationship', middleware);
					_this.router.put(modelName + '/:id', middleware);
					_this.router.patch(modelName + '/:id', middleware);
					_this.router.delete(modelName + '/:id', middleware);
				});

			}(Rhapsody.models[modelName]));
		}
	}
1091943
function (uses, payload, message, callback) {
        executeMiddlewares(uses, payload, message, function (newPayload) {
            callback.apply(undefined, [newPayload]);
        });
    }
814799
protected function setupMiddleware() {
        $this->middleware('antares.auth');
        $this->middleware('antares.manage');
        $this->middleware('antares.csrf');

        $this->canMiddleware('install');
        $this->canMiddleware('uninstall');
        $this->canMiddleware('activate');
        $this->canMiddleware('deactivate');
    }
1108586
function createMiddleware(options) {
  /**
   * Express middleware handling raw content 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;
    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);
    }

    // project-helix/#187: serve modified content only if the requested ref is currently checked out
    isCheckedOut(repPath, refName)
      .then(serveUncommitted => resolveBlob(repPath, refName, fpath, serveUncommitted))
      .then((oid) => {
        const mimeType = mime.getType(fpath) || 'text/plain';
        res.writeHead(200, {
          'Content-Type': mimeType,
          ETag: oid,
          // TODO: review cache-control header
          'Cache-Control': 'max-age=0, private, must-revalidate',
        });
        createBlobReadStream(repPath, oid)
          .then(stream => stream.pipe(res));
      })
      .catch((err) => {
        // TODO: use generic errors
        if (err.code === 'TreeOrBlobNotFoundError' || err.code === 'ResolveRefError') {
          options.logger.debug(`[rawHandler] resource not found: ${err.message}`);
          res.status(404).send('not found.');
        } else {
          options.logger.debug(`[rawHandler] code: ${err.code} message: ${err.message} stack: ${err.stack}`);
          next(err);
        }
      });
  };
}
1355740
public function addMiddleware($middleware, $priority = PriorityQueue::NORMAL)
    {
        if (is_array($middleware) && isset($middleware['priority'])) {
            $priority = $middleware['priority'];
        }

        $this->getMiddlewares()->insert($middleware, $priority);

        return $this;
    }
87493
function createMiddleware(options) {
  /**
   * Express middleware handling Git API Blob requests
   *
   * Only a small subset will be implemented
   *
   * @param {Request} req Request object
   * @param {Response} res Response object
   * @param {callback} next next middleware in chain
   *
   * @see https://developer.github.com/v3/git/trees/#get-a-tree-recursively
   */
  return (req, res, next) => {
    // GET /repos/:owner/:repo/git/trees/:ref_or_sha?recursive
    const { owner } = req.params;
    const repoName = req.params.repo;
    const refOrSha = req.params.ref_or_sha;
    const recursive = typeof req.query.recursive !== 'undefined' && req.query.recursive !== '';
    const host = req.mappedSubDomain ? `localhost:${options.listen[req.protocol].port}` : req.headers.host;

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

    async function dirEntryToJson({
      oid: sha, type, path, mode,
    }) {
      return {
        path,
        mode,
        type,
        sha,
        url: `${req.protocol}://${host}/api/repos/${owner}/${repoName}/git/trees/${sha}`,
      };
    }

    async function fileEntryToJson({
      oid: sha, type, path, mode,
    }) {
      const { object: content } = await getObject(repPath, sha);

      return {
        path,
        mode,
        type,
        sha,
        size: content.length,
        url: `${req.protocol}://${host}/api/repos/${owner}/${repoName}/git/blobs/${sha}`,
      };
    }

    async function collectTreeEntries(tree, result, treePath, deep) {
      const entries = tree.entries.map(({
        oid, type, mode, path,
      }) => {
        return {
          oid, type, mode, path: joinPaths(treePath, path),
        };
      });
      result.push(...entries);
      if (deep) {
        const treeEntries = entries.filter(entry => entry.type === 'tree');
        for (let i = 0; i < treeEntries.length; i += 1) {
          const { oid, path } = treeEntries[i];
          /* eslint-disable no-await-in-loop */
          const { object: subTree } = await getObject(repPath, oid);
          await collectTreeEntries(subTree, result, path, deep);
        }
      }
      return result;
    }

    async function treeEntriesToJson(tree, deep) {
      const result = [];
      await collectTreeEntries(tree, result, '', deep);
      return Promise.all(result.map(async (entry) => {
        /* eslint arrow-body-style: "off" */
        return entry.type === 'blob'
          ? fileEntryToJson(entry) : dirEntryToJson(entry);
      }));
    }

    resolveTree(repPath, refOrSha)
      .then(async ({ oid: sha, object: tree }) => {
        res.json({
          sha,
          url: `${req.protocol}://${host}/api/repos/${owner}/${repoName}/git/trees/${sha}`,
          tree: await treeEntriesToJson(tree, recursive),
          truncated: false,
        });
      })
      .catch((err) => {
        // TODO: use generic errors
        if (err.code === 'ReadObjectFail' || err.code === 'ResolveRefError') {
          options.logger.debug(`[treeHandler] resource not found: ${err.message}`);
          res.status(404).json({
            message: 'Not Found',
            documentation_url: 'https://developer.github.com/v3/git/trees/#get-a-tree',
          });
        } else {
          options.logger.debug(`[treeHandler] code: ${err.code} message: ${err.message} stack: ${err.stack}`);
          next(err);
        }
      });
  };
}
1334851
function createDefaultMiddleware(connect, options) {
    var middlewares = [];
    if (!Array.isArray(options.base)) {
      options.base = [options.base];
    }
    var directory = options.directory || options.base[options.base.length - 1];
    options.base.forEach(function(base) {
      // Serve static files.
      middlewares.push(connect.static(base));
    });
    // Make directory browse-able.
    middlewares.push(connect.directory(directory));
    return middlewares;
  }
1029008
function toHaveMiddleware(middleware) {
    
    expect(this.actual).toExist('Route is undefined');
    toBeAnExpressRoute(this.actual.route);
    expect(this.actual.route.stack.length).toBeGreaterThan(1, 'No middleware found');
    if(expressGuards.isMiddleware(middleware)) {
        expect(this.actual.route.stack.find(l => l.handle.toString() === middleware.toString())).toExist(`middleware is not defined`);
    } else {
        const name = middleware || '<anonymous>';
        expect(this.actual.route.stack.find(l => l.name === name)).toExist(`${name} is not defined`);
    }
}
71345
function (engine, fn, opts) {
                if (typeof engine === 'function') {
                    opts = fn;
                    fn = engine;
                    engine = null;
                }

                if (fn.length === 1) {
                    fn = fn.call(expressBem, opts);
                }

                ASSERT(fn.call, 'Invalid middleware');

                middlewares.push({
                    engine : engine,
                    fn     : fn
                });

                return this;
            }
1055579
async function createApp(middlewareConfig) {
  const app = new Koa()

  const middleware = await setupMiddleware(middlewareConfig, app)

  if (app.env == 'production') {
    app.proxy = true
  }

  return {
    app,
    middleware,
  }
}
971543
function createDefaultMiddleware(connect, options) {
					var middlewares = [];

					var directory = options.directory || options.base;
					// Serve static files.
					middlewares.push(serveStatic(options.base));
					// Make directory browse-able.
					middlewares.push(serveIndex(directory));
					return middlewares;
				}
405752
function (req, res, next) {
                // Delayed resolution of the isLoggedIn middleware.
                if (server.registry.has('localUserMiddleware')) {
                    const middleware = server.registry.get('localUserMiddleware');
                    middleware.isLoggedInMiddleware()(req, res, next);
                } else {
                    next(new restifyErrors.ForbiddenError(`Server configuration error, 'localUserMiddleware' not found.`));
                }
            }
851126
function getMiddlewareWrapper( middleware ) {
	return function ( req, res, next ) {
		try {
			middleware( req, res, next );
		}
		catch ( e ) {
			getResponder( req, res )( 500 );
		}
	};
}
206850
function createMiddleware(options) {
  /**
   * Express middleware handling Git API Commits requests
   *
   * Only a small subset will be implemented
   *
   * @param {Request} req Request object
   * @param {Response} res Response object
   * @param {callback} next next middleware in chain
   *
   * @see https://developer.github.com/v3/repos/commits/#list-commits-on-a-repository
   */
  return (req, res, next) => {
    // GET /repos/:owner/:repo/commits/?path=:path&sha=:sha
    const { owner } = req.params;
    const repoName = req.params.repo;
    const sha = req.query.sha || 'master';
    let fpath = req.query.path || '';

    // TODO: support filtering (author, since, until)
    // const { author, since, until } = req.query;

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

    if (typeof fpath !== 'string') {
      res.status(400).send('Bad request');
      return;
    }
    // issue #247: lenient handling of redundant leading slashes in path
    while (fpath.length && fpath[0] === '/') {
      // trim leading slash
      fpath = fpath.substr(1);
    }

    const NOT_IMPL = 'not implemented';

    function email2avatarUrl(email) {
      const hash = crypto.createHash('md5').update(email).digest('hex');
      return `https://s.gravatar.com/avatar/${hash}`;
    }

    commitLog(repPath, sha, fpath)
      .then((commits) => {
        const host = req.mappedSubDomain ? `localhost:${options.listen[req.protocol].port}` : req.headers.host;
        const result = [];
        commits.forEach((commit) => {
          const parents = [];
          commit.parent.forEach(oid => parents.push({
            sha: oid,
            url: `${req.protocol}://${host}/api/repos/${owner}/${repoName}/commits/${oid}`,
            html_url: `${req.protocol}://${host}/repos/${owner}/${repoName}/commit/${oid}`,
          }));
          result.push({
            sha: commit.oid,
            node_id: NOT_IMPL,
            commit: {
              author: {
                name: commit.author.name,
                email: commit.author.email,
                date: new Date(commit.author.timestamp * 1000).toISOString(),
              },
              committer: {
                name: commit.committer.name,
                email: commit.committer.email,
                date: new Date(commit.committer.timestamp * 1000).toISOString(),
              },
              message: commit.message,
              tree: {
                sha: commit.tree,
                url: `${req.protocol}://${host}/api/repos/${owner}/${repoName}/git/trees/${commit.tree}`,
              },
              url: `${req.protocol}://${host}/api/repos/${owner}/${repoName}/git/commits/${commit.oid}`,
              comment_count: 0,
              verification: {
                verified: false,
                reason: NOT_IMPL,
                signature: NOT_IMPL,
                payload: NOT_IMPL,
              },
            },
            // TODO
            url: `${req.protocol}://${host}/api/repos/${owner}/${repoName}/commits/${commit.oid}`,
            html_url: `${req.protocol}://${host}/repos/${owner}/${repoName}/commit/${commit.oid}`,
            comments_url: `${req.protocol}://${host}/api/repos/${owner}/${repoName}/commits/${commit.oid}/comments`,
            author: {
              avatar_url: email2avatarUrl(commit.author.email),
              gravatar_id: '',
              // TODO
            },
            committer: {
              avatar_url: email2avatarUrl(commit.committer.email),
              gravatar_id: '',
              // TODO
            },
            parents,
          });
        });
        res.json(result);
      })
      .catch((err) => {
        options.logger.debug(`[commitHandler] code: ${err.code} message: ${err.message} stack: ${err.stack}`);
        next(err);
        // github seems to swallow errors and just return an empty array...
        // res.json([]);
      });
  };
}
969021
function middleware(doIt, req, res) {
  const originalEnd = res.end;

  return new Promise(resolve => {
    res.end = function end(...args) {
      originalEnd.apply(this, args);
      resolve(0);
    };
    doIt(req, res, () => {
      resolve(1);
    });
  });
}