Class ConfigurableWS

java.lang.Object
org.bzdev.ejws.ConfigurableWS

public class ConfigurableWS extends Object
Configurable web server. This class supports web servers that can be configured, at least partially with a configuration file. The server can be configured to use HTTPS, either directly or with a CertManager, which is obtained using a Java service-provider interface. When HTTPS is used, an additional server running HTTP will be provided. This server will provide an HTTP redirect to the HTTPS server. An additional server will not be provided when HTTPS is not used.

When the configuration file is a Java Properties file using the format described by the API documentation for Properties.load(Reader). A number of properties, called "standard properties" below, are always available, but can be supplemented by a set of properties provided in a constructor. In addition, the input file can be a YAML file as described below. When the configuration file is a YAML file, its file name must end with the file-name extension "YAML", "yaml", "YML", or "yml".

The standard properties can be grouped into three categories:

For colors, the standards properties use values that are CSS colors. These properties are
  • color. This is the color used for text. If missing, a default, white, will be used
  • bgcolor. This is the color used for the background. If missing, a default, rgb(10,10,25), will be used.
  • linkColor. This is the color used for links. If missing, a default, rgb(65,225,128, will be used.
  • visitedColor. This is the color used for visited links. If missing, a default, rgb(65,165,128), will be used.

      For SSL parameters, the standard properties are

      • keyStoreFile. The value is the file name of the key store, which is used to hold the server's certificate. Relative file names are resolved against the directory containing the configuration file.
      • keyStorePassword. The value is the password used by the keystore file.
      • keyPassword. The value is the password used for individual entries in the keystore file. If not provided, the default is the value of keyStorePassword.
      • trustStoreFile. The value is the file name of the trust store, which provides certificates to trust in addition to those provided by Java for certificate authorities. This can be used when an organization creates an internal certificate authority for the organization's use. Relative file names are resolved against the directory containing the configuration file.
      • trustStorePassword. The value is the password used by the keystore file.
      • allowLoopback. When true, a loopback host name will be recognized as valid. The default is false.
      • allowSelfSigned. When true, self-signed certificates are accepted. The default is false. This option is useful for testing, but should not be used otherwise.
      • certificateManager. When present, the value is either a simple name or a fully-qualified class name for a certificate manager. The value "default" will set up the server so that a self-signed certificate is automatically generated and the corresponding keystore file will be created if it is not already present. Certificates are renewed automatically. The Docker container wtzbzdev/ejwsacme includes a certificate manger whose simple name is "AcmeClient" and which will get a certificate from the Let's Encrypt certificate authority. In this case, the properties domain and email are required, and the server's DNS server must be configured to map the domain name to the server's IP address (i.e., by setting an 'A' or 'AAAA" record).
      • certMode. When present, the value may be NORMAL, STAGED, or TEST. The default is NORMAL. The value STAGED is useful for initial testing when the certificate manager's provider name is AcmeClient: the Let's Encrypt server will then generate a non-functioning certificate but the ACME protocol will be used to download a certificate and receiving a certificate indicates that there is not a configuration error. When certMode is TEST, programs that implement the ACME protocol will not actually be run. This value is intended for some tests of the AcmeClient provider.
      • certName. This is a name used to tag a certificate.
      • alwaysCreate. WHen present, the value may be true or false (the default). When true, a new certificate will be created every time a certificate manager checks if the current certificate has expired. This is useful for testing, but should not be used otherwise.
      • domain. This is the fully-qualified domain name for the server. It is used to create the distinguished name in a certificate.
      • email. This is an email address used by some certificate authorities to send notifications about expiring certificates.
      • timezone. The time zone ID (e.g., GMT or America/Los_Angeles) that the server will use in determining when to schedule certificate renewals provided that a certificate manager is used. If not provided or null, the system default timezone is used. An unrecognized time zone currently defaults to GMT (this JDK/JRE dependent).
      • timeOffset. The time offset in seconds from midnight, local time, at which a server should determine if a certificate should be renewed. The default is 0.
      • interval. The number of days between attempts to renew a certificate. The default is 7.
      • stopDelay. The time interval in seconds from a request to shutdown a server to when the server is actually shut down. This is used to give transactions being processed time to complete and will be used only when a new certificate is needed. The default is 5.

      For server parameters, the standard properties are

      • sslType. When present, the values should be either SSL or TLS. TLS is preferred. When absent or when the value is null, HTTP is used instead of HTTPS.
      • ipaddr. The value is the numeric IP address on which this server listens, with two special values:

        • wildcard. The server will use the wildcard address (this is the default).
        • loopback. The server will use the loopback address. Note that within a Linux container (e.g., when using Docker), the loopback address may be interpreted as the loopback address inside the container, no the loopback address of the system.
      • port. The value is the server's TCP port. If missing the port is by default set to 80 for HTTP and 443 for HTTPS.
      • helperPort. The value is an alternate server's TCP port for use with HTTP when the certificate manager (if provided) does not provide an HTTP port to use. If the value is zero or the parameter is not defined, and the certificate manager does not provide a port, an HTTP server will not be started. If an HTTP server is started, it will provide an HTTP redirect to the HTTPS server for web pages containing documentation and public keys, and for queries. For POST methods, the HTTPS server has to be used directly. If the certificate manager does not provide a port, this value must be set when an HTTP server is desired.
      • backlog. When present, the value is an integer providing the TCP backlog. The default value is 30.
      • nthreads. The number of threads the server can use. The default is 50.
      • trace. A value of true indicates that the execution of a request will be traced, printing out what occurred on standard output. The default is false unless overrriden by setTraceDefaults(boolean,boolean).
      • stackTrace. A value of true indicates that errors resulting from GET or POST methods will generate a stack trace. The default is false unless overrriden by setTraceDefaults(boolean,boolean).

      YAML can be used as a configuration-file format, which provides some additional capabilities. A YAML configuration file must have a file-name suffix, either ".yml", ".yaml", ".YML", or ".YAML". The syntax is

       %YAML 1.2
       ---
       defs:
        ... list of objects with YAML anchors; otherwise ignored
       config:
          NAME: VALUE
          ... (additional name-value pairs)
       contexts:
          - prefix:  PREFIX
            className: CLASSNAME
            arg: ARGUMENT
            useHTTP: BOOLEAN
            welcome: 
              - PATH
              ... (additional welcome path names)
            parameters:
              NAME: VALUE
              ... (additional parameters)
            propertyNames:
               - NAME
               ... (additional property names)
            methods:
               - METHOD
               ... (additional methods)
            nowebxml:  BOOLEAN
            displayDir: BOOLEAN
            hideWebInf: BOOLEAN
            color: CSS_COLOR
            bgcolor: CSS_COLOR
            linkColor: CSS_COLOR
            visitedColor: CSS_COLOR
            trace: Boolean
            stacktrace: Boolean
          -... (additional contexts)
       ... (additional keys other than "config:" and "context:")
       ...
       
      where
      • PREFIX is the start of the path component of a URL
      • CLASSNAME is the class name for a suitable subclass of WebMap. The class names that are directly supported are although the method addContext(String,String,String,EmbeddedWebSever,Map,String[],HttpMethod[],String,String,String,String,boolean,boolean,boolean), if implemented, may support additional web maps.
      • ARGUMENT is the string representation of the argument required to initialize a web map. For
        • DirWebMap, the argument is a file name.
        • RedirectWebMap, the argument is a URL.
        • ResourceWebMap, the argument is the initial part of a Java resource name, and should end with a '/'.
        • ZipWebMap, the argument is a string naming a ZIP file.
        • ServletWebMap, the class name for a servlet adapter that has a zero-argument constructor.
      • BOOLEAN is true or false. If absent, the default is false.
      • PATH is the path to a "welcome" file If the path is a relative path, it is relative to the prefix path.
      • NAME is the name of a configuration property (listed under "config:") or a parameter.
      • VALUE is a string representation of a value corresponding to the given name.
      • METHOD is the string CONNECT, DELETE, GET, HEAD, OPTIONS, POST, PUT, TRACE and indicates which HTTP methods are supported for the specified prefix.
      • BOOLEAN is either "true" or "false" (quotation marks are not necessary).
      • CSS_COLOR is a CSS color specification, provided as a string.
      The "config:" section provides the same information as a corresponding {link Properties} file. The "contexts" section allows one to add specific prefixes to the web server without having to use EmbeddedWebServer.add(String,String,Object,com.sun.net.httpserver.Authenticator,boolean,boolean,boolean) explicitly. The value for "contexts" is a list of YAML objects. For each object, the value of the key
      • prefix is the path for an HTTP context corresponding to a WebMap.
      • className is the class name of the WebMap.
      • arg is the argument or the string representation of an argument used to initialize a web map. For the class ServletWebMap, the argument is the fully qualified class name of a ServletAdapter.
      • useHTTP, when true, preferentially assigns this context to the helper, which runs HTTP, rather than to the server, which runs HTTPS when there is a helper. If false, or if there is no helper, or if this key is missing, the context is assigned to the server.
      • welcome is a list of strings, each providing the path to a 'welcome' page for a given prefix. If there are no welcome pages, this key may be omitted.
      • parameters is an object show keys are parameter names and whose values are parameter values, as required by a ServletAdapter. If there are no parameters, this key may be omitted.
      • propertyNames is a list of names provided by the "config" section whose names and corresponding values will be added to the parameters. This minimizes configuration errors that could occur when the same name/value pair is used by multiple servlet adapters. If the list is empty, this key can be omitted.
      • methods is a list of the HTTP methods that a servlet adapter supports.
      • nowebxml is true if a web.xml file should be ignored; false otherwise. If not provided, the value is assumed to be true.
      • displayDir is true if directories should be displayed when possible; false otherwise. If not provided, the value is assumed to be true.
      • hideWebInf is true if any WEB-INF directory should be hidden; false otherwise. If not provided, the value is assumed to be true.
      • trace. A value of true indicates that the execution of a request will be traced, printing out what occurred on standard output. The default is the corresponding parameter in the config object, and if there is none, a configurable system default is used.
      • stackTrace. A value of true indicates that errors resulting from GET or POST methods will generate a stack trace. The default is the corresponding parameter in the config object, and if there is none, a configurable system default is used.
      • color is the CSS color for text. This will override a standard property for the current prefix.
      • bgcolor is the CSS color for the background. This will override a standard property for the current prefix.
      • linkColor is the CSS color for links; null if for a default. This will override a standard property for the current prefix.
      • visitedColor is the CSS color for visited links; null for a default. This will override a standard property for the current prefix.
      Additional keys can be added as specified in the constructor ConfigurableWS(Set,Set,File,File), a capability provided for extensibility. Any such keys will normally be processed before the server is started.
  • Constructor Details

    • ConfigurableWS

      public ConfigurableWS(File configFile, File logFile) throws Exception
      Constructor. The configuration file is described above. When the configuration file is a YAML file, its file name must have the file-name extension "YAML", "yaml", "YML", or "yml".
      Parameters:
      configFile - the configuration file
      logFile - the log file ; null for standard output
      Throws:
      Exception - if an error occurs
    • ConfigurableWS

      public ConfigurableWS(Set<String> additionalPropertyNames, File configFile, File logFile) throws Exception
      Constructor specifying additional property names. The configuration file is described above. When the configuration file is a YAML file, its file name must have the file-name extension "YAML", "yaml", "YML", or "yml".

      When the first argument is not null, the user must handle any configuration required by those properties explicitly. The method getProperties() can be used to obtain the a Properties object providing the values for any property.

      Parameters:
      additionalPropertyNames - additional property names; null if there are none.
      configFile - the configuration file
      logFile - the log file ; null for standard output
      Throws:
      Exception - if an error occurs
    • ConfigurableWS

      public ConfigurableWS(Set<String> additionalPropertyNames, Set<String> additionalKeys, File configFile, File logFile) throws Exception
      Constructor specifying additional property names and additional keys. The configuration file is described above. When the configuration file is a YAML file, its file name must have the file-name extension "YAML", "yaml", "YML", or "yml".

      When the first argument is not null, the user must handle any configuration required by those properties explicitly. The method getProperties() can be used to obtain the a Properties object providing the values for any property. When the second argument is not null, the user must handle any keys required by those properties explicitly. The method getRemainder() can be used to obtain a JSObject with values accessed by any key other than "config" or "context".

      Parameters:
      additionalPropertyNames - additional property names; null if there are none.
      additionalKeys - additional keys for the top-level object in a YAML-based configuration file; null if there are none
      configFile - the configuration file
      logFile - the log file ; null for standard output
      Throws:
      Exception - if an error occurs
  • Method Details

    • trace

      public boolean trace()
      Determine if tracing is configured.
      Returns:
      true if tracing is configured; false otherwise
    • stacktrace

      public boolean stacktrace()
      Determine if stack tracing is configured.
      Returns:
      true if stack tracing is configured; false otherwise
    • getLog

      public PrintStream getLog()
      Get the print stream used for logging.
      Returns:
      the print stream; null if there is none.
    • color

      public String color()
      Get a CSS color for foreground text.
      Returns:
      the color
    • bgcolor

      public String bgcolor()
      Get a CSS color for background text.
      Returns:
      the color
    • linkColor

      public String linkColor()
      Get a CSS color for links.
      Returns:
      the color
    • visitedColor

      public String visitedColor()
      /** Get a CSS color for visited links.
      Returns:
      the color
    • setTraceDefaults

      public static void setTraceDefaults(boolean defaultTrace, boolean defaultStacktrace)
      Set the defaults for tracing. The initial value for both arguments is false.
      Parameters:
      defaultTrace - true if tracing is turned on by default; false otherwise
      defaultStacktrace - true if a stack trace should be provided when an error occurs during tracing; false otherwise
    • getProperties

      public Properties getProperties()
      Get the properties defined in a configuration file. When the configuration file uses YAML syntax, these properties are the keys for the object that is the value for the top-level key "config".
      Returns:
      the properties
    • getContexts

      public JSArray getContexts()
      Get the contexts specified in the configuration file. This method returns a non-null value only for YAML configuration files. The values listed are the values for the top-level key "contexts".
      Returns:
      the contexts listed in the configuration file; null if no contexts are specified.
    • getRemainder

      public JSObject getRemainder()
      Get the keyword/value pairs specified at the top level of the configuration file. This method returns a non-null value only for YAML configuration files.

      This method can be used if a YAML configuration file contains extra keys at its top level and is provided to make configuring a server extensible.

      Returns:
      an object containing the keyword/value pairs; null if there are none or if the only keywords are "config" or "contexts"
    • getServer

      public EmbeddedWebServer getServer()
      Get the EmbeddedWebServer that will handle HTTP or HTTPS requests.
      Returns:
      the server
    • getHelper

      public EmbeddedWebServer getHelper()
      Get the EmbeddedWebServer that will handle HTTP as a 'helper' for the server returned by getServer(). When a helper exists, its default behavior is to provided an HTTP redirect to the the server returned by getServer(). Additional contexts can be added to the helper server, either explicitly or implicitly (by setting useHTTP to true for a context).
      Returns:
      the helper server; null if there is none
    • headless

      public static void headless()
      Set a system property indicating that the JVM is headless.
    • addContext

      protected boolean addContext(String prefix, String className, String arg, EmbeddedWebServer svr, Map<String,String> map, String[] welcome, HttpMethod[] methods, String color, String bgcolor, String linkColor, String visitedColor, boolean nowebxml, boolean displayDir, boolean hideWebInf) throws Exception
      Add a context to the web server. This method is called by the constructor, and can override the default behavior or handle additional WebMap subclasses. When this is done, the method must return true.

      The web-map classes automatically handled are DirWebMap, RedirectWebMap, ResourceWebMap, ZipWebMap, and ServletWebMap.

      Parameters:
      prefix - the path for a context
      className - the class name for a WebMap
      arg - the argument used to configure the WebMap
      svr - the server being modified
      map - a map assigning parameter names to parameter values
      welcome - the welcome paths; an empty array if there are none
      methods - the HTTP methods a servlet can use
      color - the CSS color for text
      bgcolor - the CSS color for the background
      linkColor - the CSS color for links
      visitedColor - the CSS color for visited links
      nowebxml - true if a web.xml file should be ignored; false otherwise
      displayDir - true if the caller wants directories displayed when possible; false otherwise
      hideWebInf - true if the WEB-INF directory should be hidden; false if it should be visible
      Returns:
      true if the context was added; false if the request was ignored.
      Throws:
      Exception - if an error occurs
    • start

      public void start() throws Exception
      Start the web server.
      Throws:
      Exception - if an error occurs
    • stop

      public void stop(int delay) throws Exception
      Stop the web server. A call to this method will block until the server stops. As soon as this method is called, the server will stop accepting new requests. Processing of existing requests will continue for the time interval specified by the argument. Once the server stops, The server's thread pool will be shut down in case the server fails to do that.

      IF there is a 'helper' server, the helper will not be stopped.

      Parameters:
      delay - the delay in seconds before the server is stopped.
      Throws:
      Exception - if an error occurred
    • shutdown

      public void shutdown(int delay)
      Shutdown the web server. A call to this method will block until the server stops and shuts down. This differs from the method stop in that the server cannot be restarted.

      A 'helper' server will also be shut down.

      Parameters:
      delay - the delay in seconds before the server is stopped.