Class Microservice
- All Implemented Interfaces:
- ConfigEventListener
- Direct Known Subclasses:
- JettyMicroservice
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:
   
 Your microservice class must be specified as the 
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:
- 
Nested Class SummaryNested Classes
- 
Constructor SummaryConstructors
- 
Method SummaryModifier and TypeMethodDescriptionstatic Microservice.Buildercreate()Creates a new builder for this object.voidPrints a localized message to STDERR.executeCommand(String command, String input, Object... args) Convenience method for executing a console command directly.booleanexecuteCommand(Args args, Scanner in, PrintWriter out) Executes a console command.voidexit()Stops the console (if it's started) and callsSystem.exit(int).getArgs()Returns the command-line arguments passed into the application.Returns the external INI-style configuration file that can be used to configure your microservice.final Map<String,ConsoleCommand> Returns the console commands associated with this microservice.protected ScannerReturns the console reader.protected PrintWriterReturns the console writer.static MicroserviceReturns the Microservice instance.Returns the logger for this microservice.Returns the main jar manifest file contents as a simpleJsonMap.Returns the variable resolver for resolving variables in strings and files.init()Initializes this microservice.join()Joins the application with the current thread.voidkill()Kill the JVM by callingSystem.exit(2); .protected voidLogs a message to the log file.voidonConfigChange(ConfigEvents events) Gets called immediately after a config file has been loaded.voidPrints a localized message to the console writer.protected FileresolveFile(String path) Resolves the specified path.start()Start this application.Starts the console thread for this microservice.stop()Stop this application.Stops the console thread for this microservice.
- 
Constructor Details- 
MicroserviceConstructor.- Parameters:
- builder- The builder containing the settings for this microservice.
- Throws:
- IOException- Problem occurred reading file.
- ParseException- Malformed input encountered.
 
 
- 
- 
Method Details- 
getInstanceReturns 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.
 
- 
createCreates a new builder for this object.- Returns:
- A new microservice builder.
 
- 
resolveFileResolves 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.
 
- 
initInitializes 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.
 
- 
startStart 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.
 
- 
startConsoleStarts the console thread for this microservice.- Returns:
- This object.
- Throws:
- Exception- Error occurred
 
- 
stopConsoleStops the console thread for this microservice.- Returns:
- This object.
- Throws:
- Exception- Error occurred
 
- 
getArgsReturns the command-line arguments passed into the application.This method can be called from the class constructor. See Argsfor details on using this method.- Returns:
- The command-line arguments passed into the application.
 
- 
getConfigReturns the external INI-style configuration file that can be used to configure your microservice.The config location is determined in the following order: - The first argument passed to the microservice jar.
- 
      The Main-Config entry in the microservice jar manifest file.
- 
      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. Configconfig = 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 ); URLaURL =config .get("MySection/aURL" ).as(URL.class ).orElse(null ); MyBeanaBean =config .get("MySection/aBean" ).as(MyBean.class ).orElse(null ); Localelocale =config .get("MySection/locale" ).as(Locale.class ).orElse(null ); Stringpath =config .get("MySection/path" ).orElse(null ); StringmainClass =config .get("MySection/mainClass" ).orElse(null );int sameAsAnInt =config .get("MySection/sameAsAnInt" ).asInteger().orElse(null ); StringmyArg =config .getString("MySection/myArg" ); StringfirstArg =config .getString("MySection/firstArg" );- Returns:
- The config file for this application, or null if no config file is configured.
 
- 
getManifestReturns the main jar manifest file contents as a simpleJsonMap.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. StringmainClass = 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.
 
- 
getVarResolverReturns 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.
 
- 
getLoggerReturns the logger for this microservice.- Returns:
- The logger for this microservice.
 
- 
executeCommandExecutes 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.
 
- 
executeCommandConvenience 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.
 
- 
joinJoins the application with the current thread.Default implementation is a no-op. - Returns:
- This object.
- Throws:
- Exception- Error occurred
 
- 
stopStop 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
 
- 
exitStops the console (if it's started) and callsSystem.exit(int).- Throws:
- Exception- Error occurred
 
- 
killKill the JVM by callingSystem.exit(2); .
- 
getConsoleCommandsReturns the console commands associated with this microservice.- Returns:
- The console commands associated with this microservice as an unmodifiable map.
 
- 
getConsoleReaderReturns the console reader.Subclasses can override this method to provide their own console input. - Returns:
- The console reader.  Never null .
 
- 
getConsoleWriterReturns the console writer.Subclasses can override this method to provide their own console output. - Returns:
- The console writer.  Never null .
 
- 
outPrints a localized message to the console writer.Ignored if "Console/enabled" isfalse .- Parameters:
- mb- The message bundle containing the message.
- messageKey- The message key.
- args- Optional- MessageFormat-style arguments.
 
- 
errPrints a localized message to STDERR.Ignored if "Console/enabled" isfalse .- Parameters:
- mb- The message bundle containing the message.
- messageKey- The message key.
- args- Optional- MessageFormat-style arguments.
 
- 
logLogs a message to the log file.- Parameters:
- level- The log level.
- message- The message text.
- args- Optional- MessageFormat-style arguments.
 
- 
onConfigChangeDescription copied from interface:ConfigEventListenerGets called immediately after a config file has been loaded.- Specified by:
- onConfigChangein interface- ConfigEventListener
- Parameters:
- events- The change events.
 
 
-