Class Microservice

java.lang.Object
org.apache.juneau.microservice.Microservice
All Implemented Interfaces:
ConfigEventListener

public class Microservice extends Object implements ConfigEventListener
Parent class for all microservices.

A microservice defines a simple API for starting and stopping simple Java services contained in executable jars.

The general command for creating and starting a microservice from a main method is as follows:

public static void main(String[] args) { Microservice.create().args(args).build().start().join(); }

Your microservice class must be specified as the Main-Class entry in the manifest file of your microservice jar file if it's an executable jar.

Microservice Configuration
This class defines the following method for accessing configuration for your microservice:
  • getArgs() - The command-line arguments passed to the jar file.
  • getConfig() - An external INI-style configuration file.
  • getManifest() - The manifest file for the main jar file.
Lifecycle Methods
Subclasses must implement the following lifecycle methods:
  • init() - Gets executed immediately following construction.
  • start() - Gets executed during startup.
  • stop() - Gets executed when 'exit' is typed in the console or an external shutdown signal is received.
  • kill() - Can be used to forcibly shut down the service. Doesn't get called during normal operation.
See Also:
  • Constructor Details

  • Method Details

    • getInstance

      public static Microservice getInstance()
      Returns the Microservice instance.

      This method only works if there's only one Microservice instance in a JVM. Otherwise, it's just overwritten by the last instantiated microservice.

      Returns:
      The Microservice instance, or null if there isn't one.
    • create

      public static Microservice.Builder create()
      Creates a new builder for this object.
      Returns:
      A new microservice builder.
    • resolveFile

      protected File resolveFile(String path)
      Resolves the specified path.

      If the working directory has been explicitly specified, relative paths are resolved relative to that.

      Parameters:
      path - The path to resolve.
      Returns:
      The resolved path.
    • init

      Initializes this microservice.

      This method can be called whenever the microservice is not started.

      It will initialize (or reinitialize) the console commands, system properties, and logger.

      Returns:
      This object.
      Throws:
      ParseException - Malformed input encountered.
      IOException - Couldn't read a file.
    • start

      public Microservice start() throws Exception
      Start this application.

      Overridden methods MUST call this method FIRST so that the MicroserviceListener.onStart(Microservice) method is called.

      Returns:
      This object.
      Throws:
      Exception - Error occurred.
    • startConsole

      Starts the console thread for this microservice.
      Returns:
      This object.
      Throws:
      Exception - Error occurred
    • stopConsole

      Stops the console thread for this microservice.
      Returns:
      This object.
      Throws:
      Exception - Error occurred
    • getArgs

      public Args getArgs()
      Returns the command-line arguments passed into the application.

      This method can be called from the class constructor.

      See Args for details on using this method.

      Returns:
      The command-line arguments passed into the application.
    • getConfig

      public Config getConfig()
      Returns the external INI-style configuration file that can be used to configure your microservice.

      The config location is determined in the following order:

      1. The first argument passed to the microservice jar.
      2. The Main-Config entry in the microservice jar manifest file.
      3. The name of the microservice jar with a ".cfg" suffix (e.g. "mymicroservice.jar"->"mymicroservice.cfg").

      If all methods for locating the config fail, then this method returns an empty config.

      Subclasses can set their own config file by using the following methods:

      String variables are automatically resolved using the variable resolver returned by getVarResolver().

      This method can be called from the class constructor.

      Example:

      #-------------------------- # My section #-------------------------- [MySection] # An integer anInt = 1 # A boolean aBoolean = true # An int array anIntArray = 1,2,3 # A POJO that can be converted from a String aURL = http://foo # A POJO that can be converted from JSON aBean = {foo:'bar',baz:123} # A system property locale = $S{java.locale, en_US} # An environment variable path = $E{PATH, unknown} # A manifest file entry mainClass = $MF{Main-Class} # Another value in this config file sameAsAnInt = $C{MySection/anInt} # A command-line argument in the form "myarg=foo" myArg = $A{myarg} # The first command-line argument firstArg = $A{0} # Look for system property, or env var if that doesn't exist, or command-line arg if that doesn't exist. nested = $S{mySystemProperty,$E{MY_ENV_VAR,$A{0}}} # A POJO with embedded variables aBean2 = {foo:'$A{0}',baz:$C{MySection/anInt}}

      // Java code for accessing config entries above. Config config = getConfig(); int anInt = config.get("MySection/anInt").asInteger().orElse(-1); boolean aBoolean = config.get("MySection/aBoolean").asBoolean().orElse(false); int[] anIntArray = config.get("MySection/anIntArray").as(int[].class).orElse(null); URL aURL = config.get("MySection/aURL").as(URL.class).orElse(null); MyBean aBean = config.get("MySection/aBean").as(MyBean.class).orElse(null); Locale locale = config.get("MySection/locale").as(Locale.class).orElse(null); String path = config.get("MySection/path").orElse(null); String mainClass = config.get("MySection/mainClass").orElse(null); int sameAsAnInt = config.get("MySection/sameAsAnInt").asInteger().orElse(null); String myArg = config.getString("MySection/myArg"); String firstArg = config.getString("MySection/firstArg");

      Returns:
      The config file for this application, or null if no config file is configured.
    • getManifest

      Returns the main jar manifest file contents as a simple JsonMap.

      This map consists of the contents of Manifest.getMainAttributes() with the keys and entries converted to simple strings.

      This method can be called from the class constructor.

      Example:

      // Get Main-Class from manifest file. String mainClass = Microservice.getManifest().getString("Main-Class", "unknown"); // Get Rest-Resources from manifest file. String[] restResources = Microservice.getManifest().getStringArray("Rest-Resources");

      Returns:
      The manifest file from the main jar, or null if the manifest file could not be retrieved.
    • getVarResolver

      Returns the variable resolver for resolving variables in strings and files.

      Variables can be controlled by the following methods:

      Returns:
      The VarResolver used by this Microservice, or null if it was never created.
    • getLogger

      public Logger getLogger()
      Returns the logger for this microservice.
      Returns:
      The logger for this microservice.
    • executeCommand

      public boolean executeCommand(Args args, Scanner in, PrintWriter out)
      Executes a console command.
      Parameters:
      args - The command arguments.
      The first entry in the arguments is always the command name.
      in - Console input.
      out - Console output.
      Returns:
      true if the command returned true meaning the console thread should exit.
    • executeCommand

      public String executeCommand(String command, String input, Object... args)
      Convenience method for executing a console command directly.

      Allows you to execute a console command outside the console by simulating input and output.

      Parameters:
      command - The command name to execute.
      input - Optional input to the command. Can be null.
      args - Optional command arguments to pass to the command.
      Returns:
      The command output.
    • join

      public Microservice join() throws Exception
      Joins the application with the current thread.

      Default implementation is a no-op.

      Returns:
      This object.
      Throws:
      Exception - Error occurred
    • stop

      public Microservice stop() throws Exception
      Stop this application.

      Overridden methods MUST call this method LAST so that the MicroserviceListener.onStop(Microservice) method is called.

      Returns:
      This object.
      Throws:
      Exception - Error occurred
    • exit

      public void exit() throws Exception
      Stops the console (if it's started) and calls System.exit(int).
      Throws:
      Exception - Error occurred
    • kill

      public void kill()
      Kill the JVM by calling System.exit(2);.
    • getConsoleCommands

      Returns the console commands associated with this microservice.
      Returns:
      The console commands associated with this microservice as an unmodifiable map.
    • getConsoleReader

      Returns the console reader.

      Subclasses can override this method to provide their own console input.

      Returns:
      The console reader. Never null.
    • getConsoleWriter

      Returns the console writer.

      Subclasses can override this method to provide their own console output.

      Returns:
      The console writer. Never null.
    • out

      public void out(Messages mb, String messageKey, Object... args)
      Prints a localized message to the console writer.

      Ignored if "Console/enabled" is false.

      Parameters:
      mb - The message bundle containing the message.
      messageKey - The message key.
      args - Optional MessageFormat-style arguments.
    • err

      public void err(Messages mb, String messageKey, Object... args)
      Prints a localized message to STDERR.

      Ignored if "Console/enabled" is false.

      Parameters:
      mb - The message bundle containing the message.
      messageKey - The message key.
      args - Optional MessageFormat-style arguments.
    • log

      protected void log(Level level, String message, Object... args)
      Logs a message to the log file.
      Parameters:
      level - The log level.
      message - The message text.
      args - Optional MessageFormat-style arguments.
    • onConfigChange

      public void onConfigChange(ConfigEvents events)
      Description copied from interface: ConfigEventListener
      Gets called immediately after a config file has been loaded.
      Specified by:
      onConfigChange in interface ConfigEventListener
      Parameters:
      events - The change events.