--- ADD MIDDLEWARE TO ACTION ---
188203
@Override
	public Action install(Action action, Tree config) {

		// Is caching enabled?
		Tree cacheNode = config.get("cache");
		if (cacheNode == null || cacheNode.isNull()) {
			return null;
		}
		if (cacheNode.getType() == Boolean.class && !cacheNode.asBoolean()) {
			return null;
		}
		
		// Get cache keys
		Tree keyNode = cacheNode.get("keys");
		final String[] keys;
		if (keyNode == null) {
			keys = null;
		} else {
			List<String> list = keyNode.asList(String.class);
			if (list.isEmpty()) {
				keys = null;
			} else {
				keys = new String[list.size()];
				list.toArray(keys);
			}
		}

		// Get TTL (0 = use default TTL)
		final int ttl = cacheNode.get("ttl", 0);

		return new Action() {

			@Override
			public Object handler(Context ctx) throws Exception {
				String key = getCacheKey(ctx.name, ctx.params, keys);
				return new Promise(resolver -> {
					get(key).then(in -> {
						if (in == null || in.isNull()) {
							new Promise(action.handler(ctx)).then(tree -> {
								set(key, tree, ttl);
								resolver.resolve(tree);
							}).catchError(err -> {
								resolver.reject(err);
							});
						} else {
							resolver.resolve(in);
						}
					}).catchError(err -> {
						resolver.reject(err);
					});
				});
			}
		};
	}
47298
private void handle(final Request request, final Response response, final List<Middleware> middlewares) throws Exception {
		if (middlewares.isEmpty()) {
			throw new NotFoundException();
		}
		
		Middleware current = middlewares.remove(0);
		current.handle(request, response, new MiddlewareChain() {
			@Override
			public void next() throws Exception {
				// recursive call
				handle(request, response, middlewares);
			}
		});
	}
751507
def use(self, middleware):
        

        logger.debug('use')
        logger.debug(middleware)

        self.middlewares.append(middleware)

        di.injector.register(instance=middleware)
        di.bind(middleware, auto=True)

        # TODO: should use DI somehow
        if check_spec(['send_text_message'], middleware):
            self.chat.add_interface(middleware)

        return middleware
840878
function makeAction (controller, method, opts) {
  let action = {action: controller + '@' + method};
  return extend (action, opts);
}
727225
def addAction(self, action):
        
        self.ACTIONS.append(action)
        return "ACTION#{}".format(len(self.ACTIONS) - 1)
979768
public function middleware( $middleware = null )
	{
		if ( is_null( $middleware ) )
			return (array) Arr::get( $this->action, 'middleware', [] );

		if ( is_string( $middleware ) )
			$middleware = [$middleware];

		$this->action['middleware'] = array_merge( (array) Arr::get( $this->action, 'middleware', [] ), $middleware );

		return $this;
	}
151567
private void sendSolutionActions(String action, String reqId){
        if(reqId!=null && !reqId.equals("")) {
            Map<String, String> map = Maps.newHashMap();
            map.put("action", action);
            map.put("reqid", reqId);
            this.sendEvent(map);
        }
    }
149222
@Override
    public void addAction(final LifecycleStage stage, final LifecycleAction<T> action)
    {
        stageEvents.add(new StageEvent(stage, action));
    }
