org.licas

## Class Auto

- java.lang.Object
- - java.lang.Thread
  - - org.licas.module.LicasModule
    - - org.licas.module.FrameworkModule
      - - org.licas.module.ServiceModule
        - - org.licas.Service
          - - org.licas.service.DataService
            - - org.licas.Auto

- All Implemented Interfaces:
    java.lang.AutoCloseable, java.lang.Runnable, DataServiceDef, ServiceDef
  Direct Known Subclasses:
    AutoInterface, AutoSecure, LinkService

      public abstract class Auto
      extends DataService

  This is the base class for a service with added autonomic or agent-based functionality. An `Auto` class is different to a `Service` in the sense that it should try to run more independently. It can run its own thread to periodically execute its own behaviour. The Auto service can also manage conversations with other services by storing separate communication IDs for each conversation thread. This is not the strict agent-based protocols, but entirely arbitrary to the service itself. If you want to use an `AutonomicManager` with your service, then you must load an Auto-derived class and not a Service-derived class.

  When a service is loaded, the `server` automatically adds an empty Autonomic Manager to any Auto-derived service, as a wrapper object. If you then start an Auto derived class’s thread and execute behaviours; if any monitoring modules are added, they can process the behaviour results. If you just want to use the more advanced features of an Auto class, you do not need to add anything else.

  The behaviour thread's `run` loop implements the main control loop that links with the empty MAPE slots and so you can use them if needed, by adding specific functionality to the modules that you might require. Looking at the Auto class should show what methods you need to implement yourself to create your own autonomic service. The other option is to invoke the behaviour directly through the `invokeBehaviour` method. this can only be used if the main thread is not running.

  The `Auto` class is still abstract however, where you must extend it to add specific behaviour functionality and implement a number of additional methods. See the `LinkService`, for example.

  Author:
    Kieran Greer

