Grape middleware methods
323853
def before
      set_auth_strategy(GrapeSimpleAuth.auth_strategy)
      auth_strategy.api_context = context
      context.extend(GrapeSimpleAuth::AuthMethods)

      context.protected_endpoint = endpoint_protected?
      context.optional_endpoint = optional_endpoint?

      return unless context.protected_endpoint? || context.optional_endpoint?
      
      self.the_request = env
      
      if token.present? && (context.protected_endpoint? || context.optional_endpoint?)
        resp = authorize!(*auth_scopes)
        context.the_access_token = token
        context.current_user = resp.parsed_response["data"]["info"] rescue nil
        context.credentials = resp.parsed_response["data"]["credential"] rescue nil
      elsif token.nil? && context.protected_endpoint?
        raise GrapeSimpleAuth::Errors::InvalidToken
      end
    end
345357
function compose () {
  // the function required by the server
  function middlewareF (req, res, end) {
    var index = 0

    // inject stats middleware
    if (middlewareF.options && middlewareF.options.stats) {
      middlewareF.stack = middlewareF.stack.map(function (mw) {
        var fn
        if (typeof mw === 'object') {
          var key = Object.keys(mw)[0]
          if (!mw[key].stats) {
            fn = {}
            fn[key] = middlewareF.options.stats(mw[key])
          }
        } else {
          if (!mw.stats) {
            fn = middlewareF.options.stats(mw)
          }
        }
        return fn
      })
    }

    // looping over all middleware functions defined by stack
    ;(function next (err) {
      var arity
      var middleware = middlewareF.stack[index++] // obtain the current middleware from the stack

      if (!middleware) {
        // we are at the end of the stack
        end && end(err)
        return
      } else {
        // extract middleware from object
        if (typeof (middleware) === 'object') {
          var name = Object.keys(middleware)[0]
          if (typeof (middleware[name]) === 'function') {
            middleware = middleware[name]
          } else {
            middleware = function (req, res, next) {
              next(new Error('missing middleware'))
            }
          }
        }

        try {
          arity = middleware.length // number of arguments function middleware requires
          // handle errors
          if (err) {
            // If the middleware function contains 4 arguments than this will act as an "error trap"
            if (arity === 4) {
              middleware(err, req, res, function (err) {
                nextTick(next, err)
              })
            } else {
              // otherwise check the next middleware
              next(err)
            }
          } else if (arity < 4) {
            // process non "error trap" stack
            middleware(req, res, function (err) {
              nextTick(next, err)
            })
          } else {
            // loop over "error traps" if no error `err` is set.
            next()
          }
        } catch (e) {
          next(e)
        }
      }
    })()
  }

  middlewareF.stack = []
  middlewareF.options = compose.options || {}

  ;[].slice.call(arguments).forEach(function (a) {
    middlewareF.stack = middlewareF.stack.concat(compose.decompose(a))
  })

  // extends
  ;[ 'before', 'after', 'replace', 'remove', 'push', 'unshift', 'clone' ].forEach(function (p) {
    middlewareF[p] = compose[p]
  })

  // inject stats middleware
  if (compose.options.stats) {
    middlewareF.options = {}
    middlewareF.options.stats = compose.options.stats
  }

  return middlewareF
}
1113819
def middleware(func):
    
    @wraps(func)
    def parse(*args, **kwargs):
        """ get middleware from route, execute middleware in order """
        middleware = copy.deepcopy(kwargs['middleware'])
        kwargs.pop('middleware')
        if request.method == "OPTIONS":
            # return 200 json response for CORS
            return JsonResponse(200)
        if middleware is None:
            return func(*args, **kwargs)
        for mware in middleware:
            ware = mware()
            if ware.status is False:
                return ware.response
            return func(*args, **kwargs)
    return parse
