Package spark
Class Service
- java.lang.Object
-
- spark.Routable
-
- spark.Service
-
public final class Service extends Routable
Represents a Spark server "session". If a user wants multiple 'Sparks' in his application the methodignite()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");
-
-
Nested Class Summary
Nested Classes Modifier and Type Class Description classService.StaticFilesProvides static files utility methods.
-
Field Summary
Fields Modifier and Type Field Description protected static java.lang.StringDEFAULT_ACCEPT_TYPEprivate ExceptionMapperexceptionMapperprivate java.util.function.Consumer<java.lang.Exception>initExceptionHandlerprotected booleaninitializedprivate java.util.concurrent.CountDownLatchinitLatchprotected java.lang.StringipAddressprivate static org.slf4j.LoggerLOGprotected intmaxThreadsprotected intminThreadsprotected java.util.Deque<java.lang.String>pathDequeprotected intportRedirectredirectprotected Routesroutesprotected EmbeddedServerserverstatic intSPARK_DEFAULT_PORTprotected SslStoressslStoresService.StaticFilesstaticFilesprivate StaticFilesConfigurationstaticFilesConfigurationprivate java.util.concurrent.CountDownLatchstopLatchprotected intthreadIdleTimeoutMillisprotected java.util.Optional<java.lang.Integer>webSocketIdleTimeoutMillis
-
Constructor Summary
Constructors Modifier Constructor Description privateService()
-
Method Summary
All Methods Static Methods Instance Methods Concrete Methods Deprecated Methods Modifier and Type Method Description voidaddFilter(java.lang.String httpMethod, FilterImpl filter)Deprecated.voidaddFilter(HttpMethod httpMethod, FilterImpl filter)Adds a filtervoidaddRoute(java.lang.String httpMethod, RouteImpl route)Deprecated.voidaddRoute(HttpMethod httpMethod, RouteImpl route)Adds a routevoidawaitInitialization()Waits for the spark server to be initialized.voidawaitStop()Waits for the Spark server to stop.<T extends java.lang.Exception>
voidexception(java.lang.Class<T> exceptionClass, ExceptionHandler<? super T> handler)Maps an exception handler to be executed when an exception occurs during routingServiceexternalStaticFileLocation(java.lang.String externalFolder)Sets the external folder serving static files.java.lang.StringgetPaths()HaltExceptionhalt()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 workHaltExceptionhalt(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 workHaltExceptionhalt(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 workHaltExceptionhalt(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 workstatic Serviceignite()Creates a new Service (a Spark instance).voidinit()voidinitExceptionHandler(java.util.function.Consumer<java.lang.Exception> initExceptionHandler)Overrides default exception handler during initialization phaseprivate voidinitializeRouteMatcher()private voidinitiateStop()voidinternalServerError(java.lang.String page)Maps 500 internal server errors to the provided custom pagevoidinternalServerError(Route route)Maps 500 internal server errors to the provided route.ServiceipAddress(java.lang.String ipAddress)Set the IP address that Spark should listen on.voidnotFound(java.lang.String page)Maps 404 errors to the provided custom pagevoidnotFound(Route route)Maps 404 errors to the provided route.voidpath(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.intport()Retrieves the port that Spark is listening on.Serviceport(int port)Set the port that Spark should listen on.java.util.List<RouteMatch>routes()ServicestaticFileLocation(java.lang.String folder)Sets the folder in classpath serving static files.voidstop()Stops the Spark server and clears all routes.ServicethreadPool(int maxThreads)Configures the embedded web server's thread pool.ServicethreadPool(int maxThreads, int minThreads, int idleTimeoutMillis)Configures the embedded web server's thread pool.private voidthrowBeforeRouteMappingException()booleanunmap(java.lang.String path)Unmaps a particular route from the collection of those that have been previously routed.booleanunmap(java.lang.String path, java.lang.String httpMethod)Unmaps a particular route from the collection of those that have been previously routed.ServicewebSocketIdleTimeoutMillis(int timeoutMillis)Sets the max idle timeout in milliseconds for WebSocket connections.-
Methods inherited from class spark.Routable
after, after, after, afterAfter, afterAfter, before, before, before, connect, connect, connect, connect, connect, connect, defaultResponseTransformer, delete, delete, delete, delete, delete, delete, get, get, get, get, get, get, head, head, head, head, head, head, options, options, options, options, options, options, patch, patch, patch, patch, patch, patch, post, post, post, post, post, post, put, put, put, put, put, put, trace, trace, trace, trace, trace, trace
-
-
-
-
Field Detail
-
LOG
private static final org.slf4j.Logger LOG
-
SPARK_DEFAULT_PORT
public static final int SPARK_DEFAULT_PORT
- See Also:
- Constant Field Values
-
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
-
sslStores
protected SslStores sslStores
-
maxThreads
protected int maxThreads
-
minThreads
protected int minThreads
-
threadIdleTimeoutMillis
protected int threadIdleTimeoutMillis
-
webSocketIdleTimeoutMillis
protected java.util.Optional<java.lang.Integer> webSocketIdleTimeoutMillis
-
server
protected EmbeddedServer server
-
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
-
staticFiles
public final Service.StaticFiles staticFiles
-
staticFilesConfiguration
private final StaticFilesConfiguration staticFilesConfiguration
-
exceptionMapper
private final ExceptionMapper exceptionMapper
-
initExceptionHandler
private java.util.function.Consumer<java.lang.Exception> initExceptionHandler
-
-
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 pathhttpMethod- 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 withrouteGroup- 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:RoutableAdds a route
-
addFilter
public void addFilter(HttpMethod httpMethod, FilterImpl filter)
Description copied from class:RoutableAdds a filter
-
addRoute
@Deprecated public void addRoute(java.lang.String httpMethod, RouteImpl route)Deprecated.
-
addFilter
@Deprecated public void addFilter(java.lang.String httpMethod, FilterImpl filter)Deprecated.
-
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 classhandler- 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 codebody- 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
-
-