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 class
Service.StaticFiles
Provides static files utility methods.
-
Field Summary
Fields Modifier and Type Field Description protected static java.lang.String
DEFAULT_ACCEPT_TYPE
private java.lang.Object
embeddedServerIdentifier
private ExceptionMapper
exceptionMapper
private java.util.function.Consumer<java.lang.Exception>
initExceptionHandler
protected boolean
initialized
private java.util.concurrent.CountDownLatch
initLatch
protected java.lang.String
ipAddress
private static org.slf4j.Logger
LOG
protected int
maxThreads
protected int
minThreads
protected java.util.Deque<java.lang.String>
pathDeque
protected int
port
Redirect
redirect
protected Routes
routes
protected EmbeddedServer
server
static int
SPARK_DEFAULT_PORT
protected SslStores
sslStores
Service.StaticFiles
staticFiles
private StaticFilesConfiguration
staticFilesConfiguration
private java.util.concurrent.CountDownLatch
stopLatch
protected int
threadIdleTimeoutMillis
protected java.util.Map<java.lang.String,WebSocketHandlerWrapper>
webSocketHandlers
protected java.util.Optional<java.lang.Integer>
webSocketIdleTimeoutMillis
-
Constructor Summary
Constructors Modifier Constructor Description private
Service()
-
Method Summary
All Methods Static Methods Instance Methods Concrete Methods Deprecated Methods Modifier and Type Method Description int
activeThreadCount()
void
addFilter(java.lang.String httpMethod, FilterImpl filter)
Deprecated.void
addFilter(HttpMethod httpMethod, FilterImpl filter)
Adds a filtervoid
addRoute(java.lang.String httpMethod, RouteImpl route)
Deprecated.void
addRoute(HttpMethod httpMethod, RouteImpl route)
Adds a routeprivate void
addWebSocketHandler(java.lang.String path, WebSocketHandlerWrapper handlerWrapper)
void
awaitInitialization()
Waits for the spark server to be initialized.void
awaitStop()
Waits for the Spark server to stop.java.lang.Object
embeddedServerIdentifier()
Get the identifier used to select the EmbeddedServer; null for the default.void
embeddedServerIdentifier(java.lang.Object obj)
Set the identifier used to select the EmbeddedServer; null for the default.<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 routingService
externalStaticFileLocation(java.lang.String externalFolder)
Sets the external folder serving static files.java.lang.String
getPaths()
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 workHaltException
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 workHaltException
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 workHaltException
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 workprivate boolean
hasMultipleHandlers()
static Service
ignite()
Creates a new Service (a Spark instance).void
init()
void
initExceptionHandler(java.util.function.Consumer<java.lang.Exception> initExceptionHandler)
Overrides default exception handler during initialization phaseprivate void
initializeRouteMatcher()
private void
initiateStop()
void
internalServerError(java.lang.String page)
Maps 500 internal server errors to the provided custom pagevoid
internalServerError(Route route)
Maps 500 internal server errors to the provided route.Service
ipAddress(java.lang.String ipAddress)
Set the IP address that Spark should listen on.void
notFound(java.lang.String page)
Maps 404 errors to the provided custom pagevoid
notFound(Route route)
Maps 404 errors to the provided route.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.int
port()
Retrieves the port that Spark is listening on.Service
port(int port)
Set the port that Spark should listen on.java.util.List<RouteMatch>
routes()
Service
secure(java.lang.String keystoreFile, java.lang.String keystorePassword, java.lang.String truststoreFile, java.lang.String truststorePassword)
Set the connection to be secure, using the specified keystore and truststore.Service
secure(java.lang.String keystoreFile, java.lang.String keystorePassword, java.lang.String truststoreFile, java.lang.String truststorePassword, boolean needsClientCert)
Set the connection to be secure, using the specified keystore and truststore.Service
secure(java.lang.String keystoreFile, java.lang.String keystorePassword, java.lang.String certAlias, java.lang.String truststoreFile, java.lang.String truststorePassword)
Set the connection to be secure, using the specified keystore and truststore.Service
secure(java.lang.String keystoreFile, java.lang.String keystorePassword, java.lang.String certAlias, java.lang.String truststoreFile, java.lang.String truststorePassword, boolean needsClientCert)
Set the connection to be secure, using the specified keystore and truststore.Service
staticFileLocation(java.lang.String folder)
Sets the folder in classpath serving static files.void
stop()
Stops the Spark server and clears all routes.Service
threadPool(int maxThreads)
Configures the embedded web server's thread pool.Service
threadPool(int maxThreads, int minThreads, int idleTimeoutMillis)
Configures the embedded web server's thread pool.private void
throwBeforeRouteMappingException()
boolean
unmap(java.lang.String path)
Unmaps a particular route from the collection of those that have been previously routed.boolean
unmap(java.lang.String path, java.lang.String httpMethod)
Unmaps a particular route from the collection of those that have been previously routed.void
webSocket(java.lang.String path, java.lang.Class<?> handlerClass)
Maps the given path to the given WebSocket handler class.void
webSocket(java.lang.String path, java.lang.Object handler)
Maps the given path to the given WebSocket handler instance.Service
webSocketIdleTimeoutMillis(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
-
webSocketHandlers
protected java.util.Map<java.lang.String,WebSocketHandlerWrapper> webSocketHandlers
-
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
-
embeddedServerIdentifier
private java.lang.Object embeddedServerIdentifier
-
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
-
embeddedServerIdentifier
public void embeddedServerIdentifier(java.lang.Object obj)
Set the identifier used to select the EmbeddedServer; null for the default.- Parameters:
obj
- the identifier passed toEmbeddedServers
.
-
embeddedServerIdentifier
public java.lang.Object embeddedServerIdentifier()
Get the identifier used to select the EmbeddedServer; null for the default.- Parameters:
obj
- the identifier passed toEmbeddedServers
.
-
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
-
secure
public Service secure(java.lang.String keystoreFile, java.lang.String keystorePassword, java.lang.String truststoreFile, java.lang.String truststorePassword)
Set the connection to be secure, using the specified keystore and truststore. This has to be called before any route mapping is done. You have to supply a keystore file, truststore file is optional (keystore will be reused). By default, client certificates are not checked. This method is only relevant when using embedded Jetty servers. It should not be used if you are using Servlets, where you will need to secure the connection in the servlet container- Parameters:
keystoreFile
- The keystore file location as stringkeystorePassword
- the password for the keystoretruststoreFile
- the truststore file location as string, leave null to reuse keystoretruststorePassword
- the trust store password- Returns:
- the object with connection set to be secure
-
secure
public Service secure(java.lang.String keystoreFile, java.lang.String keystorePassword, java.lang.String certAlias, java.lang.String truststoreFile, java.lang.String truststorePassword)
Set the connection to be secure, using the specified keystore and truststore. This has to be called before any route mapping is done. You have to supply a keystore file, truststore file is optional (keystore will be reused). By default, client certificates are not checked. This method is only relevant when using embedded Jetty servers. It should not be used if you are using Servlets, where you will need to secure the connection in the servlet container- Parameters:
keystoreFile
- The keystore file location as stringkeystorePassword
- the password for the keystorecertAlias
- the default certificate AliastruststoreFile
- the truststore file location as string, leave null to reuse keystoretruststorePassword
- the trust store password- Returns:
- the object with connection set to be secure
-
secure
public Service secure(java.lang.String keystoreFile, java.lang.String keystorePassword, java.lang.String truststoreFile, java.lang.String truststorePassword, boolean needsClientCert)
Set the connection to be secure, using the specified keystore and truststore. This has to be called before any route mapping is done. You have to supply a keystore file, truststore file is optional (keystore will be reused). This method is only relevant when using embedded Jetty servers. It should not be used if you are using Servlets, where you will need to secure the connection in the servlet container- Parameters:
keystoreFile
- The keystore file location as stringkeystorePassword
- the password for the keystoretruststoreFile
- the truststore file location as string, leave null to reuse keystoreneedsClientCert
- Whether to require client certificate to be supplied in requesttruststorePassword
- the trust store password- Returns:
- the object with connection set to be secure
-
secure
public Service secure(java.lang.String keystoreFile, java.lang.String keystorePassword, java.lang.String certAlias, java.lang.String truststoreFile, java.lang.String truststorePassword, boolean needsClientCert)
Set the connection to be secure, using the specified keystore and truststore. This has to be called before any route mapping is done. You have to supply a keystore file, truststore file is optional (keystore will be reused). This method is only relevant when using embedded Jetty servers. It should not be used if you are using Servlets, where you will need to secure the connection in the servlet container- Parameters:
keystoreFile
- The keystore file location as stringkeystorePassword
- the password for the keystorecertAlias
- the default certificate AliastruststoreFile
- the truststore file location as string, leave null to reuse keystoreneedsClientCert
- Whether to require client certificate to be supplied in requesttruststorePassword
- the trust store password- Returns:
- the object with connection set to be secure
-
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
-
webSocket
public void webSocket(java.lang.String path, java.lang.Class<?> handlerClass)
Maps the given path to the given WebSocket handler class.This is currently only available in the embedded server mode.
- Parameters:
path
- the WebSocket path.handlerClass
- the handler class that will manage the WebSocket connection to the given path.
-
webSocket
public void webSocket(java.lang.String path, java.lang.Object handler)
Maps the given path to the given WebSocket handler instance.This is currently only available in the embedded server mode.
- Parameters:
path
- the WebSocket path.handler
- the handler instance that will manage the WebSocket connection to the given path.
-
addWebSocketHandler
private void addWebSocketHandler(java.lang.String path, WebSocketHandlerWrapper handlerWrapper)
-
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()
-
hasMultipleHandlers
private boolean hasMultipleHandlers()
-
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:Routable
Adds a route
-
addFilter
public void addFilter(HttpMethod httpMethod, FilterImpl filter)
Description copied from class:Routable
Adds 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()
-
activeThreadCount
public int activeThreadCount()
- Returns:
- The approximate number of currently active threads in the embedded Jetty server
-
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
-
-