Searches for annotations to register routes ...

@param vertx   Vert.X instance
@param restApi instance to search for annotations
@return Router new Router with routes as defined in {@code restApi} class
359097
public static Router register(Vertx vertx, Object... restApi) {

		Assert.notNull(vertx, "Missing vertx!");

		Router router = Router.router(vertx);
		return register(router, restApi);
	}
1347722
public Routed<T> route(M method, String path) {
    MethodlessRouter<T> router = routers.get(method);
    if (router == null) router = anyMethodRouter;

    Routed<T> ret = router.route(path);
    if (ret != null) return ret;

    if (router != anyMethodRouter) {
      ret = anyMethodRouter.route(path);
      if (ret != null) return ret;
    }

    if (notFound != null) return new Routed<T>(notFound, true, Collections.<String, String>emptyMap());

    return null;
  }
1135104
public static Route GET(String uriPattern, RouteHandler routeHandler) {
        return new Route(HttpConstants.Method.GET, uriPattern, routeHandler);
    }
651745
public function register_routes() {

		register_rest_route(
			$this->namespace, '/' . $this->parent_base . '/(?P<parent>[\d]+)/' . $this->rest_base, [
				'args' => [
					'parent' => [
						'required' => true,
						'description' => __( 'The ID for the parent of the object.' ),
						'type' => 'integer',
					],
				],
				[
					'methods' => \WP_REST_Server::READABLE,
					'callback' => [ $this, 'get_item' ],
					'permission_callback' => [ $this, 'get_item_permissions_check' ],
					'args' => [
						'context' => $this->get_context_param(
							[
								'default' => 'view',
							]
						),
					],
				],
				'schema' => [ $this, 'get_public_item_schema' ],
			]
		);
	}
1022996
function Router(HandleConstructor) {
  if (!(this instanceof Router)) return new Router(HandleConstructor);

  this.Handle = DefaultHandle;
  this.router = new HttpHash();
  this.collections = new Map();
  this.attachMethods = [];
}
1118091
def make_route(self, route) -> dict:
        
        middleware = route['middleware'] if 'middleware' in route else None
        # added to ALL requests to support xhr cross-site requests
        route['methods'].append('OPTIONS')
        return {
            'url': route['url'],
            'name': route['name'],
            'methods': route['methods'],
            'middleware': middleware,
            'callback': {
                'module': route['function'].__module__,
                'class': route['function'].__qualname__.rsplit('.', 1)[0],
                'function': route['function'].__name__
            }
        }
995540
private static <V> Router<V> router(boolean isTrie, List<V> values,
                                        Function<V, PathMapping> pathMappingResolver) {
        final Comparator<V> valueComparator =
                Comparator.comparingInt(e -> -1 * pathMappingResolver.apply(e).complexity());

        final Router<V> router;
        if (isTrie) {
            final RoutingTrie.Builder<V> builder = new Builder<>();
            // Set a comparator to sort services by the number of conditions to be checked in a descending
            // order.
            builder.comparator(valueComparator);
            values.forEach(v -> builder.add(pathMappingResolver.apply(v).triePath().get(), v));
            router = new TrieRouter<>(builder.build(), pathMappingResolver);
        } else {
            values.sort(valueComparator);
            router = new SequentialRouter<>(values, pathMappingResolver);
        }

        if (logger.isDebugEnabled()) {
            logger.debug("Router created for {} service(s): {}",
                         values.size(), router.getClass().getSimpleName());
            values.forEach(c -> {
                final PathMapping mapping = pathMappingResolver.apply(c);
                logger.debug("meterTag: {}, complexity: {}", mapping.meterTag(), mapping.complexity());
            });
        }
        values.clear();
        return router;
    }
615145
public Route matchRoute(String url) {
        if (hashRoute.containsKey(url)) {
            return new Route(hashRoute.get(url).get(0), null);
        }

        for (RegexRoute route : regexRoute) {
            Matcher matcher = route.getPattern().matcher(url);
            if (matcher.matches()) {
                return new Route(route, matcher);
            }
        }
        return null;
    }
1334340
private Map<String, String> getHttpHeaders(String restUrl) throws Exception {
        // return if already created...
        if (this.requestHttpHeaders != null)
            return this.requestHttpHeaders;

        // ...or initialize with default headers
        Map<String, String> httpHeaders = new HashMap<>();

        // content type
        httpHeaders.put("Content-Type", "application/json");

        // AuthenticationHelper http header
        if (this.authRequired) {
            AuthenticationHelper authHlp = new AuthenticationHelper(root);
            httpHeaders.putAll(authHlp.getHttpHeaderKey());
        }

        return httpHeaders;
    }
