ServerApplication

scamper.http.server.ServerApplication
class ServerApplication extends Router

Defines server application for creating HttpServer.

Default Configuration

The initial application is constructed with the following default configuration:

Key Value
backlogSize 50
poolSize Runtime.getRuntime().availableProcessors()
queueSize Runtime.getRuntime().availableProcessors() * 4
bufferSize 8192
readTimeout 5000
headerLimit 100
keepAlive (Not configured)
secure (Not configured)
trigger (Not configured)
incoming (Not configured)
outgoing (Not configured)
recover (Sends 500 Internal Server Error)

Building HTTP Server

ServerApplication is a mutable structure. With each applied change, the application is modified and returned. After the desired configuration is applied, a server is created using a factory method.

import java.io.File

import scala.language.implicitConversions

import scamper.http.{ BodyParser, stringToEntity }
import scamper.http.ResponseStatus.Registry.{ NotFound, NoContent, Ok }
import scamper.http.server.{ *, given }

// Get server application
val app = ServerApplication()

// Add request handler to log all requests
app.incoming { req =>
 println(req.startLine)
 req
}

// Add request handler for GET requests at specified path
app.get("/about") { req =>
 Ok("This server is powered by Scamper.")
}

// Add request handler for PUT requests at specified path
app.put("/data/:id") { req =>
 def update(id: Int, data: String): Boolean = ???

 given BodyParser[String] = BodyParser.string()

 // Get path parameter
 val id = req.pathParams.getInt("id")

 update(id, req.as[String]) match
   case true  => NoContent()
   case false => NotFound()
}

// Serve files from file directory
app.files("/main", File("/path/to/public"))

// Gzip response body if not empty
app.outgoing { res =>
 res.body.isKnownEmpty match
   case true  => res
   case false => res.setGzipContentEncoding()
}

// Create server
val server = app.toHttpServer(8080)

try
 printf("Host: %s%n", server.host)
 printf("Port: %d%n", server.port)

 // Run server for 60 seconds
 Thread.sleep(60 * 1000)
finally
 // Close server when done
 server.close()

Attributes

Graph
Supertypes
trait Router
class Object
trait Matchable
class Any

Members list

Value members

Concrete methods

def backlogSize(size: Int): ServerApplication.this.type

Sets backlog size.

Sets backlog size.

The backlogSize specifies the maximum number of incoming connections that can wait before being accepted. Incoming connections that exceed this limit are refused.

Value parameters

size

backlog size

Attributes

Returns

this application

def bufferSize(size: Int): ServerApplication.this.type

Sets buffer size.

Sets buffer size.

The bufferSize specifies in bytes the size of buffer used when reading from and writing to socket.

The bufferSize also determines the maximum length of any header line. Incoming requests containing a header that exceeds this limit are sent 431 (Request Header Fields Too Large).

Value parameters

size

buffer size in bytes

Attributes

Returns

this application

Note

bufferSize is also used as the optimal chunk size when writing a response with chunked transfer encoding.

def headerLimit(limit: Int): ServerApplication.this.type

Sets header limit.

Sets header limit.

The headerLimit specifies the maximum number of headers allowed. Incoming requests containing headers that exceed this limit are sent 431 (Request Header Fields Too Large).

Value parameters

limit

header limit

Attributes

Returns

this application

def incoming(handler: RequestHandler): ServerApplication.this.type

Adds supplied request handler.

Adds supplied request handler.

The handler is appended to existing request handler chain.

Attributes

def incoming(path: String, methods: RequestMethod*)(handler: RequestHandler): ServerApplication.this.type

Adds supplied handler for requests with given router path and any of specified request methods.

Adds supplied handler for requests with given router path and any of specified request methods.

The handler is appended to existing request handler chain.

Attributes

Enables persistent connections using specified parameters.

Enables persistent connections using specified parameters.

Value parameters

params

keep-alive parameters

Attributes

Returns

this application

def keepAlive(timeout: Int, max: Int): ServerApplication.this.type

Enables persistent connections using specified timeout and max.

Enables persistent connections using specified timeout and max.

Value parameters

max

maximum number of requests per connection

timeout

idle timeout in seconds

Attributes

Returns

this application

def logger(name: String): ServerApplication.this.type

Sets logger name.

Sets logger name.

Value parameters

name

logger name

Attributes

def mountPath: String

Gets mount path.

Gets mount path.

Attributes

Returns

"/"

def outgoing(filter: ResponseFilter): ServerApplication.this.type

Adds supplied response filter.

Adds supplied response filter.

The filter is appended to existing response filter chain.

Attributes

def poolSize(size: Int): ServerApplication.this.type

Sets pool size.

Sets pool size.

The poolSize specifies the maximum number of requests processed concurrently.

Value parameters

size

pool size

Attributes

Returns

this application

def queueSize(size: Int): ServerApplication.this.type

Sets queue size.

Sets queue size.

The queueSize specifies the maximum number of requests that can be queued for processing. Incoming requests that exceed this limit are sent 503 (Service Unavailable).

Value parameters

size

queue size

Attributes

Returns

this application

def readTimeout(timeout: Int): ServerApplication.this.type

Sets read timeout.

Sets read timeout.

The readTimeout specifies how long a read from a socket blocks before it times out, whereafter 408 (Request Timeout) is sent to client.

