Module io.jooby
Package io.jooby

Interface Router

All Superinterfaces:
Registry
All Known Implementing Classes:
Jooby

public interface Router extends Registry
Routing DSL functions.
Since:
2.0.0
Author:
edgar
  • Field Details

  • Method Details

    • getConfig

      @NonNull com.typesafe.config.Config getConfig()
      Application configuration.
      Returns:
      Application configuration.
    • getEnvironment

      @NonNull Environment getEnvironment()
      Application environment.
      Returns:
      Application environment.
    • getLocales

      @NonNull List<Locale> getLocales()
      Returns the supported locales.
      Returns:
      The supported locales.
    • getAttributes

      @NonNull Map<String,Object> getAttributes()
      Mutable map of application attributes.
      Returns:
      Mutable map of application attributes.
    • attribute

      @NonNull default <T> T attribute(@NonNull String key)
      Get an attribute by his key. This is just a utility method around getAttributes().
      Type Parameters:
      T - Attribute type.
      Parameters:
      key - Attribute key.
      Returns:
      Attribute value.
    • attribute

      @NonNull default Router attribute(@NonNull String key, Object value)
      Set an application attribute.
      Parameters:
      key - Attribute key.
      value - Attribute value.
      Returns:
      This router.
    • getServices

      @NonNull ServiceRegistry getServices()
      Application service registry. Services are accessible via this registry or Jooby.require(Class) calls.

      This method returns a mutable registry. You are free to modify/alter the registry.

      Returns:
      Service registry.
    • setContextPath

      @NonNull Router setContextPath(@NonNull String contextPath)
      Set application context path. Context path is the base path for all routes. Default is: / .
      Parameters:
      contextPath - Context path.
      Returns:
      This router.
    • getContextPath

      @NonNull String getContextPath()
      Get application context path (a.k.a as base path).
      Returns:
      Application context path (a.k.a as base path).
    • isTrustProxy

      boolean isTrustProxy()
      When true handles X-Forwarded-* headers by updating the values on the current context to match what was sent in the header(s).

      This should only be installed behind a reverse proxy that has been configured to send the X-Forwarded-* header, otherwise a remote user can spoof their address by sending a header with bogus values.

      The headers that are read/set are:

      Returns:
      True when enabled. Default is false.
    • isStarted

      boolean isStarted()
    • isStopped

      boolean isStopped()
    • setTrustProxy

      @NonNull Router setTrustProxy(boolean trustProxy)
      When true handles X-Forwarded-* headers by updating the values on the current context to match what was sent in the header(s).

      This should only be installed behind a reverse proxy that has been configured to send the X-Forwarded-* header, otherwise a remote user can spoof their address by sending a header with bogus values.

      The headers that are read/set are:

      Parameters:
      trustProxy - True to enable.
      Returns:
      This router.
    • setHiddenMethod

      @NonNull Router setHiddenMethod(@NonNull String parameterName)
      Provides a way to override the current HTTP method. Request must be:

      - POST Form/multipart request

      For alternative strategy use the setHiddenMethod(Function) method.

      Parameters:
      parameterName - Form field name.
      Returns:
      This router.
    • setHiddenMethod

      @NonNull Router setHiddenMethod(@NonNull Function<Context,Optional<String>> provider)
      Provides a way to override the current HTTP method using lookup strategy.
      Parameters:
      provider - Lookup strategy.
      Returns:
      This router.
    • setCurrentUser

      @NonNull Router setCurrentUser(@NonNull Function<Context,Object> provider)
      Provides a way to set the current user from a Context. Current user can be retrieve it using Context.getUser().
      Parameters:
      provider - User provider/factory.
      Returns:
      This router.
    • setContextAsService

      @NonNull Router setContextAsService(boolean contextAsService)
      If enabled, allows to retrieve the Context object associated with the current request via the service registry while the request is being processed.
      Parameters:
      contextAsService - whether to enable or disable this feature
      Returns:
      This router.
    • domain

      @NonNull Router domain(@NonNull String domain, @NonNull Router subrouter)
      Enabled routes for specific domain. Domain matching is done using the host header.
      
       {
         domain("foo.com", new FooApp());
         domain("bar.com", new BarApp());
       }
       
      NOTE: if you run behind a reverse proxy you might to enabled setTrustProxy(boolean).

      NOTE: ONLY routes are imported. Services, callback, etc.. are ignored.

      Parameters:
      domain - Predicate
      subrouter - Subrouter.
      Returns:
      This router.
    • domain

      @NonNull RouteSet domain(@NonNull String domain, @NonNull Runnable body)
      Enabled routes for specific domain. Domain matching is done using the host header.
      
       {
         domain("foo.com", () -> {
           get("/", ctx -> "foo");
         });
         domain("bar.com", () -> {
           get("/", ctx -> "bar");
         });
       }
       
      NOTE: if you run behind a reverse proxy you might to enabled setTrustProxy(boolean).
      Parameters:
      domain - Predicate
      body - Route action.
      Returns:
      This router.
    • mount

      @NonNull Router mount(@NonNull Predicate<Context> predicate, @NonNull Router router)
      Import routes from given router. Predicate works like a filter and only when predicate pass the routes match against the current request.

      Example of domain predicate filter:

      
       {
         use(ctx -> ctx.getHost().equals("foo.com"), new FooApp());
         use(ctx -> ctx.getHost().equals("bar.com"), new BarApp());
       }
       
      Imported routes are matched only when predicate pass.

      NOTE: if you run behind a reverse proxy you might to enabled setTrustProxy(boolean).

      NOTE: ONLY routes are imported. Services, callback, etc.. are ignored.

      Parameters:
      predicate - Context predicate.
      router - Router to import.
      Returns:
      This router.
    • mount

      @NonNull RouteSet mount(@NonNull Predicate<Context> predicate, @NonNull Runnable body)
      Import routes from given action. Predicate works like a filter and only when predicate pass the routes match against the current request.

      Example of domain predicate filter:

      
       {
         mount(ctx -> ctx.getHost().equals("foo.com"), () -> {
           get("/", ctx -> "foo");
         });
         mount(ctx -> ctx.getHost().equals("bar.com"), () -> {
           get("/", ctx -> "bar");
         });
       }
       
      NOTE: if you run behind a reverse proxy you might to enabled setTrustProxy(boolean).

      NOTE: ONLY routes are imported. Services, callback, etc.. are ignored.

      Parameters:
      predicate - Context predicate.
      body - Route action.
      Returns:
      This router.
    • mount

      @NonNull Router mount(@NonNull String path, @NonNull Router router)
      Import all routes from the given router and prefix them with the given path.

      NOTE: ONLY routes are imported. Services, callback, etc.. are ignored.

      Parameters:
      path - Prefix path.
      router - Router to import.
      Returns:
      This router.
    • mount

      @NonNull Router mount(@NonNull Router router)
      Import all routes from the given router.

      NOTE: ONLY routes are imported. Services, callback, etc.. are ignored.

      Parameters:
      router - Router to import.
      Returns:
      This router.
    • mvc

      @NonNull Router mvc(@NonNull Class router)
      Import all route method from the given controller class. At runtime the controller instance is resolved by calling Jooby.require(Class).
      Parameters:
      router - Controller class.
      Returns:
      This router.
    • mvc

      @NonNull <T> Router mvc(@NonNull Class<T> router, @NonNull jakarta.inject.Provider<T> provider)
      Import all route method from the given controller class.
      Type Parameters:
      T - Controller type.
      Parameters:
      router - Controller class.
      provider - Controller provider.
      Returns:
      This router.
    • mvc

      @NonNull Router mvc(@NonNull Object router)
      Import all route methods from given controller instance.
      Parameters:
      router - Controller instance.
      Returns:
      This routes.
    • ws

      @NonNull Route ws(@NonNull String pattern, @NonNull WebSocket.Initializer handler)
      Add a websocket handler.
      Parameters:
      pattern - WebSocket path pattern.
      handler - WebSocket handler.
      Returns:
      A new route.
    • sse

      @NonNull Route sse(@NonNull String pattern, @NonNull ServerSentEmitter.Handler handler)
      Add a server-sent event handler.
      Parameters:
      pattern - Path pattern.
      handler - Handler.
      Returns:
      A new route.
    • getRoutes

      @NonNull List<Route> getRoutes()
      Returns all routes.
      Returns:
      All routes.
    • encoder

      @NonNull Router encoder(@NonNull MessageEncoder encoder)
      Register a route response encoder.
      Parameters:
      encoder - MessageEncoder instance.
      Returns:
      This router.
    • encoder

      @NonNull Router encoder(@NonNull MediaType contentType, @NonNull MessageEncoder encoder)
      Register a route response encoder.
      Parameters:
      contentType - Accept header should match the content-type.
      encoder - MessageEncoder instance.
      Returns:
      This router.
    • getTmpdir

      @NonNull Path getTmpdir()
      Application temporary directory. This method initialize the Environment when isn't set manually.
      Returns:
      Application temporary directory.
    • decoder

      @NonNull Router decoder(@NonNull MediaType contentType, @NonNull MessageDecoder decoder)
      Register a decoder for the given content type.
      Parameters:
      contentType - Content type to match.
      decoder - MessageDecoder.
      Returns:
      This router.
    • getWorker

      @NonNull Executor getWorker()
      Returns the worker thread pool. This thread pool is used to run application blocking code.
      Returns:
      Worker thread pool.
    • setWorker

      @NonNull Router setWorker(@NonNull Executor worker)
      Set a worker thread pool. This thread pool is used to run application blocking code.
      Parameters:
      worker - Worker thread pool.
      Returns:
      This router.
    • setDefaultWorker

      @NonNull Router setDefaultWorker(@NonNull Executor worker)
      Set the default worker thread pool. Via this method the underlying web server set/suggests the worker thread pool that should be used it.

      A call to getWorker() returns the default thread pool, unless you explicitly set one.

      Parameters:
      worker - Default worker thread pool.
      Returns:
      This router.
    • use

      @NonNull Router use(@NonNull Route.Filter filter)
      Attach a filter to the route pipeline.
      Parameters:
      filter - Filter.
      Returns:
      This router.
    • decorator

      @Deprecated @NonNull default Router decorator(@NonNull Route.Decorator filter)
      Deprecated.
      Attach a filter to the route pipeline.
      Parameters:
      filter - Filter.
      Returns:
      This router.
    • before

      @NonNull Router before(@NonNull Route.Before before)
      Add a before route decorator to the route pipeline.
      Parameters:
      before - Before decorator.
      Returns:
      This router.
    • after

      @NonNull Router after(@NonNull Route.After after)
      Add an after route decorator to the route pipeline.
      Parameters:
      after - After decorator.
      Returns:
      This router.
    • dispatch

      @NonNull Router dispatch(@NonNull Runnable body)
      Dispatch route pipeline to the getWorker() worker thread pool. After dispatch application code is allowed to do blocking calls.
      Parameters:
      body - Dispatch body.
      Returns:
      This router.
    • dispatch

      @NonNull Router dispatch(@NonNull Executor executor, @NonNull Runnable body)
      Dispatch route pipeline to the given executor. After dispatch application code is allowed to do blocking calls.
      Parameters:
      executor - Executor. ExecutorService instances automatically shutdown at application exit.
      body - Dispatch body.
      Returns:
      This router.
    • routes

      @NonNull RouteSet routes(@NonNull Runnable body)
      Group one or more routes. Useful for applying cross cutting concerns to the enclosed routes.
      Parameters:
      body - Route body.
      Returns:
      All routes created.
    • path

      @NonNull RouteSet path(@NonNull String pattern, @NonNull Runnable body)
      Group one or more routes under a common path prefix. Useful for applying cross-cutting concerns to the enclosed routes.
      Parameters:
      pattern - Path pattern.
      body - Route body.
      Returns:
      All routes created.
    • get

      @NonNull default Route get(@NonNull String pattern, @NonNull Route.Handler handler)
      Add a HTTP GET handler.
      Parameters:
      pattern - Path pattern.
      handler - Application code.
      Returns:
      A route.
    • post

      @NonNull default Route post(@NonNull String pattern, @NonNull Route.Handler handler)
      Add a HTTP POST handler.
      Parameters:
      pattern - Path pattern.
      handler - Application code.
      Returns:
      A route.
    • put

      @NonNull default Route put(@NonNull String pattern, @NonNull Route.Handler handler)
      Add a HTTP PUT handler.
      Parameters:
      pattern - Path pattern.
      handler - Application code.
      Returns:
      A route.
    • delete

      @NonNull default Route delete(@NonNull String pattern, @NonNull Route.Handler handler)
      Add a HTTP DELETE handler.
      Parameters:
      pattern - Path pattern.
      handler - Application code.
      Returns:
      A route.
    • patch

      @NonNull default Route patch(@NonNull String pattern, @NonNull Route.Handler handler)
      Add a HTTP PATCH handler.
      Parameters:
      pattern - Path pattern.
      handler - Application code.
      Returns:
      A route.
    • head

      @NonNull default Route head(@NonNull String pattern, @NonNull Route.Handler handler)
      Add a HTTP HEAD handler.
      Parameters:
      pattern - Path pattern.
      handler - Application code.
      Returns:
      A route.
    • options

      @NonNull default Route options(@NonNull String pattern, @NonNull Route.Handler handler)
      Add a HTTP OPTIONS handler.
      Parameters:
      pattern - Path pattern.
      handler - Application code.
      Returns:
      A route.
    • trace

      @NonNull default Route trace(@NonNull String pattern, @NonNull Route.Handler handler)
      Add a HTTP TRACE handler.
      Parameters:
      pattern - Path pattern.
      handler - Application code.
      Returns:
      A route.
    • assets

      @NonNull default Route assets(@NonNull String pattern, @NonNull Path source)
      Add a static resource handler. Static resources are resolved from file system.
      Parameters:
      pattern - Path pattern.
      source - File system directory.
      Returns:
      A route.
    • assets

      @NonNull default Route assets(@NonNull String pattern, @NonNull String source)
      Add a static resource handler. Static resources are resolved from:

      - file-system if the source folder exists in the current user directory - or fallback to classpath when file-system folder doesn't exist.

      NOTE: This method choose file-system or classpath, it doesn't merge them.

      Parameters:
      pattern - Path pattern.
      source - File-System folder when exists, or fallback to a classpath folder.
      Returns:
      A route.
    • assets

      @NonNull default Route assets(@NonNull String pattern, @NonNull AssetSource... sources)
      Add a static resource handler.
      Parameters:
      pattern - Path pattern.
      sources - Asset sources. At least one source is required.
      Returns:
      A route.
    • assets

      @NonNull default Route assets(@NonNull String pattern, @NonNull AssetHandler handler)
      Add a static resource handler.
      Parameters:
      pattern - Path pattern.
      handler - Asset handler.
      Returns:
      A route.
    • route

      @NonNull Route route(@NonNull String method, @NonNull String pattern, @NonNull Route.Handler handler)
      Add a route.
      Parameters:
      method - HTTP method.
      pattern - Path pattern.
      handler - Application code.
      Returns:
      A route.
    • match

      @NonNull Router.Match match(@NonNull Context ctx)
      Find a matching route using the given context.

      If no match exists this method returns a route with a 404 handler. See Route.NOT_FOUND.

      Parameters:
      ctx - Web Context.
      Returns:
      A route match result.
    • match

      boolean match(@NonNull String method, @NonNull String path)
      Find a matching route using the given context.

      If no match exists this method returns a route with a 404 handler. See Route.NOT_FOUND.

      Parameters:
      method - Method to match.
      path - Path to match.
      Returns:
      A route match result.
    • errorCode

      @NonNull Router errorCode(@NonNull Class<? extends Throwable> type, @NonNull StatusCode statusCode)
      Map an exception type to a status code.
      Parameters:
      type - Exception type.
      statusCode - Status code.
      Returns:
      This router.
    • errorCode

      @NonNull StatusCode errorCode(@NonNull Throwable cause)
      Computes the status code for the given exception.
      Parameters:
      cause - Exception.
      Returns:
      Status code.
    • error

      @NonNull default Router error(@NonNull StatusCode statusCode, @NonNull ErrorHandler handler)
      Add a custom error handler that matches the given status code.
      Parameters:
      statusCode - Status code.
      handler - Error handler.
      Returns:
      This router.
    • error

      @NonNull default Router error(@NonNull Class<? extends Throwable> type, @NonNull ErrorHandler handler)
      Add a custom error handler that matches the given exception type.
      Parameters:
      type - Exception type.
      handler - Error handler.
      Returns:
      This router.
    • error

      @NonNull default Router error(@NonNull Predicate<StatusCode> predicate, @NonNull ErrorHandler handler)
      Add a custom error handler that matches the given predicate.
      Parameters:
      predicate - Status code filter.
      handler - Error handler.
      Returns:
      This router.
    • error

      @NonNull Router error(@NonNull ErrorHandler handler)
      Add a custom error handler.
      Parameters:
      handler - Error handler.
      Returns:
      This router.
    • getErrorHandler

      @NonNull ErrorHandler getErrorHandler()
      Get the error handler.
      Returns:
      An error handler.
    • getLog

      @NonNull org.slf4j.Logger getLog()
      Application logger.
      Returns:
      Application logger.
    • resultHandler

      @NonNull Router resultHandler(@NonNull ResultHandler factory)
      Add a response handler factory.
      Parameters:
      factory - Response handler factory.
      Returns:
      This router.
    • getRouterOptions

      @NonNull Set<RouterOption> getRouterOptions()
      Router options.
      Returns:
      Router options.
    • setRouterOptions

      @NonNull Router setRouterOptions(@NonNull RouterOption... options)
      Set router options.
      Parameters:
      options - router options.
      Returns:
      This router.
    • getSessionStore

      @NonNull SessionStore getSessionStore()
      Session store. Default use a cookie ID with a memory storage.

      See SessionStore.memory().

      Returns:
      Session store.
    • setSessionStore

      @NonNull Router setSessionStore(@NonNull SessionStore store)
      Set session store.
      Parameters:
      store - Session store.
      Returns:
      This router.
    • executor

      @NonNull default Executor executor(@NonNull String name)
      Get an executor from application registry.
      Parameters:
      name - Executor name.
      Returns:
      Executor.
    • executor

      @NonNull Router executor(@NonNull String name, @NonNull Executor executor)
      Put an executor into the application registry.
      Parameters:
      name - Executor's name.
      executor - Executor.
      Returns:
      This router.
    • getFlashCookie

      @NonNull Cookie getFlashCookie()
      Template for the flash cookie. Default name is: jooby.flash.
      Returns:
      Template for the flash cookie.
    • setFlashCookie

      @NonNull Router setFlashCookie(@NonNull Cookie flashCookie)
      Sets a cookie used as a template to generate the flash cookie, allowing to customize the cookie name and other cookie parameters.
      Parameters:
      flashCookie - The cookie template.
      Returns:
      This router.
    • converter

      @NonNull Router converter(@NonNull ValueConverter converter)
      Add a custom string value converter.
      Parameters:
      converter - Custom value converter.
      Returns:
      This router.
    • getConverters

      @NonNull List<ValueConverter> getConverters()
      Get all simple/string value converters.
      Returns:
      All simple/string value converters.
    • getBeanConverters

      @NonNull List<BeanConverter> getBeanConverters()
      Get all complex/bean value converters.
      Returns:
      All complex/bean value converters.
    • getServerOptions

      @NonNull ServerOptions getServerOptions()
      Available server options.
      Returns:
      Server options.
    • leadingSlash

      @NonNull static String leadingSlash(@Nullable String path)
      Ensure path start with a /(leading slash).
      Parameters:
      path - Path to process.
      Returns:
      Path with leading slash.
    • noTrailingSlash

      @NonNull static String noTrailingSlash(@NonNull String path)
      Strip trailing slashes.
      Parameters:
      path - Path to process.
      Returns:
      Path without trailing slashes.
    • normalizePath

      @NonNull static String normalizePath(@Nullable String path)
      Normalize a path by removing consecutive /(slashes).
      Parameters:
      path - Path to process.
      Returns:
      Safe path pattern.
    • pathKeys

      @NonNull static List<String> pathKeys(@NonNull String pattern)
      Extract path keys from given path pattern. A path key (a.k.a path variable) looks like:
      /product/{id}
      Parameters:
      pattern - Path pattern.
      Returns:
      Path keys.
    • pathKeys

      @NonNull static List<String> pathKeys(@NonNull String pattern, BiConsumer<String,String> consumer)
      Extract path keys from given path pattern. A path key (a.k.a path variable) looks like:
      /product/{id}
      Parameters:
      pattern - Path pattern.
      consumer - Listen for key and regex variables found.
      Returns:
      Path keys.
    • expandOptionalVariables

      @NonNull static List<String> expandOptionalVariables(@NonNull String pattern)
      Look for optional path parameter and expand the given pattern into multiple pattern.
         /path => [/path]
         /{id} => [/{id}]
         /path/{id} => [/path/{id}]
      
         /{id}? => [/, /{id}]
         /path/{id}? => [/path, /path/{id}]
         /path/{id}/{start}?/{end}? => [/path/{id}, /path/{id}/{start}, /path/{id}/{start}/{end}]
         /path/{id}?/suffix => [/path, /path/{id}, /path/suffix]
       
      Parameters:
      pattern - Pattern.
      Returns:
      One or more patterns.
    • reverse

      @NonNull static String reverse(@NonNull String pattern, @NonNull Object... values)
      Recreate a path pattern using the given variables. Variable replacement is done using the current index.
      Parameters:
      pattern - Path pattern.
      values - Path keys.
      Returns:
      Path.
    • reverse

      @NonNull static String reverse(@NonNull String pattern, @NonNull Map<String,Object> keys)
      Recreate a path pattern using the given variables.
      Parameters:
      pattern - Path pattern.
      keys - Path keys.
      Returns:
      Path.