656971
public ProteusApplication addDefaultRoutes(RoutingHandler router)
    {

        if (config.hasPath("health.statusPath")) {
            try {
                final String statusPath = config.getString("health.statusPath");

                router.add(Methods.GET, statusPath, (final HttpServerExchange exchange) ->
                {
                    exchange.getResponseHeaders().add(Headers.CONTENT_TYPE, MediaType.TEXT_PLAIN);
                    exchange.getResponseSender().send("OK");
                });

                this.registeredEndpoints.add(EndpointInfo.builder().withConsumes("*/*").withProduces("text/plain").withPathTemplate(statusPath).withControllerName("Internal").withMethod(Methods.GET).build());

            } catch (Exception e) {
                log.error("Error adding health status route.", e.getMessage());
            }
        }

        if (config.hasPath("application.favicon")) {
            try {

                final ByteBuffer faviconImageBuffer;

                final File faviconFile = new File(config.getString("application.favicon"));

                if (!faviconFile.exists()) {
                    try (final InputStream stream = this.getClass().getResourceAsStream(config.getString("application.favicon"))) {
                        ByteArrayOutputStream baos = new ByteArrayOutputStream();

                        byte[] buffer = new byte[4096];
                        int read = 0;
                        while (read != -1) {
                            read = stream.read(buffer);
                            if (read > 0) {
                                baos.write(buffer, 0, read);
                            }
                        }

                        faviconImageBuffer = ByteBuffer.wrap(baos.toByteArray());
                    }

                } else {
                    try (final InputStream stream = Files.newInputStream(Paths.get(config.getString("application.favicon")))) {
                        ByteArrayOutputStream baos = new ByteArrayOutputStream();

                        byte[] buffer = new byte[4096];
                        int read = 0;
                        while (read != -1) {
                            read = stream.read(buffer);
                            if (read > 0) {
                                baos.write(buffer, 0, read);
                            }
                        }

                        faviconImageBuffer = ByteBuffer.wrap(baos.toByteArray());
                    }
                }

                router.add(Methods.GET, "favicon.ico", (final HttpServerExchange exchange) ->
                {
                    exchange.getResponseHeaders().add(Headers.CONTENT_TYPE, io.sinistral.proteus.server.MediaType.IMAGE_X_ICON.toString());
                    exchange.getResponseSender().send(faviconImageBuffer);
                });

            } catch (Exception e) {
                log.error("Error adding favicon route.", e.getMessage());
            }
        }

        return this;
    }