- - ### Nested Class Summary

    - ### Nested classes/interfaces inherited from class java.lang.Thread

      `java.lang.Thread.State, java.lang.Thread.UncaughtExceptionHandler`

  - ### Field Summary

    Fields
    Modifier and Type | Field and Description
    --- | ---
    `protected AutoEngine` | `autoEngine` Auto engine for this service, not the autonomic manager.
    `protected AutonomicManager` | `autoManager` The autonomic manager monitoring this service
    `protected BehaviourModule` | `bm` Module to manage the actions of the behaviour.
    `protected long` | `iterations` Number of behaviour events to execute, then shut-down the service.
    `protected long` | `sleepTime` Time period between behaviour events.

    - ### Fields inherited from class org.licas.service.DataService

      `dataCompare, dataMethod, resultObj`

    - ### Fields inherited from class org.licas.Service

      `canAccessMeta, canAccessNested, dm, finalised, isRemoteCall, messageStore, serviceAdmin, serviceGrade, serviceInitialise, serviceLinks, serviceState, sm, toLoadScript`

    - ### Fields inherited from class org.licas.module.ServiceModule

      `shutDown`

    - ### Fields inherited from class org.licas.module.FrameworkModule

      `passwordHandler, service, serviceType`

    - ### Fields inherited from class org.licas.module.LicasModule

      `jarFile, syncOn, uuid`

    - ### Fields inherited from class java.lang.Thread

      `MAX_PRIORITY, MIN_PRIORITY, NORM_PRIORITY`

  - ### Constructor Summary

    Constructors
    Constructor and Description
    `Auto()` Creates a new instance of Auto.
    `Auto(java.lang.String thisPassword, java.lang.String thisAdminKey)` Creates a new instance of Auto.
    `Auto(java.lang.String thisPassword, java.lang.String thisAdminKey, org.licas_xml.abs.Element adminXml)` Creates a new instance of Auto.

  - ### Method Summary

    All Methods Instance Methods Abstract Methods Concrete Methods
    Modifier and Type | Method and Description
    --- | ---
    `void` | `autoAction(java.lang.String action, java.lang.String adminKey)` This allows the autonomic manager to ask the parent service to perform some action.
    `MessageInfo` | `autoQueueMessage(org.dcs.query_process.model.activity.Script_Auto scriptAuto, java.lang.String adminKey)` Retrieve and remove the first message on the auto manager's queue with the specified condition - method name, timestamp, etc.
    `protected abstract MessageInfo` | `behaviourAction(MessageInfo messageInfo)` Execute a behaviour, such as an evaluation and result.
    `protected AutoEngine` | `getAutoEngine()` Get the auto engine.
    `protected java.lang.Object` | `getInstanceValue(java.lang.String varName)` Get the value of the specified variable if it exists.
    `protected java.lang.String` | `getMessageState(java.lang.Object message)` Calculate the current state for the message and related conversation.
    `boolean` | `interrupt(java.lang.String adminKey)` You must call this method to interrupt the thread.
    `java.lang.Object` | `invokeBehaviour(MessageInfo messageInfo)` This can be used to execute a single invocation of the service's `evaluateBehaviour` method.
    `boolean` | `messageReply(java.lang.Object message)` This can be used as part of a conversation, for example, to reply to some other method invocation, or even to start a conversation.
    `protected void` | `removeCommunicationID(java.lang.String commID)` Remove the communication ID reference.
    `void` | `run()` This is the default method to start the service thread.
    `protected void` | `setAutoEngine()` Initialise and create the auto engine.
    `protected void` | `setAutonomicManager(AutonomicManager thisAutoManager)` Set a reference to the autonomic manager monitoring this service.
    `protected void` | `setBehaviourModule()` Set the type of behaviour that the control loop uses to evaluate the service.
    `protected void` | `setInstanceValues(org.licas_xml.abs.Element instanceValues)` Set actual values for variable instances if they are defined.
    `boolean` | `setProcessScript(org.licas_xml.abs.Element theScript, java.lang.String adminKey)` Set or update the auto engine `AiConst`.`PROCESS` script to execute a (business) process through the script description.
    `protected void` | `setSerializeValues(org.licas_xml.abs.Element serializeXml)` Set actual values for serialized variable instances if they are defined.

    - ### Methods inherited from class org.licas.service.DataService

      `createEvaluateData, createEvaluateData, dataTypeOK, dataXmlBM, dataXmlBM, dataXmlDH, dataXmlDH, evaluate, getData, getData, getDataType, getResultObj, resetValues, setData, setData, setFixedDataValue, setGenData, setResultObj`

    - ### Methods inherited from class org.licas.Service

      `addCommunicationID, addDefaultService, addDefaultService, addDefaultService, addDefaultService, addLinkFromService, addLinkToService, addMessageMetrics, addService, addService, addService, addService, addServiceAssociation, addServicePassword, addTempPassword, allowAddService, canAccess, canAccess, canAccess, canAccess, canAccessMeta, canAccessNested, canAccessTemp, canRun, classNameOK, clearServiceLinks, clearServices, clearServices, close, createMetaForRepos, createMetaFull, createPermanentLinkTo, createServiceWrapper, defaultAdminToRemove, dynamicLinkQuery, dynamicLinksToPermanent, dynamicLinksToXml, dynamicLinksToXml, execute, finaliseInitialisation, finaliseInitialisation, finaliseModule, finaliseThisConfig, GET, getAllLinkToService, getAllowAddService, getAutonomicManagerConfig, getCommunicationClientURI, getDescription, getFullPath, getIsRemoteCall, getLinkFromService, getLinkToService, getLocalRemoteID, getParent, getParent, getPassword, getPassword, getPassword, getPasswordHandler, getPrivateMethods, getPublicMethods, getPublicServiceClassname, getServerPassword, getService, getService, getServiceAdmin, getServiceClasses, getServiceGrade, getServiceLinks, getServiceNames, getServiceNames, getServiceNames, getServiceNumber, getServiceOrWrapper, getServiceState, getServiceType, getServiceTypes, handshake, hasCommunicationID, hasLinkTo, hasServerPassword, hasService, hasServiceType, isCorrectPassword, isPrivateMethod, isPublicMethod, isStarted, linksToXml, passwordsStateToXml, permanentLinksToXml, reflectionMethods, reflectionObject, removeAllLinksTo, removeAllServices, removeAllServices, removeLinkFromService, removeLinkToService, removePermanentLinkTo, removeServiceAssociation, removeServiceID, removeServicePath, removeServicePath, removeTempPassword, serviceNegotiate, serviceToXml, serviceToXml, setAdminInfo, setCanAccessMeta, setCanAccessNested, setData, setDataModule, setDataModule, setDescription, setIsRemoteCall, setOtherMeta, setParent, setParent, setServerPassword, setServiceGrade, setServiceModule, setServiceState, startAllThreads, startThread, stopAllThreads, syncToAsync, syncToAsyncReply, syncToAsyncTransit, xmlToDynamicLinks, xmlToService`

    - ### Methods inherited from class org.licas.module.ServiceModule

      `getShutDown, setShutDown, setShutDown`

    - ### Methods inherited from class org.licas.module.FrameworkModule

      `canAccess, getPasswordHandler, getServicePassword, getServiceType, isAdminKey, setServiceDetails, setServiceType`

    - ### Methods inherited from class org.licas.module.LicasModule

      `getJarFile, getUUID, loadObject, setJarFile, setUUID, threadAliveState`

    - ### Methods inherited from class java.lang.Thread

      `activeCount, checkAccess, clone, countStackFrames, currentThread, destroy, dumpStack, enumerate, getAllStackTraces, getContextClassLoader, getDefaultUncaughtExceptionHandler, getId, getName, getPriority, getStackTrace, getState, getThreadGroup, getUncaughtExceptionHandler, holdsLock, interrupt, interrupted, isAlive, isDaemon, isInterrupted, join, join, join, resume, setContextClassLoader, setDaemon, setDefaultUncaughtExceptionHandler, setName, setPriority, setUncaughtExceptionHandler, sleep, sleep, start, stop, stop, suspend, toString, yield`

    - ### Methods inherited from class java.lang.Object

      `equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait`

    - ### Methods inherited from interface org.licas.def.DataServiceDef

      `setData`

    - ### Methods inherited from interface org.licas.def.ServiceDef

      `getUUID, setJarFile, setUUID`

