Packages

  • package root

    Provided herein is API documentation for Scamper, the HTTP library for Scala.

    Provided herein is API documentation for Scamper, the HTTP library for Scala.

    Definition Classes
    root
  • package scamper

    Defines core types.

    Defines core types.

    HTTP Messages

    At the core of Scamper is HttpMessage, which is a trait that defines the fundamental characteristics of an HTTP message. HttpRequest and HttpResponse extend the specification to define characteristics specific to their respective message types.

    An HttpRequest is created using a factory method defined in its companion object. Or you can start with a RequestMethod and use builder methods to further define the request.

    import scamper.Header
    import scamper.Implicits.stringToUri
    import scamper.RequestMethod.Registry.Get
    
    val request = Get("/motd").setHeaders(
      Header("Host: localhost:8080"),
      Header("Accept: text/plain")
    )
    
    printf("Request Method: %s%n", request.method)
    printf("Target URI: %s%n", request.target)
    
    request.headers.foreach(println)
    
    val host: Option[String] = request.getHeaderValue("Host")

    An HttpResponse is created using a factory method defined in its companion object. Or you can start with a ResponseStatus and use builder methods to further define the response.

    import scamper.{ BodyParser, Header }
    import scamper.Implicits.stringToEntity
    import scamper.ResponseStatus.Registry.Ok
    
    val response = Ok("There is an answer.").setHeaders(
      Header("Content-Type: text/plain"),
      Header("Connection: close")
    )
    
    printf("Status Code: %s%n", response.statusCode)
    printf("Reason Phrase: %s%n", response.reasonPhrase)
    
    response.headers.foreach(println)
    
    val contentType: Option[String] = response.getHeaderValue("Content-Type")
    
    implicit val parser = BodyParser.text()
    
    printf("Body: %s%n", response.as[String])
    Definition Classes
    root
  • package server

    Provides HTTP server implementation.

    Provides HTTP server implementation.

    Building HTTP Server

    To build a server, you begin with ServerApplication. This is a mutable structure to which you apply changes to configure the server. Once the desired settings are applied, you invoke one of several methods to create the server.

    import java.io.File
    import scamper.BodyParser
    import scamper.Implicits.stringToEntity
    import scamper.ResponseStatus.Registry.{ NotFound, Ok }
    import scamper.server.HttpServer
    import scamper.server.Implicits._
    
    // Get server application
    val app = HttpServer.app()
    
    // Add request handler to log all requests
    app.incoming { req =>
      println(req.startLine)
      req
    }
    
    // Add request handler to specific request method and path
    app.get("/about") { req =>
      Ok("This server is powered by Scamper.")
    }
    
    // Add request handler using path parameter
    app.put("/data/:id") { req =>
      def update(id: Int, data: String): Boolean = ???
    
      implicit val parser = BodyParser.text()
    
      // Get path parameter
      val id = req.params.getInt("id")
    
      update(id, req.as[String]) match {
        case true  => Ok()
        case false => NotFound()
      }
    }
    
    // Serve static files
    app.files("/main", new 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.create(8080)
    
    printf("Host: %s%n", server.host)
    printf("Port: %d%n", server.port)
    
    // Run server for 60 seconds
    Thread.sleep(60 * 1000)
    
    // Close server when done
    server.close()
    Definition Classes
    scamper
  • ErrorHandler
  • HttpServer
  • Implicits
  • ParameterNotConvertible
  • ParameterNotFound
  • PathParameters
  • RequestHandler
  • ResponseAborted
  • ResponseFilter
  • Router
  • ServerApplication
  • WebSocketUpgrade

class ServerApplication extends Router

Configures and creates HttpServer.

ServerApplication is a mutable structure. With each applied change, the application is modified and returned. After the desired settings are applied, a server is created using one of several factory methods.

Linear Supertypes
Router, AnyRef, Any
Ordering
  1. Alphabetic
  2. By Inheritance
Inherited
  1. ServerApplication
  2. Router
  3. AnyRef
  4. Any
  1. Hide All
  2. Show All
Visibility
  1. Public
  2. All

Instance Constructors

  1. new ServerApplication()

    Creates server application.

    Creates server application.

    Default Configuration

    Key

    Value

    logger

    scamper.logging.ConsoleLogger

    backlogSize

    50

    poolSize

    Runtime.getRuntime().availableProcessors()

    queueSize

    Runtime.getRuntime().availableProcessors() * 4

    bufferSize

    8192

    readTimeout

    5000

    headerLimit

    100

    keepAlive

    (Not configured)

    secure

    (Not configured)

    incoming

    (Not configured)

    outgoing

    (Not configured)

    error

    (Sends 500 Internal Server Error)


Value Members

  1. final def !=(arg0: Any): Boolean
    Definition Classes
    AnyRef → Any
  2. final def ##(): Int
    Definition Classes
    AnyRef → Any
  3. final def ==(arg0: Any): Boolean
    Definition Classes
    AnyRef → Any
  4. final def asInstanceOf[T0]: T0
    Definition Classes
    Any
  5. 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.

    size

    backlog size

    returns

    this application

  6. 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).

    size

    buffer size in bytes

    returns

    this application

    Note

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

  7. def clone(): AnyRef
    Attributes
    protected[lang]
    Definition Classes
    AnyRef
    Annotations
    @throws( ... ) @native()
  8. def create(host: InetAddress, port: Int): HttpServer

    Creates server at given host and port.

    Creates server at given host and port.

    host

    host address

    port

    port number

    returns

    new server

  9. def create(host: String, port: Int): HttpServer

    Creates server at given host and port.

    Creates server at given host and port.

    host

    host address

    port

    port number

    returns

    new server

  10. def create(port: Int): HttpServer

    Creates server at given port.

    Creates server at given port.

    port

    port number

    returns

    new server

  11. def delete(path: String)(handler: RequestHandler): ServerApplication.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.

    path

    router path

    handler

    request handler

    returns

    this router

    Definition Classes
    Router
  12. final def eq(arg0: AnyRef): Boolean
    Definition Classes
    AnyRef
  13. def equals(arg0: Any): Boolean
    Definition Classes
    AnyRef → Any
  14. def error(handler: ErrorHandler): ServerApplication.this.type

    Sets error handler.

    Sets error handler.

    handler

    error handler

    returns

    this application

  15. def files(path: String, source: File): ServerApplication.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 or one of its subdirectories.

    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

    path

    router path at which directory is mounted

    source

    base directory from which files are served

    returns

    this router

    Definition Classes
    Router
  16. def finalize(): Unit
    Attributes
    protected[lang]
    Definition Classes
    AnyRef
    Annotations
    @throws( classOf[java.lang.Throwable] )
  17. def get(path: String)(handler: RequestHandler): ServerApplication.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.

    path

    router path

    handler

    request handler

    returns

    this router

    Definition Classes
    Router
  18. final def getClass(): Class[_]
    Definition Classes
    AnyRef → Any
    Annotations
    @native()
  19. def hashCode(): Int
    Definition Classes
    AnyRef → Any
    Annotations
    @native()
  20. 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).

    limit

    header limit

    returns

    this application

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

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

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

    The handler is appended to existing request handler chain.

    path

    request path

    methods

    request methods

    handler

    request handler

    returns

    this application

    Definition Classes
    ServerApplicationRouter
    Note

    If no request methods are specified, then matches are limited to path only.

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

    Adds supplied request handler.

    Adds supplied request handler.

    The handler is appended to existing request handler chain.

    handler

    request handler

    returns

    this application

    Definition Classes
    ServerApplicationRouter
  23. final def isInstanceOf[T0]: Boolean
    Definition Classes
    Any
  24. 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.

    timeout

    idle timeout in seconds

    max

    maximum number of requests per connection

    returns

    this application

  25. def keepAlive(params: KeepAliveParameters): ServerApplication.this.type

    Enables persistent connections using specified parameters.

    Enables persistent connections using specified parameters.

    params

    keep-alive parameters

    returns

    this application

  26. def logger(logger: Logger): ServerApplication.this.type

    Sets logger.

    Sets logger.

    logger

    logger to which server logs are written

    returns

    this application

  27. def logger(file: File): ServerApplication.this.type

    Sets logger to given file.

    Sets logger to given file.

    file

    file to which server logs are written

    returns

    this application

    Note

    If file exists, it is opened in append mode.

  28. def mountPath: String

    Gets mount path.

    Gets mount path.

    Definition Classes
    ServerApplicationRouter
    Note

    Mount path is always "/".

  29. final def ne(arg0: AnyRef): Boolean
    Definition Classes
    AnyRef
  30. final def notify(): Unit
    Definition Classes
    AnyRef
    Annotations
    @native()
  31. final def notifyAll(): Unit
    Definition Classes
    AnyRef
    Annotations
    @native()
  32. def outgoing(filter: ResponseFilter): ServerApplication.this.type

    Adds supplied response filter.

    Adds supplied response filter.

    The filter is appended to existing response filter chain.

    filter

    response filter

    returns

    this application

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

    Sets pool size.

    Sets pool size.

    The poolSize specifies the maximum number of requests processed concurrently.

    size

    pool size

    returns

    this application

  34. def post(path: String)(handler: RequestHandler): ServerApplication.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.

    path

    router path

    handler

    request handler

    returns

    this router

    Definition Classes
    Router
  35. def put(path: String)(handler: RequestHandler): ServerApplication.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.

    path

    router path

    handler

    request handler

    returns

    this router

    Definition Classes
    Router
  36. 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).

    size

    queue size

    returns

    this application

  37. 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.

    timeout

    read timeout in milliseconds

    returns

    this application

  38. def reset(): ServerApplication.this.type

    Resets application to default configuration.

  39. def resources(path: String, source: String, loader: ClassLoader): ServerApplication.this.type

    Mounts file server (for resources) at given path.

    Mounts file server (for resources) at given path.

    At request time, the mount path is stripped from the router path, and the remaining path is used to locate a resource in the source directory or one of its subdirectories.

    Resource Mapping Examples

    Mount Path

    Source Directory

    Router Path

    Maps to

    /images

    assets

    /images/logo.png

    assets/logo.png

    /images

    assets

    /images/icons/warning.png

    assets/icons/warning.png

    path

    router path at which directory is mounted

    source

    base directory from which resources are served

    loader

    class loader with which resources are loaded

    returns

    this router

    Definition Classes
    Router
  40. def resources(path: String, source: String): ServerApplication.this.type

    Mounts file server (for resources) at given path.

    Mounts file server (for resources) at given path.

    At request time, the mount path is stripped from the router path, and the remaining path is used to locate a resource in the source directory or one of its subdirectories.

    Resource Mapping Examples

    Mount Path

    Source Directory

    Router Path

    Maps to

    /images

    assets

    /images/logo.png

    assets/logo.png

    /images

    assets

    /images/icons/warning.png

    assets/icons/warning.png

    path

    router path at which directory is mounted

    source

    base directory from which resources are served

    returns

    this router

    Definition Classes
    Router
    Note

    The current thread's context class loader is used to load resources.

  41. def route[T](path: String)(routing: (Router) ⇒ T): ServerApplication.this.type

    Adds new router at given path.

    Adds new router at given path.

    A new router is created and passed to routing application.

    path

    router path at which new router is mounted

    routing

    routing application

    returns

    this router

    Definition Classes
    Router
  42. 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.

    key

    private key

    certificate

    public key certificate

    returns

    this application

  43. 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.

    keyStore

    server key store

    password

    key store password

    storeType

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

    returns

    this application

    Note

    The password can be discarded after invoking this method.

  44. 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.

    keyStore

    server key store

    password

    key store password

    storeType

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

    returns

    this application

  45. final def synchronized[T0](arg0: ⇒ T0): T0
    Definition Classes
    AnyRef
  46. def toAbsolutePath(path: String): String

    Expands supplied router path to its absolute path.

    Expands supplied router path to its absolute path.

    path

    router path

    Definition Classes
    Router
    Exceptions thrown

    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 *.

  47. def toString(): String
    Definition Classes
    AnyRef → Any
  48. final def wait(): Unit
    Definition Classes
    AnyRef
    Annotations
    @throws( ... )
  49. final def wait(arg0: Long, arg1: Int): Unit
    Definition Classes
    AnyRef
    Annotations
    @throws( ... )
  50. final def wait(arg0: Long): Unit
    Definition Classes
    AnyRef
    Annotations
    @throws( ... ) @native()
  51. def websocket[T](path: String)(handler: (WebSocketSession) ⇒ T): ServerApplication.this.type

    Adds WebSocket server at given router path using supplied session handler for each connection.

    Adds WebSocket server at given router path using supplied session handler for each connection.

    The handler is appended to existing request handler chain.

    path

    WebSocket path

    handler

    WebSocket session handler

    returns

    this router

    Definition Classes
    Router

Inherited from Router

Inherited from AnyRef

Inherited from Any

Ungrouped