1242820
function restController(method, path) {

    'use strict';

    /*jshint validthis: true */

    this.method = method;
    this.path = path;
    this.controllerAction = null;

    /**
     * Parameters given to service (cannot be overloaded with query params)
     * @var {Object}
     */
    this.forcedParameters = {};

    /**
     * Ignore empty parameter in request if set to true
     * This can be usefull for search parameters given to a REST service, if empty string parmeters
     * are ignored, the associated service will not have to test this bebore doing the query
     * Forced parameters are not subject to this rule
     *
     * @var {Boolean}
     */
    this.ignoreEmptyParams = false;


    var ctrl = this;


    /**
     * Method called when the controller route path is fired by the app
     * the controllerAction() method will be called at the end
     * to process the controller specific action
     *
     * @param {Request} req
     * @param {Response} res
     *
     * @return {Promise}
     */
    this.onRequest = function(req, res, next) {

        var Q = require('q');
        var deferred = Q.defer();

        ctrl.req = req;
        ctrl.res = res;
        ctrl.next = next;


        var workflow = require('./workflow');
        ctrl.workflow = workflow(req, res);



        if (typeof req.app.checkPathOnRequest == 'function') {

            /**
             * If the method exists on application use it to verify the path validity
             * this method can use ctrl.accessDenied to output an error message in outcome
             * and the return false to cancel the controller defaut action
             */
            if (!req.app.checkPathOnRequest(ctrl)) {
                return Q.fcall(function () {
                    throw new Error("Access denied");
                });
            }
        }


        /**
         * Declare a new method to get the service object
         * @param {string} path          relative path from the services folder
         * @param {object} forceParams   Parameters given to service (cannot be overloaded with query params)
         * @return {apiService}
         */
        ctrl.service = function(path, forceParams) {
            var srv = require('./service').load(ctrl.req.app, path);

            ctrl.forcedParameters = forceParams;

            return srv;
        };

        deferred.resolve(ctrl.controllerAction());

        return deferred.promise;
    };


    /**
     * Return on object with parameters to give to the service
     * this method merge the client parameters and the forced server parameters
     *
     * @param {http.IncomingMessage} request
     *
     * @return {Promise}
     */
    this.getServiceParameters = function(request) {

        var name;
        var params = {};


        if (request.query) {
            for(name in request.query) {
                if (request.query.hasOwnProperty(name)) {

                    if (ctrl.ignoreEmptyParams && '' === request.query[name]) {
                        continue;
                    }

                    params[name] = request.query[name];
                }
            }
        }


        if (request.params) {

            // route path parameters

            for(name in request.params) {
                if (request.params.hasOwnProperty(name)) {

                    if (ctrl.ignoreEmptyParams && '' === request.params[name]) {
                        continue;
                    }

                    params[name] = request.params[name];
                }
            }
        }

        if (request.body) {

            // posted body in json format

            for(name in request.body) {
                if (request.body.hasOwnProperty(name)) {

                    if (ctrl.ignoreEmptyParams && '' === request.params[name]) {
                        continue;
                    }

                    params[name] = request.body[name];
                }
            }
        }


        for(name in this.forcedParameters) {
            if (this.forcedParameters.hasOwnProperty(name)) {
                params[name] = this.forcedParameters[name];
            }
        }

        return params;
    };


    /**
     * Output a 500 http code
     * Emit wokflow exception with message
     * @param {String} message
     *
     */
    ctrl.error = function(message) {
         ctrl.workflow.httpstatus = 500;
         ctrl.workflow.emit('exception', message);
    };


    /**
     * Output a 401 http code
     * Emit wokflow exception with message
     * @param {String} message
     *
     */
    ctrl.accessDenied = function(message) {
         ctrl.workflow.httpstatus = 401;
         ctrl.workflow.emit('exception', message);
    };

    /**
     * Output a 404 http code
     * Emit wokflow exception with message
     * @param {String} message
     *
     */
    this.notFound = function(message) {
         ctrl.workflow.httpstatus = 404;
         ctrl.workflow.emit('exception', message);
    };

    /**
     * Add the controller route the app
     * @param {Object} app
     */
    this.addRoute = function(app) {
        app[ctrl.method](ctrl.path, ctrl.onRequest);
    };

    /**
     * Controller use this method to output a service as a rest
     * service
     *
     * @param {apiService} service
     */
    this.jsonService = function(service) {
        throw new Error('not implemented');
    };

    /**
     * Output result as JSON string in controller response and end the response
     * if the promise fail, output the service.outcome object witch is supposed to contrain the error
     *
     * @param {apiService} service
     * @param {Promise}    promise The result promise from apiService.getResultPromise
     */
    this.outputJsonFromPromise = function(service, promise) {

        ctrl.res.setHeader("Content-Type", "application/json");

        promise.then(function(result) {
            ctrl.res.statusCode = service.httpstatus;
            ctrl.res.end(JSON.stringify(result));

        }).catch(function(err) {
            ctrl.res.statusCode = service.httpstatus;
            ctrl.res.end(JSON.stringify({ $outcome: service.outcome }));
        });

    };
}
668468
public static Server defaultHttp(ServiceAccessor accessor, Vertx vertx) {
        return new Server(
                accessor,
                vertx,
                "default-http",
                accessor.getConfiguration().getIntegerWithDefault("http.port", 9000),
                false, false,
                null,
                Collections.<String>emptyList(), Collections.<String>emptyList(), null);
    }
624490
def route(*args, response_formatter=jsonify, **kwargs):
    

    def decorator(func):
        @app.route(*args, **kwargs)
        @functools.wraps(func)
        def wrapped_view(*a, **kw):
            annotations = getattr(func, "__annotations__", {})
            reqargs = {
                name: value
                for name, value in annotations.items()
                if isinstance(value, fields.Field) and name != "return"
            }
            response_schema = annotations.get("return")
            parsed = parser.parse(reqargs, request)
            kw.update(parsed)
            response_data = func(*a, **kw)
            if response_schema:
                return response_formatter(response_schema.dump(response_data).data)
            else:
                return response_formatter(func(*a, **kw))

        return wrapped_view

    return decorator
131506
public Router get(@NotNull final Pattern regex, @NotNull final IMiddleware... handlers) {
        addRegEx("GET", regex, handlers, getBindings);
        return this;
    }
1103612
def _setup_rest_dispatcher(self):
        
        for _, method in inspect.getmembers(self, inspect.isroutine):
            try:
                config = getattr(method, HTTP_ROUTE_ATTRIBUTE)
            except AttributeError:
                # Not a REST method
                continue

            for route in config["routes"]:
                pattern, arguments = self.__convert_route(route)
                self.__methods_args.setdefault(method, {}).update(arguments)
                for http_verb in config["methods"]:
                    self.__routes.setdefault(http_verb, {})[pattern] = method
