Package io.muserver

Class 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 Detail

      • MuServerBuilder

        public MuServerBuilder()
    • 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
      • 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
      • withHttpsPort

        public MuServerBuilder withHttpsPort​(int port)
        Sets the HTTPS port to use. To set the SSL certificate config, see withHttpsConfig(HttpsConfigBuilder)
        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
      • withHandlerExecutor

        public MuServerBuilder withHandlerExecutor​(java.util.concurrent.ExecutorService executor)
        Sets the thread executor service to run requests on. By default Executors.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, a 414 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)
      • 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. The build() 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, or null 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 the pathParams 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
      • minimumGzipSize

        public long minimumGzipSize()
        Returns:
        The current value of this property
      • httpPort

        public int httpPort()
        Returns:
        The current value of this property
      • httpsPort

        public int httpsPort()
        Returns:
        The current value of this property
      • maxHeadersSize

        public int maxHeadersSize()
        Returns:
        The current value of this property
      • maxUrlSize

        public int maxUrlSize()
        Returns:
        The current value of this property
      • nioThreads

        public int nioThreads()
        Returns:
        The current value of this property
      • handlers

        public java.util.List<MuHandler> handlers()
        Returns:
        The current value of this property
      • gzipEnabled

        public boolean gzipEnabled()
        Returns:
        The current value of this property
      • mimeTypesToGzip

        public java.util.Set<java.lang.String> mimeTypesToGzip()
        Returns:
        The current value of this property
      • addShutdownHook

        public boolean addShutdownHook()
        Returns:
        The current value of this property
      • interfaceHost

        public java.lang.String interfaceHost()
        Returns:
        The current value of this property
      • httpsConfigBuilder

        public HttpsConfigBuilder httpsConfigBuilder()
        Returns:
        The current value of this property
      • http2Config

        public Http2Config http2Config()
        Returns:
        The current value of this property
      • requestReadTimeoutMillis

        public long requestReadTimeoutMillis()
        Returns:
        The current value of this property
      • idleTimeoutMills

        public long idleTimeoutMills()
        Returns:
        The current value of this property
      • executor

        public java.util.concurrent.ExecutorService executor()
        Returns:
        The current value of this property
      • maxRequestSize

        public long maxRequestSize()
        Returns:
        The current value of this property
      • responseCompleteListeners

        public java.util.List<ResponseCompleteListener> responseCompleteListeners()
        Returns:
        The current value of this property
      • rateLimiters

        public java.util.List<RateLimiter> rateLimiters()
        Returns:
        The current value of this property
      • unhandledExceptionHandler

        public UnhandledExceptionHandler unhandledExceptionHandler()
        Returns:
        The current value of this property
      • 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 class java.lang.Object