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

    • create

      public static Microservice.Builder create()
      Creates a new builder for this object.

      Routes builder construction through BeanInstantiator so that the juneau.workingDir env default is resolved through the active Settings chain.

      Returns:
      A new microservice builder.
    • create

      public static Microservice.Builder create(BeanStore beanStore)
      Creates a new builder for this object using the supplied BeanStore for @Value-resolution and dependency injection.
      Parameters:
      beanStore - The bean store to use for dependency injection.
      Returns:
      A new microservice builder.
    • 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.
    • 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. Must not be null.
      messageKey - The message key.
      args - Optional MessageFormat-style arguments.
    • executeCommand

      public boolean executeCommand(Args args, Scanner in, PrintWriter out)
      Executes a console command.
      Parameters:
      args - The command arguments. Must not be null.
      The first entry in the arguments is always the command name.
      in - Console input.
      out - Console output. Must not be null.
      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 (treated as an empty string).
      args - Optional command arguments to pass to the command.
      Returns:
      The command output.
    • exit

      public void exit() throws Exception
      Stops the console (if it's started) and calls System.exit(int).
      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. Never null (an empty config is returned if none is configured).
    • getConsoleCommands

      Returns the console commands associated with this microservice.
      Returns:
      The console commands associated with this microservice. Never null.
    • getLogger

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

      Returns the internal WritableBeanStore that backs this microservice's inject-aware bootstrap.

      The store is populated with this microservice's resolved values (Args, ManifestFile, Config, VarResolver, MicroserviceListener, and Microservice itself), plus any beans contributed by @Configuration classes registered via Microservice.Builder.configurations(Class...).

      Lifecycle integration beans (e.g. JettyServerComponent contributed by JettyConfiguration) implement MicroserviceListener and participate in the start() / stop() fan-out. External callers can query the store directly to look up beans contributed by user-supplied @Configuration classes.

      The store is closed during stop(), which triggers @PreDestroy hooks on resolved beans.

      Returns:
      The microservice's bean store. Never null.
      Since:
      10.0.0
    • 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. Never null (an empty manifest is returned if none could 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. Never null.
    • 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.
    • 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
    • kill

      public void kill()
      Kill the JVM by calling System.exit(2);.
    • 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.
    • 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. Must not be null.
      messageKey - The message key.
      args - Optional MessageFormat-style arguments.
    • start

      public Microservice start() throws Exception
      Start this application.

      Iterates over every MicroserviceListener bean in the bean store (in registration order) and calls MicroserviceListener.onStart(Microservice) on each.

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

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

      public Microservice stop() throws Exception
      Stop this application.

      Iterates over every MicroserviceListener bean in the bean store in reverse registration order and calls MicroserviceListener.onStop(Microservice) on each, then closes the bean store (firing any @PreDestroy hooks).

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

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

      Returns the console reader.

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

      Returns:
      The console reader, or null if the console is not enabled.
    • getConsoleWriter

      Returns the console writer.

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

      Returns:
      The console writer, or null if the console is not enabled.
    • 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 String.format-style arguments.
    • 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. Must not be null.
      Returns:
      The resolved path.