562898
protected void generateRoutes()
    {
        try {

//			Optional<io.sinistral.proteus.annotations.Chain> typeLevelWrapAnnotation = Optional.ofNullable(controllerClass.getAnnotation(io.sinistral.proteus.annotations.Chain.class));
//			
//			typeLevelWrapAnnotation.ifPresent( a -> {
//				 
//				io.sinistral.proteus.annotations.Chain w = typeLevelWrapAnnotation.get();
//
//				Class<? extends HandlerWrapper> wrapperClasses[] = w.value();
//
//				for (int i = 0; i < wrapperClasses.length; i++)
//				{
//					Class<? extends HandlerWrapper> wrapperClass = wrapperClasses[i];
//
//					String wrapperName = generateFieldName(wrapperClass.getCanonicalName());
//
//					handlerWrapperMap.put(wrapperClass, wrapperName);
//				}
//				
//			});
//			
//			for(Method m : this.controllerClass.getDeclaredMethods())
//			{
//			
//				Optional<io.sinistral.proteus.annotations.Chain> methodLevelWrapAnnotation = Optional.ofNullable(m.getAnnotation(io.sinistral.proteus.annotations.Chain.class));
//				
//				methodLevelWrapAnnotation.ifPresent( a -> {
//					 
//					io.sinistral.proteus.annotations.Chain w = methodLevelWrapAnnotation.get();
//	
//					Class<? extends HandlerWrapper> wrapperClasses[] = w.value();
//	
//					for (int i = 0; i < wrapperClasses.length; i++)
//					{
//						Class<? extends HandlerWrapper> wrapperClass = wrapperClasses[i];
//	
//						String wrapperName = generateFieldName(wrapperClass.getCanonicalName());
//	
//						handlerWrapperMap.put(wrapperClass, wrapperName);
//					}
//					
//				});
//
//			}
//			
//			log.info("handlerWrapperMap: " + handlerWrapperMap);

            TypeSpec.Builder typeBuilder = TypeSpec.classBuilder(className).addModifiers(Modifier.PUBLIC)
                    .addSuperinterface(ParameterizedTypeName.get(Supplier.class, RoutingHandler.class));

            ClassName extractorClass = ClassName.get("io.sinistral.proteus.server", "Extractors");

            ClassName injectClass = ClassName.get("com.google.inject", "Inject");


            MethodSpec.Builder constructor = MethodSpec.constructorBuilder().addModifiers(Modifier.PUBLIC).addAnnotation(injectClass);

            String className = this.controllerClass.getSimpleName().toLowerCase() + "Controller";

            typeBuilder.addField(this.controllerClass, className, Modifier.PROTECTED, Modifier.FINAL);

            ClassName wrapperClass = ClassName.get("io.undertow.server", "HandlerWrapper");
            ClassName stringClass = ClassName.get("java.lang", "String");
            ClassName mapClass = ClassName.get("java.util", "Map");

            TypeName mapOfWrappers = ParameterizedTypeName.get(mapClass, stringClass, wrapperClass);

            TypeName annotatedMapOfWrappers = mapOfWrappers
                    .annotated(AnnotationSpec.builder(com.google.inject.name.Named.class).addMember("value", "$S", "registeredHandlerWrappers").build());

            typeBuilder.addField(mapOfWrappers, "registeredHandlerWrappers", Modifier.PROTECTED, Modifier.FINAL);


            constructor.addParameter(this.controllerClass, className);
            constructor.addParameter(annotatedMapOfWrappers, "registeredHandlerWrappers");

            constructor.addStatement("this.$N = $N", className, className);
            constructor.addStatement("this.$N = $N", "registeredHandlerWrappers", "registeredHandlerWrappers");

            addClassMethodHandlers(typeBuilder, this.controllerClass);

            typeBuilder.addMethod(constructor.build());

            JavaFile javaFile = JavaFile.builder(packageName, typeBuilder.build()).addStaticImport(extractorClass, "*").build();

            StringBuilder sb = new StringBuilder();

            javaFile.writeTo(sb);

            this.sourceString = sb.toString();

        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }
313649
public ServiceFuture<List<ExpressRouteGatewayInner>> listAsync(final ServiceCallback<List<ExpressRouteGatewayInner>> serviceCallback) {
        return ServiceFuture.fromResponse(listWithServiceResponseAsync(), serviceCallback);
    }