1273901
function callMiddlewares(actionName, actionData, done) {
    let store = this;
    let index = -1;
    /**
     * Call next middleware or done
     * @function next
     * @param {*} actionData - An action data
     */
    function next(actionData) {
        index++;
        if(index === store.middlewares.length) {
            done(actionData);
        } else {
            store.middlewares[index](store, actionName, actionData, next);
        }
    }
    next(actionData);
}
830170
function middleware(schema, options = optionsDefault) {
    return (req, res, next) => {
        // Test if schema exists
        /* istanbul ignore if */
        if (!schema) {
            next();
        }

        // Test if Joi is provided
        const Joi = options.joi || require('joi');

        // Object to validate
        const objectToValidate = {};
        ['params', 'body', 'query', 'headers'].forEach((key) => {
            if (schema[key]) {
                objectToValidate[key] = req[key];
            }
        });

        // Get joi options
        const joiOptions = options.joiOptions || {};

        // Get callback
        const callback = options.validationCallback || validationCallback;

        return Joi.validate(objectToValidate, schema, joiOptions, callback(req, res, next, options));
    };
}
677989
function Stack (middleware, context) {
  var handle = function (args, next) { next.call(context) }
  middleware.reverse().forEach(function (layer) {
    var child = handle
    handle = function (args, next) {
      layer(args, function () {
        child(args, next)
      })
    }
  })
  return handle
}
1151191
@Override
	public void use(Collection<Middleware> middlewares) {
		LinkedList<Middleware> newMiddlewares = new LinkedList<>();
		final long stamp = lock.writeLock();
		try {

			// Register middlewares
			for (Middleware middleware : middlewares) {
				if (this.middlewares.add(middleware)) {
					newMiddlewares.add(middleware);
				}
			}

			// Apply new middlewares
			if (!newMiddlewares.isEmpty()) {
				for (Strategy<ActionEndpoint> strategy : strategies.values()) {
					List<ActionEndpoint> endpoints = strategy.getAllEndpoints();
					for (ActionEndpoint endpoint : endpoints) {
						for (Middleware middleware : newMiddlewares) {
							endpoint.use(middleware);
						}
					}
				}
			}

		} finally {
			lock.unlockWrite(stamp);
		}

		// Start new middlewares
		if (!newMiddlewares.isEmpty()) {
			for (Middleware middleware : newMiddlewares) {
				try {
					middleware.started(broker);
				} catch (MoleculerError moleculerError) {
					throw moleculerError;
				} catch (Exception cause) {
					throw new MoleculerError("Unable to start middleware!", cause, "MoleculerError", nodeID, false, 500,
							"MIDDLEWARE_ERROR");
				}
			}
		}
	}
1111630
def combine_middlewares(middlewares, web3, provider_request_fn):
    
    return functools.reduce(
        lambda request_fn, middleware: middleware(request_fn, web3),
        reversed(middlewares),
        provider_request_fn,
    )
834361
def setup(self, middleware):
        
        if not isinstance(middleware, BaseMiddleware):
            raise TypeError(f"`middleware` must be an instance of BaseMiddleware, not {type(middleware)}")
        if middleware.is_configured():
            raise ValueError('That middleware is already used!')

        self.applications.append(middleware)
        middleware.setup(self)
        log.debug(f"Loaded middleware '{middleware.__class__.__name__}'")
        return middleware
1360965
def _call_one_middleware(self, middleware):
        '''  '''
        args = {}
        for arg in middleware['args']:
            if hasattr(self, arg):
                # same as eval() but safer for arbitrary code execution
                args[arg] = reduce(getattr, arg.split('.'), self)
        self.logger.debug('calling middleware event {}'
                          .format(middleware['name']))
        middleware['call'](**args)
1143787
function compose (middleware) {
  if (!Array.isArray(middleware)) throw new TypeError('Middleware stack must be an array!')
  for (const fn of middleware) {
    if (typeof fn !== 'function') throw new TypeError('Middleware must be composed of functions!')
  }

  /**
   * @param {Object} context
   * @return {Promise}
   * @api public
   */

  return function (context, next) {
    // last called middleware #
    let index = -1
    return dispatch(0)
    function dispatch (i) {
      if (i <= index) return Promise.reject(new Error('next() called multiple times'))
      index = i
      let fn = middleware[i]
      if (i === middleware.length) fn = next
      if (!fn) return Promise.resolve()
      try {
        return Promise.resolve(fn(context, dispatch.bind(null, i + 1)))
      } catch (err) {
        return Promise.reject(err)
      }
    }
  }
}
212098
function middleware3() {
	return function mw3(handler) {

		return async function mw3(ctx) {
			broker.logger.info(chalk.cyan("mw3 before", ctx.action.name));
			//return broker.Promise.resolve("data from mw3");
			const res = await handler(ctx);
			broker.logger.info(chalk.cyan("mw3 after", ctx.action.name));
			if (res) {
				if (ctx.action.name == "users.get")
					delete res.gravatar;
				if (ctx.action.name == "posts.get")
					delete res.content;
			}
			return 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')
        }
    }
1121448
function callResponseMiddleware(err, res1, res2) {
        i -= 1;
        if (i >= 0) {
            var next = self.middlewares[i].response;
            if (typeof next === 'function') {
                next(req, err, res1, res2, callResponseMiddleware);
            } else {
                // skip this middleware if it doesn't implement response
                callResponseMiddleware(err, res1, res2);
            }
        } else {
            callback(req, err, res1, res2);
        }
    }
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);
			});
		}
	}