- - ### Field Detail

    - #### sleepTime

          protected long sleepTime

      Time period between behaviour events. Allocated a default value of `ServiceConst`.`BEHAVIOURLOOPSLEEP` milliseconds.

    - #### iterations

          protected long iterations

      Number of behaviour events to execute, then shut-down the service. If `iterations <= 0` then execute continuously.

    - #### bm

          protected BehaviourModule bm

      Module to manage the actions of the behaviour.

    - #### autoEngine

          protected AutoEngine autoEngine

      Auto engine for this service, not the autonomic manager. Can be configured through the admin script.

    - #### autoManager

          protected AutonomicManager autoManager

      The autonomic manager monitoring this service

  - ### Constructor Detail

    - #### Auto

          public Auto()
               throws java.lang.Exception

      Creates a new instance of Auto. Password and service key set to `anon` by default.
      Throws:
        `java.lang.Exception` - any error.

    - #### Auto

          public Auto(java.lang.String thisPassword,
                      java.lang.String thisAdminKey)
               throws java.lang.Exception

      Creates a new instance of Auto.
      Parameters:
        `thisPassword` - password to invoke this service.
        `thisAdminKey` - admin key for this service.
      Throws:
        `java.lang.Exception` - any error.

    - #### Auto

          public Auto(java.lang.String thisPassword,
                      java.lang.String thisAdminKey,
                      org.licas_xml.abs.Element adminXml)
               throws java.lang.Exception

      Creates a new instance of Auto.
      Parameters:
        `thisPassword` - password to invoke this service.
        `thisAdminKey` - admin key for this service.
        `adminXml` - the admin info or description of this service.
      Throws:
        `java.lang.Exception` - any error.

  - ### Method Detail

    - #### setBehaviourModule

          protected void setBehaviourModule()
                                     throws java.lang.Exception

      Set the type of behaviour that the control loop uses to evaluate the service.
      Throws:
        `java.lang.Exception` - any error.

    - #### setAutoEngine

          protected void setAutoEngine()

      Initialise and create the auto engine.

    - #### getAutoEngine

          protected AutoEngine getAutoEngine()

      Get the auto engine.
      Returns:
        the value of autoEngine.

    - #### setInstanceValues

          protected void setInstanceValues(org.licas_xml.abs.Element instanceValues)
                                    throws java.lang.Exception

      Set actual values for variable instances if they are defined.

      `NOTE:` you must add this method to your own derived class if you use it, so that the private variables in that class can be accessed. It is ignored unless it gets called through the script initialisation process.

      Overrides:
        `setInstanceValues` in class `DataService`
      Parameters:
        `instanceValues` - the admin script part that defines instance values.
      Throws:
        `java.lang.Exception` - any error.

    - #### getInstanceValue

          protected java.lang.Object getInstanceValue(java.lang.String varName)
                                               throws java.lang.Exception

      Get the value of the specified variable if it exists.

      `NOTE:` you must add this method to your own derived class if you use it, so that the private variables in that class can be accessed. It is ignored unless it gets called through the script initialisation process.

      Overrides:
        `getInstanceValue` in class `DataService`
      Parameters:
        `varName` - the name of the variable to check for.
      Returns:
        the variable value, or null if it does not exist.
      Throws:
        `java.lang.Exception` - any error.

    - #### setSerializeValues

          protected void setSerializeValues(org.licas_xml.abs.Element serializeXml)
                                     throws java.lang.Exception

      Set actual values for serialized variable instances if they are defined.

      `NOTE:` you must add this method to your own derived class if you use it, so that the private variables in that class can be accessed.

      Overrides:
        `setSerializeValues` in class `DataService`
      Parameters:
        `serializeXml` - the admin script part that defines serialize instance values.
      Throws:
        `java.lang.Exception` - any error.

    - #### setProcessScript

          public boolean setProcessScript(org.licas_xml.abs.Element theScript,
                                          java.lang.String adminKey)
                                   throws java.lang.Exception

      Set or update the auto engine `AiConst`.`PROCESS` script to execute a (business) process through the script description.
      Parameters:
        `theScript` - the auto engine script to execute.
        `adminKey` - the admin key for the service.
      Returns:
        true if set, false if the password is incorrect.
      Throws:
        `java.lang.Exception` - any error.

    - #### behaviourAction

          protected abstract MessageInfo behaviourAction(MessageInfo messageInfo)
                                                  throws java.lang.Exception

      Execute a behaviour, such as an evaluation and result.
      Parameters:
        `messageInfo` - the message to evaluate.
      Returns:
        the result of executing the behaviour.
      Throws:
        `java.lang.Exception` - any error.

    - #### invokeBehaviour

          public java.lang.Object invokeBehaviour(MessageInfo messageInfo)
                                           throws ServiceException,
                                                  java.lang.Exception

      This can be used to execute a single invocation of the service's `evaluateBehaviour` method. This is correct if the service is waiting to be invoked and is not running on a thread.
      Parameters:
        `messageInfo` - the message with data to evaluate. This is only the values related to the evaluation result, not the whole set of service values.
      Returns:
        the evaluation reply. This is the `evaluateBehaviour` `MessageInfo` reply object. If this is not one of the basic types, a parser needs to be added to parse the complex object to/from XML.
      Throws:
        `ServiceException` - if this service's main thread is currently running.
        `java.lang.Exception` - and error.

    - #### run

          public void run()

      This is the default method to start the service thread. This default process periodically executes and evaluates a behaviour.
      Specified by:
        `run` in interface `java.lang.Runnable`
      Overrides:
        `run` in class `java.lang.Thread`

    - #### autoQueueMessage

          public MessageInfo autoQueueMessage(org.dcs.query_process.model.activity.Script_Auto scriptAuto,
                                              java.lang.String adminKey)
                                       throws PasswordException

      Retrieve and remove the first message on the auto manager's queue with the specified condition - method name, timestamp, etc.
      Parameters:
        `scriptAuto` - the script element with a single condition to use.
        `adminKey` - the admin key for this service.
      Returns:
        the message object if one exists, null otherwise.
      Throws:
        `PasswordException` - if the admin key is incorrect.

    - #### autoAction

          public void autoAction(java.lang.String action,
                                 java.lang.String adminKey)
                          throws PasswordException,
                                 ServiceException,
                                 java.lang.Exception

      This allows the autonomic manager to ask the parent service to perform some action.
      Parameters:
        `action` - to action to perform.
        `adminKey` - the admin key for this service.
      Throws:
        `PasswordException` - if the admin key is incorrect.
        `ServiceException` - if a licas service problem occurs.
        `java.lang.Exception` - any other error.

    - #### removeCommunicationID

          protected void removeCommunicationID(java.lang.String commID)

      Remove the communication ID reference.
      Overrides:
        `removeCommunicationID` in class `Service`
      Parameters:
        `commID` - the communication ID.

    - #### messageReply

          public boolean messageReply(java.lang.Object message)
                               throws java.lang.Exception

      This can be used as part of a conversation, for example, to reply to some other method invocation, or even to start a conversation. The `message` object is added to the service queue, wrapped in a `MessageInfo` object, with optional states and conversation protocol. It is also used internally by the communication system to queue the `CallObject` `MethodInfo` requests. When accessed through the communication mechanism, a `communicationID` from the client has already been looked for in the (MethodInfo) message object. That could then be used to identify this particular message, or as part of conversation.

      If used internally, the `MethodInfo` message is re-packaged with some state information, before being queued in the `AutonomicManager`. The messages are then lifted off the queue in order, as part of an `asynchronous` process. If the parameter is a MessageInfo object itself, it is queued as is and so its state and other values can be set. This would allow for a conversation protocol, for example.

      The `AutonomicManagerDefault` now records some basic stats for the messages that are received, such as number of calls or message size, as would be the case for any server. It is stored locally to this service, not globally in the server, but the server can query it. There is no other monitoring as default and so messages just get added and removed in order, without any consideration of their state or content. The state variables are therefore ignored by the default system and the message object is simply stored and returned again. For example, the `evaluateBehaviour` method calls `autoManager.getMessage` to retrieve the next message Object to evaluate. You can change any of this in a derived class.

      One final important option is in fact to ask the system not to queue the message. If the message parameter is a `MessageInfo` object and has a `message state` of `AiConst`.`NOACTION` already added, then it is not added to the message queue. You could add service-specific code to process it further, where this allows for an immediate response, such as setting a variable value, on the service itself.

      Parameters:
        `message` - an object representing the result of the task. Can be null.
      Returns:
        true if processed correctly, or false if there is no autonomic manager.
      Throws:
        `java.lang.Exception` - any error.

    - #### getMessageState

          protected java.lang.String getMessageState(java.lang.Object message)

      Calculate the current state for the message and related conversation. If this service is involved in conversations with several other services, for example, each conversation can be at a different stage, resulting in a different state for each conversation process. This method should be used to return the current state for the specified conversation. It should be implemented by any derived class, but only called internally, inside the `messageReply` method, for example.

      This default version checks if the message parameter is a `MessageInfo` object. If it is, it returns its `getMessageState` method call. If it is not, then it returns the thread state for this service.

      Parameters:
        `message` - an object representing a result from the other service in the conversation. This can represent the result of the last conversation task, or can be null if no information is required.
      Returns:
        the state of this service relating to the selected conversation.

    - #### setAutonomicManager

          protected void setAutonomicManager(AutonomicManager thisAutoManager)
                                      throws java.lang.Exception

      Set a reference to the autonomic manager monitoring this service.
      Parameters:
        `thisAutoManager` - the autonomic manager.
      Throws:
        `java.lang.Exception` - any error.

    - #### interrupt

          public boolean interrupt(java.lang.String adminKey)

      You must call this method to interrupt the thread. This also interrupts all nested services.
      Overrides:
        `interrupt` in class `Service`
      Parameters:
        `adminKey` - the key to identify unique loading of the service.
      Returns:
        true if the service is stopped.