Value parameters

timeout

read timeout in milliseconds

Attributes

Returns

this application

def recover(handler: ErrorHandler): ServerApplication.this.type

Adds error handler.

Adds error handler.

The handler is appended to existing error handler chain.

Attributes

def reset(): ServerApplication.this.type

Resets router.

Resets router.

Attributes

def secure(keyStore: File, password: String, storeType: String): ServerApplication.this.type

Sets key store to be used for SSL/TLS.

Sets key store to be used for SSL/TLS.

Value parameters

keyStore

server key store

password

key store password

storeType

key store type (i.e., JKS, JCEKS, etc.)

Attributes

Returns

this application

def secure(keyStore: File, password: Array[Char], storeType: String): ServerApplication.this.type

Sets key store to be used for SSL/TLS.

Sets key store to be used for SSL/TLS.

Value parameters

keyStore

server key store

password

key store password

storeType

key store type (i.e., JKS, JCEKS, etc.)

Attributes

Returns

this application

Note

The password can be discarded after invoking this method.

def secure(key: File, certificate: File): ServerApplication.this.type

Sets key and certificate to be used for SSL/TLS.

Sets key and certificate to be used for SSL/TLS.

Value parameters

certificate

public key certificate

key

private key

Attributes

Returns

this application

def toHttpServer(port: Int): HttpServer

Creates server at given port.

Creates server at given port.

Value parameters

port

port number

Attributes

Returns

new server

def toHttpServer(host: String, port: Int): HttpServer

Creates server at given host and port.

Creates server at given host and port.

Value parameters

host

host address

port

port number

Attributes

Returns

new server

def toHttpServer(host: InetAddress, port: Int): HttpServer

Creates server at given host and port.

Creates server at given host and port.

Value parameters

host

host address

port

port number

Attributes

Returns

new server

def trigger(hook: LifecycleHook): ServerApplication.this.type

Adds server lifecycle hook.

Adds server lifecycle hook.

Attributes

Inherited methods

def delete(path: String)(handler: RequestHandler): Router.this.type

Adds supplied handler for DELETE requests to given router path.

Adds supplied handler for DELETE requests to given router path.

The handler is appended to existing request handler chain.

Value parameters

handler

request handler

path

router path

Attributes

Returns

this router

Note

If request handler implements LifecycleHook, it is also added as a lifecycle hook.

Inherited from:
Router
def files(path: String, source: File, defaults: String*): Router.this.type

Mounts file server at given path.

Mounts file server at given path.

At request time, the mount path is stripped from the router path, and the remaining path is used to locate a file in the source directory.

File Mapping Examples

Mount Path Source Directory Router Path Maps to
/images /tmp /images/logo.png /tmp/logo.png
/images /tmp /images/icons/warning.png /tmp/icons/warning.png

Value parameters

defaults

default file names used when request matches directory

path

router path at which directory is mounted

source

directory from which files are served

Attributes

Returns

this router

Note

If a request matches a directory, and if a file with one of the default file names exists in that directory, the server sends 303 (See Other) with a Location header value set to path of default file.

Inherited from:
Router
def get(path: String)(handler: RequestHandler): Router.this.type

Adds supplied handler for GET requests to given router path.

Adds supplied handler for GET requests to given router path.

The handler is appended to existing request handler chain.

Value parameters

handler

request handler

path

router path

Attributes

Returns

this router

Note

If request handler implements LifecycleHook, it is also added as a lifecycle hook.

Inherited from:
Router
def post(path: String)(handler: RequestHandler): Router.this.type

Adds supplied handler for POST requests to given router path.

Adds supplied handler for POST requests to given router path.

The handler is appended to existing request handler chain.

Value parameters

handler

request handler

path

router path

Attributes

Returns

this router

Note

If request handler implements LifecycleHook, it is also added as a lifecycle hook.

Inherited from:
Router
def put(path: String)(handler: RequestHandler): Router.this.type

Adds supplied handler for PUT requests to given router path.

Adds supplied handler for PUT requests to given router path.

The handler is appended to existing request handler chain.

Value parameters

handler

request handler

path

router path

Attributes

Returns

this router

Note

If request handler implements LifecycleHook, it is also added as a lifecycle hook.

Inherited from:
Router
def route(path: String)(app: RouterApplication): Router.this.type

Mounts router application at given path.

Mounts router application at given path.

Value parameters

app

router application

path

router path at which application is mounted

Attributes

Returns

this router

Note

If router app implements LifecycleHook, it is also added as a lifecycle hook.

Inherited from:
Router
def toAbsolutePath(path: String): String

Expands supplied router path to its absolute path.

Expands supplied router path to its absolute path.

Value parameters

path

router path

Attributes

Throws
java.lang.IllegalArgumentException

if router path is not * and does not begin with / or if it escapes mount path

Note

If * is supplied as router path, its absolute path is also *.

Inherited from:
Router
def websocket(path: String)(app: WebSocketApplication[_]): Router.this.type

Mounts WebSocket application at given path.

Mounts WebSocket application at given path.

Value parameters

app

WebSocket application

path

router path at which application is mounted

Attributes

Returns

this router

Note

If WebSocket app implements LifecycleHook, it is also added as a lifecycle hook.

Inherited from:
Router