1367494
function createMiddleware(options = {}) {
  const middlewareOptions = Object.assign({}, defaults, options);

  return ({ getState }) => next => action => {
    // Do not process actions without an [RSAA] property
    if (!isRSAA(action)) {
      return next(action);
    }

    return (async () => {
      // Try to dispatch an error request FSA for invalid RSAAs
      const validationErrors = validateRSAA(action);
      if (validationErrors.length) {
        const callAPI = action[RSAA];
        if (callAPI.types && Array.isArray(callAPI.types)) {
          let requestType = callAPI.types[0];
          if (requestType && requestType.type) {
            requestType = requestType.type;
          }
          next({
            type: requestType,
            payload: new InvalidRSAA(validationErrors),
            error: true
          });
        }
        return;
      }

      // Parse the validated RSAA action
      const callAPI = action[RSAA];
      var {
        endpoint,
        body,
        headers,
        options = {},
        fetch: doFetch = middlewareOptions.fetch,
        ok = middlewareOptions.ok
      } = callAPI;
      const { method, credentials, bailout, types } = callAPI;
      const [requestType, successType, failureType] = normalizeTypeDescriptors(
        types
      );

      // Should we bail out?
      try {
        if (
          (typeof bailout === 'boolean' && bailout) ||
          (typeof bailout === 'function' && bailout(getState()))
        ) {
          return;
        }
      } catch (e) {
        return next(
          await actionWith(
            {
              ...failureType,
              payload: new RequestError('[RSAA].bailout function failed'),
              error: true
            },
            [action, getState()]
          )
        );
      }

      // Process [RSAA].endpoint function
      if (typeof endpoint === 'function') {
        try {
          endpoint = endpoint(getState());
        } catch (e) {
          return next(
            await actionWith(
              {
                ...failureType,
                payload: new RequestError('[RSAA].endpoint function failed'),
                error: true
              },
              [action, getState()]
            )
          );
        }
      }

      // Process [RSAA].body function
      if (typeof body === 'function') {
        try {
          body = body(getState());
        } catch (e) {
          return next(
            await actionWith(
              {
                ...failureType,
                payload: new RequestError('[RSAA].body function failed'),
                error: true
              },
              [action, getState()]
            )
          );
        }
      }

      // Process [RSAA].headers function
      if (typeof headers === 'function') {
        try {
          headers = headers(getState());
        } catch (e) {
          return next(
            await actionWith(
              {
                ...failureType,
                payload: new RequestError('[RSAA].headers function failed'),
                error: true
              },
              [action, getState()]
            )
          );
        }
      }

      // Process [RSAA].options function
      if (typeof options === 'function') {
        try {
          options = options(getState());
        } catch (e) {
          return next(
            await actionWith(
              {
                ...failureType,
                payload: new RequestError('[RSAA].options function failed'),
                error: true
              },
              [action, getState()]
            )
          );
        }
      }

      // We can now dispatch the request FSA
      if (
        typeof requestType.payload === 'function' ||
        typeof requestType.meta === 'function'
      ) {
        next(await actionWith(requestType, [action, getState()]));
      } else {
        next(requestType);
      }

      let res;
      try {
        // Make the API call
        res = await doFetch(endpoint, {
          ...options,
          method,
          body: body || undefined,
          credentials,
          headers: headers || {}
        });
      } catch (e) {
        // The request was malformed, or there was a network error
        return next(
          await actionWith(
            {
              ...failureType,
              payload: new RequestError(e.message),
              error: true
            },
            [action, getState()]
          )
        );
      }

      let isOk;
      try {
        isOk = ok(res);
      } catch (e) {
        return next(
          await actionWith(
            {
              ...failureType,
              payload: new InternalError('[RSAA].ok function failed'),
              error: true
            },
            [action, getState(), res]
          )
        );
      }

      // Process the server response
      if (isOk) {
        return next(await actionWith(successType, [action, getState(), res]));
      } else {
        return next(
          await actionWith(
            {
              ...failureType,
              error: true
            },
            [action, getState(), res]
          )
        );
      }
    })();
  };
}
441238
def log_middleware(store):
    """"""
    def wrapper(next_):
        def log_dispatch(action):
            print('Dispatch Action:', action)
            return next_(action)
        return log_dispatch
    return wrapper