Class MuServerBuilder
- java.lang.Object
-
- io.muserver.MuServerBuilder
-
public class MuServerBuilder extends java.lang.Object
A builder for creating a web server.
Use the
withXXX()
methods to set the ports, config, and request handlers needed.
-
-
Constructor Summary
Constructors Constructor Description MuServerBuilder()
-
Method Summary
All Methods Static Methods Instance Methods Concrete Methods Deprecated Methods Modifier and Type Method Description MuServerBuilder
addAsyncHandler(AsyncMuHandler handler)
Deprecated.For async handling, add a normalMuHandler
and callMuRequest.handleAsync()
MuServerBuilder
addHandler(Method method, java.lang.String uriTemplate, RouteHandler handler)
Registers a new handler that will only be called if it matches the given route infoMuServerBuilder
addHandler(MuHandler handler)
Adds a request handler.MuServerBuilder
addHandler(MuHandlerBuilder handler)
Adds a request handler.MuServerBuilder
addResponseCompleteListener(ResponseCompleteListener listener)
Adds a listener that is notified when each response completesMuServerBuilder
addShutdownHook(boolean stopServerOnShutdown)
static MuServerBuilder
httpServer()
Creates a new server builder which will run as HTTP on a random port.static MuServerBuilder
httpsServer()
Creates a new server builder which will run as HTTPS on a random port.static MuServerBuilder
muServer()
Creates a new server builder.MuServer
start()
Creates and starts this server.java.lang.String
toString()
MuServerBuilder
withExceptionHandler(UnhandledExceptionHandler exceptionHandler)
Sets the handler to use for exceptions thrown by other handlers, allowing for things such as custom error pages.MuServerBuilder
withGzip(long minimumGzipSize, java.util.Set<java.lang.String> mimeTypesToGzip)
Enables gzip for files of at least the specified size that match the given mime-types.MuServerBuilder
withGzipEnabled(boolean enabled)
Enables gzip for certain resource types.MuServerBuilder
withHandlerExecutor(java.util.concurrent.ExecutorService executor)
Sets the thread executor service to run requests on.MuServerBuilder
withHttp2Config(Http2Config http2Config)
Sets the configuration for HTTP2MuServerBuilder
withHttp2Config(Http2ConfigBuilder http2Config)
Sets the configuration for HTTP2MuServerBuilder
withHttpConnection(int port)
Deprecated.UsewithHttpPort(int)
insteadMuServerBuilder
withHttpDisabled()
Deprecated.It is off by default so this is not needed.MuServerBuilder
withHttpPort(int port)
MuServerBuilder
withHttpsConfig(HttpsConfigBuilder httpsConfig)
Sets the HTTPS config.MuServerBuilder
withHttpsConfig(SSLContextBuilder sslContext)
Deprecated.UsewithHttpsConfig(HttpsConfigBuilder)
insteadMuServerBuilder
withHttpsConfig(javax.net.ssl.SSLContext sslContext)
Deprecated.This won't be supported in the future.MuServerBuilder
withHttpsConnection(int port, javax.net.ssl.SSLContext sslEngine)
Deprecated.usewithHttpsPort(int)
andwithHttpsConfig(SSLContext)
instead.MuServerBuilder
withHttpsPort(int port)
Sets the HTTPS port to use.MuServerBuilder
withIdleTimeout(long duration, java.util.concurrent.TimeUnit unit)
Sets the idle timeout for connections.MuServerBuilder
withInterface(java.lang.String host)
Use this to specify which network interface to bind to.MuServerBuilder
withMaxHeadersSize(int size)
Specifies the maximum size in bytes of the HTTP request headers.MuServerBuilder
withMaxRequestSize(long maxSizeInBytes)
The maximum allowed request body size.MuServerBuilder
withMaxUrlSize(int size)
The maximum length that a URL can be.MuServerBuilder
withNioThreads(int nioThreads)
The number of nio threads to handle requests.MuServerBuilder
withRateLimiter(RateLimitSelector selector)
Adds a rate limiter to incoming requests.MuServerBuilder
withRequestTimeout(long duration, java.util.concurrent.TimeUnit unit)
Sets the idle timeout for reading request bodies.
-
-
-
Method Detail
-
withHttpPort
public MuServerBuilder withHttpPort(int port)
- Parameters:
port
- The HTTP port to use. A value of 0 will have a random port assigned; a value of -1 will result in no HTTP connector.- Returns:
- The current Mu Server Builder
-
withInterface
public MuServerBuilder withInterface(java.lang.String host)
Use this to specify which network interface to bind to.- Parameters:
host
- The host to bind to, for example"127.0.0.1"
to restrict connections from localhost only, or"0.0.0.0"
to allow connections from the local network.- Returns:
- The current Mu Server Builder
-
addShutdownHook
public MuServerBuilder addShutdownHook(boolean stopServerOnShutdown)
- Parameters:
stopServerOnShutdown
- If true, then a shutdown hook which stops this server will be added to the JVM Runtime- Returns:
- The current Mu Server Builder
-
withHttpConnection
@Deprecated public MuServerBuilder withHttpConnection(int port)
Deprecated.UsewithHttpPort(int)
instead- Parameters:
port
- The HTTP port to use. A value of 0 will have a random port assigned; a value of -1 will result in no HTTP connector.- Returns:
- The current Mu Server Builder
-
withGzipEnabled
public MuServerBuilder withGzipEnabled(boolean enabled)
Enables gzip for certain resource types. The default istrue
. By default, the gzippable resource types are taken fromResourceType.getResourceTypes()
whereResourceType.gzip
istrue
.- Parameters:
enabled
- True to enable; false to disable- Returns:
- The current Mu Server builder
- See Also:
withGzip(long, Set)
-
withGzip
public MuServerBuilder withGzip(long minimumGzipSize, java.util.Set<java.lang.String> mimeTypesToGzip)
Enables gzip for files of at least the specified size that match the given mime-types. By default, gzip is enabled for text-based mime types over 1400 bytes. It is recommended to keep the defaults and only use this method if you have very specific requirements around GZIP.- Parameters:
minimumGzipSize
- The size in bytes before gzip is used. The default is 1400.mimeTypesToGzip
- The mime-types that should be gzipped. In general, only text files should be gzipped.- Returns:
- The current Mu Server Builder
-
withHttpDisabled
@Deprecated public MuServerBuilder withHttpDisabled()
Deprecated.It is off by default so this is not needed.Turns off HTTP.- Returns:
- The current builder.
-
withHttpsConnection
@Deprecated public MuServerBuilder withHttpsConnection(int port, javax.net.ssl.SSLContext sslEngine)
Deprecated.usewithHttpsPort(int)
andwithHttpsConfig(SSLContext)
instead.- Parameters:
port
- The portsslEngine
- The SSL Context- Returns:
- The builder
-
withHttpsConfig
@Deprecated public MuServerBuilder withHttpsConfig(javax.net.ssl.SSLContext sslContext)
Deprecated.This won't be supported in the future. Instead, use aHttpsConfigBuilder
to set up HTTPS.Sets the HTTPS config. Defaults toSSLContextBuilder.unsignedLocalhostCert()
- Parameters:
sslContext
- An SSL Context.- Returns:
- The current Mu Server Builder
- See Also:
SSLContextBuilder
-
withHttpsConfig
@Deprecated public MuServerBuilder withHttpsConfig(SSLContextBuilder sslContext)
Deprecated.UsewithHttpsConfig(HttpsConfigBuilder)
insteadSets the HTTPS config. Defaults toHttpsConfigBuilder.unsignedLocalhost()
}- Parameters:
sslContext
- An SSL Context builder.- Returns:
- The current Mu Server Builder
- See Also:
SSLContextBuilder
-
withHttpsConfig
public MuServerBuilder withHttpsConfig(HttpsConfigBuilder httpsConfig)
Sets the HTTPS config. Defaults toHttpsConfigBuilder.unsignedLocalhost()
}- Parameters:
httpsConfig
- An HTTPS Config builder.- Returns:
- The current Mu Server Builder
-
withHttpsPort
public MuServerBuilder withHttpsPort(int port)
Sets the HTTPS port to use. To set the SSL certificate config, seewithHttpsConfig(SSLContextBuilder)
- Parameters:
port
- A value of 0 will result in a random port being assigned; a value of -1 will disable HTTPS.- Returns:
- The current Mu Server builder
-
withHttp2Config
public MuServerBuilder withHttp2Config(Http2Config http2Config)
Sets the configuration for HTTP2- Parameters:
http2Config
- A config- Returns:
- The current Mu Server builder
- See Also:
Http2ConfigBuilder
-
withHttp2Config
public MuServerBuilder withHttp2Config(Http2ConfigBuilder http2Config)
Sets the configuration for HTTP2- Parameters:
http2Config
- A config- Returns:
- The current Mu Server builder
- See Also:
Http2ConfigBuilder
-
withHandlerExecutor
public MuServerBuilder withHandlerExecutor(java.util.concurrent.ExecutorService executor)
Sets the thread executor service to run requests on. By defaultExecutors.newCachedThreadPool()
is used.- Parameters:
executor
- The executor service to use to handle requests- Returns:
- The current Mu Server builder
-
withNioThreads
public MuServerBuilder withNioThreads(int nioThreads)
The number of nio threads to handle requests.
Generally only a small number is required as NIO threads are only used for non-blocking reads and writes of data. Request handlers are executed on a separate thread pool which can be specified with
withHandlerExecutor(ExecutorService)
.Note that websocket callbacks are handled on these NIO threads.
- Parameters:
nioThreads
- The nio threads. Default is 2 * processor's count but not more than 16- Returns:
- The current Mu Server builder
-
withMaxHeadersSize
public MuServerBuilder withMaxHeadersSize(int size)
Specifies the maximum size in bytes of the HTTP request headers. Defaults to 8192.
If a request has headers exceeding this value, it will be rejected and a
431
status code will be returned. Large values increase the risk of Denial-of-Service attacks due to the extra memory allocated in each request.It is recommended to not specify a value unless you are finding legitimate requests are being rejected with
413
errors.- Parameters:
size
- The maximum size in bytes that can be used for headers.- Returns:
- The current Mu Server builder.
-
withMaxUrlSize
public MuServerBuilder withMaxUrlSize(int size)
The maximum length that a URL can be. If it exceeds this value, a414
error is returned to the client. The default value is 8175.- Parameters:
size
- The maximum number of characters allowed in URLs sent to this server.- Returns:
- The current Mu Server builder
-
withMaxRequestSize
public MuServerBuilder withMaxRequestSize(long maxSizeInBytes)
The maximum allowed request body size. If exceeded, a 413 will be returned.- Parameters:
maxSizeInBytes
- The maximum request body size allowed, in bytes. The default is 24MB.- Returns:
- The current Mu Server builder
-
withIdleTimeout
public MuServerBuilder withIdleTimeout(long duration, java.util.concurrent.TimeUnit unit)
Sets the idle timeout for connections. If no bytes are sent or received within this time then the connection is closed.The default is 5 minutes.
- Parameters:
duration
- The allowed timeout duration, or 0 to disable timeouts.unit
- The unit of the duration.- Returns:
- This builder
- See Also:
withRequestTimeout(long, TimeUnit)
-
withRequestTimeout
public MuServerBuilder withRequestTimeout(long duration, java.util.concurrent.TimeUnit unit)
Sets the idle timeout for reading request bodies. If a slow client that is uploading a request body pauses for this amount of time, the request will be closed (if the response has not started, the client will receive a 408 error).The default is 2 minutes.
- Parameters:
duration
- The allowed timeout duration, or 0 to disable timeouts.unit
- The unit of the duration.- Returns:
- This builder
- See Also:
withIdleTimeout(long, TimeUnit)
-
addAsyncHandler
@Deprecated public MuServerBuilder addAsyncHandler(AsyncMuHandler handler)
Deprecated.For async handling, add a normalMuHandler
and callMuRequest.handleAsync()
Throws an exception. Do not use.
- Parameters:
handler
- Ignored- Returns:
- Never returns
-
addHandler
public MuServerBuilder addHandler(MuHandlerBuilder handler)
Adds a request handler.
Note that handlers are executed in the order added to the builder, but all async handlers are executed before synchronous handlers.
- Parameters:
handler
- A handler builder. Thebuild()
method will be called on this to create the handler. If null, then no handler is added.- Returns:
- The current Mu Server Handler.
- See Also:
addHandler(Method, String, RouteHandler)
-
addHandler
public MuServerBuilder addHandler(MuHandler handler)
Adds a request handler.
Note that handlers are executed in the order added to the builder, but all async handlers are executed before synchronous handlers.
- Parameters:
handler
- The handler to add. If null, then no handler is added.- Returns:
- The current Mu Server Handler.
- See Also:
addHandler(Method, String, RouteHandler)
-
addHandler
public MuServerBuilder addHandler(Method method, java.lang.String uriTemplate, RouteHandler handler)
Registers a new handler that will only be called if it matches the given route info- Parameters:
method
- The method to match, ornull
to accept any method.uriTemplate
- A URL template. Supports plain URLs like/abc
or paths with named parameters such as/abc/{id}
or named parameters with regexes such as/abc/{id : [0-9]+}
where the named parameter values can be accessed with thepathParams
parameter in the route handler.handler
- The handler to invoke if the method and URI matches. If null, then no handler is added.- Returns:
- Returns the server builder
-
addResponseCompleteListener
public MuServerBuilder addResponseCompleteListener(ResponseCompleteListener listener)
Adds a listener that is notified when each response completes- Parameters:
listener
- A listener. If null, then nothing is added.- Returns:
- Returns the server builder
-
withRateLimiter
public MuServerBuilder withRateLimiter(RateLimitSelector selector)
Adds a rate limiter to incoming requests.
The selector specified in this method allows you to control the limit buckets that are used. For example, to set a limit on client IP addresses the selector would return
MuRequest.remoteAddress()
.The selector also specifies the number of requests allowed for the bucket per time period, such that different buckets can have different limits.
The following example shows how to allow 100 requests per second per IP address:
MuServerBuilder.httpsServer() .withRateLimiter(request -> RateLimit.builder() .withBucket(request.remoteAddress()) .withRate(100) .withWindow(1, TimeUnit.SECONDS) .build())
Note that multiple limiters can be added which allows different limits across different dimensions. For example, you may allow 100 requests per second based on IP address and also a limit based on a cookie, request path, or other value.
- Parameters:
selector
- A function that returns a string based on the request, or null to not have a limit applied- Returns:
- This builder
-
withExceptionHandler
public MuServerBuilder withExceptionHandler(UnhandledExceptionHandler exceptionHandler)
Sets the handler to use for exceptions thrown by other handlers, allowing for things such as custom error pages.Note that if the response has already started sending data, you will not be able to add a custom error message. In this case, you may want to allow for the default error handling by returning
false
.The following shows a pattern to filter out certain errors:
muServerBuilder.withExceptionHandler((request, response, exception) -> { if (response.hasStartedSendingData()) return false; // cannot customise the response if (exception instanceof NotAuthorizedException) return false; response.contentType(ContentTypes.TEXT_PLAIN_UTF8); response.write("Oh I'm worry, there was a problem"); return true; })
- Parameters:
exceptionHandler
- The handler to be called when an unhandled exception is encountered- Returns:
- This builder
-
muServer
public static MuServerBuilder muServer()
Creates a new server builder. CallwithHttpsPort(int)
orwithHttpPort(int)
to specify the port to use, and callstart()
to start the server.- Returns:
- A new Mu Server builder
-
httpServer
public static MuServerBuilder httpServer()
Creates a new server builder which will run as HTTP on a random port.- Returns:
- A new Mu Server builder with the HTTP port set to 0
-
httpsServer
public static MuServerBuilder httpsServer()
Creates a new server builder which will run as HTTPS on a random port.- Returns:
- A new Mu Server builder with the HTTPS port set to 0
-
start
public MuServer start()
Creates and starts this server. An exception is thrown if it fails to start.- Returns:
- The running server.
-
toString
public java.lang.String toString()
- Overrides:
toString
in classjava.lang.Object
-
-