Package spark

Class Service


  • public final class Service
    extends Routable
    Represents a Spark server "session". If a user wants multiple 'Sparks' in his application the method ignite() should be statically imported and used to create instances. The instance should typically be named so when prefixing the 'routing' methods the semantic makes sense. For example 'http' is a good variable name since when adding routes it would be: Service http = ignite(); ... http.get("/hello", (q, a) -> "Hello World");
    • Field Detail

      • LOG

        private static final org.slf4j.Logger LOG
      • DEFAULT_ACCEPT_TYPE

        protected static final java.lang.String DEFAULT_ACCEPT_TYPE
        See Also:
        Constant Field Values
      • initialized

        protected boolean initialized
      • port

        protected int port
      • ipAddress

        protected java.lang.String ipAddress
      • maxThreads

        protected int maxThreads
      • minThreads

        protected int minThreads
      • threadIdleTimeoutMillis

        protected int threadIdleTimeoutMillis
      • webSocketIdleTimeoutMillis

        protected java.util.Optional<java.lang.Integer> webSocketIdleTimeoutMillis
      • pathDeque

        protected java.util.Deque<java.lang.String> pathDeque
      • routes

        protected Routes routes
      • initLatch

        private java.util.concurrent.CountDownLatch initLatch
      • stopLatch

        private java.util.concurrent.CountDownLatch stopLatch
      • redirect

        public final Redirect redirect
      • initExceptionHandler

        private java.util.function.Consumer<java.lang.Exception> initExceptionHandler
    • Constructor Detail

      • Service

        private Service()
    • Method Detail

      • ignite

        public static Service ignite()
        Creates a new Service (a Spark instance). This should be used instead of the static API if the user wants multiple services in one process.
        Returns:
        the newly created object
      • ipAddress

        public Service ipAddress​(java.lang.String ipAddress)
        Set the IP address that Spark should listen on. If not called the default address is '0.0.0.0'. This has to be called before any route mapping is done.
        Parameters:
        ipAddress - The ipAddress
        Returns:
        the object with IP address set
      • port

        public Service port​(int port)
        Set the port that Spark should listen on. If not called the default port is 4567. This has to be called before any route mapping is done. If provided port = 0 then the an arbitrary available port will be used.
        Parameters:
        port - The port number
        Returns:
        the object with port set
      • port

        public int port()
        Retrieves the port that Spark is listening on.
        Returns:
        The port Spark server is listening on.
        Throws:
        java.lang.IllegalStateException - when the server is not started
      • threadPool

        public Service threadPool​(int maxThreads)
        Configures the embedded web server's thread pool.
        Parameters:
        maxThreads - max nbr of threads.
        Returns:
        the object with the embedded web server's thread pool configured
      • threadPool

        public Service threadPool​(int maxThreads,
                                  int minThreads,
                                  int idleTimeoutMillis)
        Configures the embedded web server's thread pool.
        Parameters:
        maxThreads - max nbr of threads.
        minThreads - min nbr of threads.
        idleTimeoutMillis - thread idle timeout (ms).
        Returns:
        the object with the embedded web server's thread pool configured
      • staticFileLocation

        public Service staticFileLocation​(java.lang.String folder)
        Sets the folder in classpath serving static files. Observe: this method must be called before all other methods.
        Parameters:
        folder - the folder in classpath.
        Returns:
        the object with folder set
      • externalStaticFileLocation

        public Service externalStaticFileLocation​(java.lang.String externalFolder)
        Sets the external folder serving static files. Observe: this method must be called before all other methods.
        Parameters:
        externalFolder - the external folder serving static files.
        Returns:
        the object with external folder set
      • unmap

        public boolean unmap​(java.lang.String path)
        Unmaps a particular route from the collection of those that have been previously routed. Search for previously established routes using the given path and unmaps any matches that are found.
        Parameters:
        path - the route path
        Returns:
        true if this is a matching route which has been previously routed
        Throws:
        java.lang.IllegalArgumentException - if path is null or blank
      • unmap

        public boolean unmap​(java.lang.String path,
                             java.lang.String httpMethod)
        Unmaps a particular route from the collection of those that have been previously routed. Search for previously established routes using the given path and HTTP method, unmaps any matches that are found.
        Parameters:
        path - the route path
        httpMethod - the http method
        Returns:
        true if this is a matching route that has been previously routed
        Throws:
        java.lang.IllegalArgumentException - if path is null or blank or if httpMethod is null, blank, or an invalid HTTP method
      • webSocketIdleTimeoutMillis

        public Service webSocketIdleTimeoutMillis​(int timeoutMillis)
        Sets the max idle timeout in milliseconds for WebSocket connections.
        Parameters:
        timeoutMillis - The max idle timeout in milliseconds.
        Returns:
        the object with max idle timeout set for WebSocket connections
      • notFound

        public void notFound​(java.lang.String page)
        Maps 404 errors to the provided custom page
        Parameters:
        page - the custom 404 error page.
      • internalServerError

        public void internalServerError​(java.lang.String page)
        Maps 500 internal server errors to the provided custom page
        Parameters:
        page - the custom 500 internal server error page.
      • notFound

        public void notFound​(Route route)
        Maps 404 errors to the provided route.
      • internalServerError

        public void internalServerError​(Route route)
        Maps 500 internal server errors to the provided route.
      • awaitInitialization

        public void awaitInitialization()
        Waits for the spark server to be initialized. If it's already initialized will return immediately
      • throwBeforeRouteMappingException

        private void throwBeforeRouteMappingException()
      • stop

        public void stop()
        Stops the Spark server and clears all routes.
      • awaitStop

        public void awaitStop()
        Waits for the Spark server to stop. Warning: this method should not be called from a request handler.
      • initiateStop

        private void initiateStop()
      • path

        public void path​(java.lang.String path,
                         RouteGroup routeGroup)
        Add a path-prefix to the routes declared in the routeGroup The path() method adds a path-fragment to a path-stack, adds routes from the routeGroup, then pops the path-fragment again. It's used for separating routes into groups, for example: path("/api/email", () -> { ....post("/add", EmailApi::addEmail); ....put("/change", EmailApi::changeEmail); ....etc }); Multiple path() calls can be nested.
        Parameters:
        path - the path to prefix routes with
        routeGroup - group of routes (can also contain path() calls)
      • getPaths

        public java.lang.String getPaths()
      • routes

        public java.util.List<RouteMatch> routes()
        Returns:
        all routes information from this service
      • addRoute

        public void addRoute​(HttpMethod httpMethod,
                             RouteImpl route)
        Description copied from class: Routable
        Adds a route
        Specified by:
        addRoute in class Routable
        Parameters:
        httpMethod - the HTTP method
        route - the route implementation
      • addFilter

        public void addFilter​(HttpMethod httpMethod,
                              FilterImpl filter)
        Description copied from class: Routable
        Adds a filter
        Specified by:
        addFilter in class Routable
        Parameters:
        httpMethod - the HTTP method
        filter - the route implementation
      • addRoute

        @Deprecated
        public void addRoute​(java.lang.String httpMethod,
                             RouteImpl route)
        Deprecated.
        Specified by:
        addRoute in class Routable
      • addFilter

        @Deprecated
        public void addFilter​(java.lang.String httpMethod,
                              FilterImpl filter)
        Deprecated.
        Specified by:
        addFilter in class Routable
      • init

        public void init()
      • initializeRouteMatcher

        private void initializeRouteMatcher()
      • exception

        public <T extends java.lang.Exception> void exception​(java.lang.Class<T> exceptionClass,
                                                              ExceptionHandler<? super T> handler)
        Maps an exception handler to be executed when an exception occurs during routing
        Parameters:
        exceptionClass - the exception class
        handler - The handler
      • halt

        public HaltException halt()
        Immediately stops a request within a filter or route NOTE: When using this don't catch exceptions of type HaltException, or if catched, re-throw otherwise halt will not work
        Returns:
        HaltException object
      • halt

        public HaltException halt​(int status)
        Immediately stops a request within a filter or route with specified status code NOTE: When using this don't catch exceptions of type HaltException, or if catched, re-throw otherwise halt will not work
        Parameters:
        status - the status code
        Returns:
        HaltException object with status code set
      • halt

        public HaltException halt​(java.lang.String body)
        Immediately stops a request within a filter or route with specified body content NOTE: When using this don't catch exceptions of type HaltException, or if catched, re-throw otherwise halt will not work
        Parameters:
        body - The body content
        Returns:
        HaltException object with body set
      • halt

        public HaltException halt​(int status,
                                  java.lang.String body)
        Immediately stops a request within a filter or route with specified status code and body content NOTE: When using this don't catch exceptions of type HaltException, or if catched, re-throw otherwise halt will not work
        Parameters:
        status - The status code
        body - The body content
        Returns:
        HaltException object with status and body set
      • initExceptionHandler

        public void initExceptionHandler​(java.util.function.Consumer<java.lang.Exception> initExceptionHandler)
        Overrides default exception handler during initialization phase
        Parameters:
        initExceptionHandler - The custom init exception handler