154578
public boolean use(Middleware middleware) {
		if (checkedMiddlewares.add(middleware)) {
			Action action = middleware.install(current, config);
			if (action != null) {
				logger.info("Middleware \"" + middleware.getName() + "\" installed to action \"" + name + "\".");
				current = action;
				return true;
			}
		}
		return false;
	}
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`);
    }
}
1007736
public function middleware($request, &$response)
    {
        $that = $this;
        if ($middleware = current($this->middleware)) {
            next($this->middleware);
            $middleware->next($request, $response, function ($request, $response) use ($that) {
                $that->middleware($request, $response);
            });
        }
    }
1097166
function(middlewares, method, request, response_middlewares, callback) {
        var that = this;
        try {
            var middleware = middlewares.shift();
            if (!middleware) {
                return this._makeRequest(request, callback, response_middlewares);
            }
            if (middleware.cond(method, request)) {
                var middleware_callback = function(retVal) {
                    /**
                     * got an error
                     * break middleware chain and callback
                     */
                    if (retVal && retVal instanceof Error) {
                        return callback(retVal, null);
                    }
                    /**
                     * got a response object
                     * break middleware chain and bypass request
                     */
                    if (retVal && typeof retVal == 'object') {
                        return that._callResponseMiddlewares(response_middlewares, retVal, callback);
                    }
                    /**
                     * got a callback
                     * push it on response_middlewares array
                     * will be called after request
                     */
                    if (retVal && typeof retVal == 'function') {
                        response_middlewares.unshift(retVal);
                    }
                    that._callRequestMiddlewares(middlewares, method, request, response_middlewares, callback);
                };
                middleware.fun(method, request, middleware_callback);
            } else {
                this._callRequestMiddlewares(middlewares, method, request, response_middlewares, callback);
            }
        } catch (e) {
            callback(e, null);
        }
    }
291208
private void addActionFromRouteElem(ControllerRouteModel<Raml> elem, Resource resource) {
        Action action = new Action();
        action.setType(ActionType.valueOf(elem.getHttpMethod().name()));

        action.setDescription(elem.getDescription());

        //handle body
        addBodyToAction(elem, action);

        //Handle responses
        addResponsesToAction(elem, action);

        //handle all route params
        for (RouteParamModel<Raml> param : elem.getParams()) {

            AbstractParam ap = null; //the param to add

            //Fill the param info depending on its type
            switch (param.getParamType()) {
                case FORM:
                    MimeType formMime = action.getBody().get("application/x-www-form-urlencoded");

                    if (formMime == null) {
                        //create default form mimeType
                        formMime = new MimeType("application/x-www-form-urlencoded");
                    }

                    if (formMime.getFormParameters() == null) { //why raml, why you ain't init that
                        formMime.setFormParameters(new LinkedHashMap<String, List<FormParameter>>(2));
                    }

                    ap = new FormParameter();
                    formMime.getFormParameters().put(param.getName(), singletonList((FormParameter) ap));
                    break;
                case PARAM:
                case PATH_PARAM:
                    if (!ancestorOrIHasParam(resource, param.getName())) {
                        ap = new UriParameter();
                        resource.getUriParameters().put(param.getName(), (UriParameter) ap);
                    }
                    //we do nothing if the param has already been define in the resouce or its ancestor.
                    break;
                case QUERY:
                    ap = new QueryParameter();
                    action.getQueryParameters().put(param.getName(), (QueryParameter) ap);
                    break;
                case BODY:
                default:
                    break; //body is handled at the method level.
            }

            if (ap == null) {
                //no param has been created, we skip.
                continue;
            }

            //Set param type
            ParamType type = typeConverter(param.getValueType());

            if (type != null) {
                ap.setType(type);
            }

            //set required, usually thanks to the notnull constraints annotation.
            if(param.isMandatory()){
                ap.setRequired(true);
            } else {
                ap.setRequired(false);
            }

            //set minimum if specified
            if(param.getMin()!=null){
                ap.setMinimum(BigDecimal.valueOf(param.getMin()));
                //TODO warn if type is not number/integer
            }

            //set maximum if specified
            if(param.getMax()!=null){
                ap.setMinimum(BigDecimal.valueOf(param.getMax()));
                //TODO warn if type is not number/integer
            }

            //set default value
            if (param.getDefaultValue() != null) {
                ap.setRequired(false);
                ap.setDefaultValue(param.getDefaultValue());
            }
        }

        resource.getActions().put(action.getType(), action);
    }
1124365
function extractMiddleware(name, targets, config) {
  for(const i in targets) {
    if(name.indexOf('#') !== -1) {
      const [controller, action] = name.split('#');
      MiddleWares.push({
        target: targets[i],
        controller,
        action,
        type: config && config.type ? config.type : 'use'
      });
    } else {
      MiddleWares.push({
        target: targets[i],
        controller: name,
        type: config && config.type ? config.type : 'use'
      });
    }
  }
}
126783
function addResourceRoute(routePath, controllerName) {
		resourceRouting.forEach(function(route) {
			var actionPath = route.path.replace(':controller', controllerName);
			route.verbs.forEach(function (verb) {
				addSingleRoute(verb, actionPath, controllerName, route.target.action);
			});
		});
	}
1258162
def add_action(self, name, parent, action):
        
        if iskeyword(name):
            name = '_' + name
        self._actions[name] = parent.new_action(**action)
        setattr(self, name, self._actions[name].execute)
509521
public static void addAction(Set<Action> aas, Action action, boolean condition) {

        if (condition) {
            aas.add(action);
        }
    }