de.esprit.appsuite.task

## Class AbstractAsyncExecutable<C extends ApplicationContext>

- java.lang.Object
- - de.esprit.common.util.DumpableObject
  - - de.esprit.appsuite.launch.AbstractApplicationObject<C>
    - - de.esprit.appsuite.task.AbstractAsyncExecutable<C>

- All Implemented Interfaces:
    ApplicationObject<C>, AsyncExecutable<C>, CancellableTask, TaskMonitorSupport, SimpleLogSupport, Dumpable, Executable
  Direct Known Subclasses:
    AbstractArchiveExtractor, AbstractArchiver, AbstractAsciiParser, AbstractAsyncTask, AsciiWriter, AsyncAgentExecutorAdapter, DataParser, DataWriter, DBOCompiler, NdfWriter, XmlDataParser

      public abstract class AbstractAsyncExecutable<C extends ApplicationContext>
      extends AbstractApplicationObject<C>
      implements AsyncExecutable<C>

  This is a default implementation of `AsyncExecutable` used for subclassing.
  Author:
    Rainer Buesch

- - ### Field Summary

    Fields
    Modifier and Type | Field and Description
    --- | ---
    `protected java.util.concurrent.atomic.AtomicReference<AsyncExecutable>` | `childTaskRef`
    `protected boolean` | `isTestMode`
    `protected TaskMonitorController` | `monitorController`
    `protected java.util.concurrent.atomic.AtomicReference` | `resultRef`
    `protected RunStateFlag` | `stateFlag`

  - ### Constructor Summary

    Constructors
    Modifier | Constructor and Description
    --- | ---
    `protected` | `AbstractAsyncExecutable(C ctx)`
    `protected` | `AbstractAsyncExecutable(C ctx, LogChannel logCh)`
    `protected` | `AbstractAsyncExecutable(C ctx, LogChannel logCh, java.lang.String taskName, TaskType taskType)`
    `protected` | `AbstractAsyncExecutable(C ctx, java.lang.String taskName)`
    `protected` | `AbstractAsyncExecutable(C ctx, java.lang.String taskName, TaskType taskType)`

  - ### Method Summary

    Methods
    Modifier and Type | Method and Description
    --- | ---
    `void` | `addMonitor(TaskMonitor monitor)` Adds a `TaskMonitor` which is notified about `RunStateFlag` changes
    `void` | `checkCancelled()` Checks whether the task was cancelled and throws a `CancellationException` just in case.
    `void` | `checkForErrorAndRethrow(java.lang.Exception e)` Stores an Error (if any) or a cancellation in the `RunStateFlag` of this task.
    `void` | `clearMonitors()` Removes all `TaskMonitor`s
    `protected RunStateFlag` | `createRunStateFlag()` Creates the `RunStateFlag` instance of this task.
    `protected void` | `doOnCancel()` This method is called after having detected cancellation.
    `protected void` | `doOnFailure(java.lang.Exception error)` Is called when the task failed.
    `void` | `execute()` This method just calls `executeAsync()` synchronously within the same thread (not putting the task into a thread-pool).
    `abstract void` | `executeAsync()` Contains the code to be executed asynchronously.
    `void` | `executeSubTask(AsyncExecutable subTask)` Runs the subTask synchronously within the same execution thread.
    `java.lang.Exception` | `getError()`
    `int` | `getMaxProgressSteps()`
    `int` | `getMonitorCount()` Tells how many `TaskMonitor`s are registered
    `TaskMonitor[]` | `getMonitors()` Return the current `TaskMonitor`s if any
    `java.lang.String` | `getName()` Return the task-name which is rendered by the RunStateFlag during run.
    `int` | `getProgressStepCount()` Returns the number of progress steps notified during the last run.
    `<R> R` | `getResult()` Returns the execution result of this task, if any.
    `RunStateFlag` | `getRunStateFlag()` Returns the current `RunStateFlag`.
    `TaskId` | `getTaskId()` Returns an identifier object for this task.
    `TaskType` | `getType()` Return the task-type which is rendered by the RunStateFlag during run.
    `void` | `handleCancellation()` This method is public as an implementation side effect.
    `void` | `handleFailure(java.lang.Exception error)` This method is public as an implementation side effect.
    `protected void` | `handleFinish()`
    `protected void` | `handleStart()`
    `protected void` | `handleSuccess()`
    `boolean` | `hasError()`
    `boolean` | `hasMonitor()` Tells whether there are `TaskMonitor`s registered
    `boolean` | `isCancellable()` Tells whether this task can be cancelled.
    `void` | `notifyProceeded(java.lang.Object result, int step, int maxSteps, java.lang.String message)` Notifies progress to an attached task-monitor.
    `protected void` | `registerTaskStateChange()`
    `void` | `removeMonitor(TaskMonitor monitor)` Removes the given `TaskMonitor` from the registration
    `protected void` | `resetProgress()`
    `void` | `setCancellable(boolean isCancellable)` Tells whether this task is cancellable - is true by default.
    `void` | `setLogLevel(LogLevel level)` Changes the `LogLevel` of the task's `LogChannel`
    `void` | `setMaxProgressSteps(int expectedProgressSteps)` Sets the max number of progressSteps expected (i.e. for driving a progress bar).
    `void` | `setMonitor(TaskMonitor monitor)` Clears all monitors and adds the given monitor as the only one.
    `void` | `setName(NlsKey trKey, java.lang.Object... args)` Convenience method for setting translated taskName with optional args.
    `void` | `setName(java.lang.String taskName)` Sets the taskName for this executable which will also be reflected by the `TaskId`.
    `void` | `setResult(java.lang.Object result)` If this task produces any result it uses this method to store it.
    `void` | `setRunStateFlag(RunStateFlag stateFlag)` Used to set a `RunStateFlag` if this task should run as a childTask.
    `protected void` | `setTaskId(TaskId taskId)`
    `void` | `setType(TaskType taskType)` Sets the `TaskType` for this task.
    `protected boolean` | `shouldFireMonitor()`
    `void` | `sleepChecked(long millis)` Used to delay task execution.
    `boolean` | `wasCancelled()` Tells whether ever an attempt has been made to cancel this task.

    - ### Methods inherited from class de.esprit.appsuite.launch.AbstractApplicationObject

      `getApplicationContext, getLogChannel, isLogDebug, isLogVerbose, logDebug, logDump, logError, logError, logFatal, logInfo, logVerbose, logWarning, setLogChannel`

    - ### Methods inherited from class de.esprit.common.util.DumpableObject

      `configureDumpHeadlineLength, configureDumpMaxElementsPrinted, copyDumpStringValues, copyToStringValues, createDumpHeader, toDumpString, toDumpString, toString, toString`

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

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

    - ### Methods inherited from interface de.esprit.appsuite.launch.ApplicationObject

      `getApplicationContext`

    - ### Methods inherited from interface de.esprit.common.log.SimpleLogSupport

      `getLogChannel, isLogDebug, isLogVerbose, logDebug, logDump, logError, logError, logFatal, logInfo, logVerbose, logWarning, setLogChannel`

- - ### Field Detail

    - #### isTestMode

          protected boolean isTestMode

    - #### resultRef

          protected final java.util.concurrent.atomic.AtomicReference resultRef

    - #### monitorController

          protected final TaskMonitorController monitorController

    - #### childTaskRef

          protected final java.util.concurrent.atomic.AtomicReference<AsyncExecutable> childTaskRef

    - #### stateFlag

          protected RunStateFlag stateFlag

  - ### Constructor Detail

    - #### AbstractAsyncExecutable

          protected AbstractAsyncExecutable(C ctx)

    - #### AbstractAsyncExecutable

          protected AbstractAsyncExecutable(C ctx,
                                 LogChannel logCh)

    - #### AbstractAsyncExecutable

          protected AbstractAsyncExecutable(C ctx,
                                 java.lang.String taskName)

    - #### AbstractAsyncExecutable

          protected AbstractAsyncExecutable(C ctx,
                                 java.lang.String taskName,
                                 TaskType taskType)

    - #### AbstractAsyncExecutable

          protected AbstractAsyncExecutable(C ctx,
                                 LogChannel logCh,
                                 java.lang.String taskName,
                                 TaskType taskType)

  - ### Method Detail

    - #### setLogLevel

          public void setLogLevel(LogLevel level)

      Changes the `LogLevel` of the task's `LogChannel`

    - #### setName

          public final void setName(NlsKey trKey,
                     java.lang.Object... args)

      Convenience method for setting translated taskName with optional args.
      See Also:
        `setName(String)`

    - #### setName

          public void setName(java.lang.String taskName)

      Sets the taskName for this executable which will also be reflected by the `TaskId`. If taskName is null then the simple className of this instance will be used as a default.
      Specified by:
        `setName` in interface `AsyncExecutable<C extends ApplicationContext>`

    - #### getName

          public final java.lang.String getName()

      Description copied from interface: `AsyncExecutable`
      Return the task-name which is rendered by the RunStateFlag during run.
      Specified by:
        `getName` in interface `AsyncExecutable<C extends ApplicationContext>`

    - #### setType

          public final void setType(TaskType taskType)

      Sets the `TaskType` for this task. This type will also be reflected by the `RunStateFlag` and the `TaskId`.

    - #### getType

          public TaskType getType()

      Description copied from interface: `AsyncExecutable`
      Return the task-type which is rendered by the RunStateFlag during run.
      Specified by:
        `getType` in interface `AsyncExecutable<C extends ApplicationContext>`

    - #### getTaskId

          public TaskId getTaskId()

      Description copied from interface: `AsyncExecutable`
      Returns an identifier object for this task. Note: The `TaskId` is used to model the task-hierarchy in a `RunStateFlag`. For `AsyncExecutable`s it's always an instance of `PseudoTaskId`.
      Specified by:
        `getTaskId` in interface `AsyncExecutable<C extends ApplicationContext>`

    - #### setTaskId

          protected void setTaskId(TaskId taskId)

    - #### setMaxProgressSteps

          public void setMaxProgressSteps(int expectedProgressSteps)

      Sets the max number of progressSteps expected (i.e. for driving a progress bar). A value of zero (default) indicates that it's not known how many progress notifications will be received. Therefore an attached progress bar cannot render the progress percentage and runs in 'floating' mode instead. Note that a negative value will suppress any progress notifications to be forwarded to the attached `TaskMonitor`s.
      See Also:
        `getMaxProgressSteps()`

    - #### getMaxProgressSteps

          public final int getMaxProgressSteps()

      See Also:
        `setMaxProgressSteps(int)`

    - #### getProgressStepCount

          public final int getProgressStepCount()

      Returns the number of progress steps notified during the last run.

    - #### resetProgress

          protected final void resetProgress()

    - #### createRunStateFlag

          protected RunStateFlag createRunStateFlag()

      Creates the `RunStateFlag` instance of this task. Is only called once at construction time.

    - #### setRunStateFlag

          public final void setRunStateFlag(RunStateFlag stateFlag)

      Used to set a `RunStateFlag` if this task should run as a childTask. By default this task has got its own RunStateFlag already set.
      Specified by:
        `setRunStateFlag` in interface `AsyncExecutable<C extends ApplicationContext>`
      See Also:
        `getRunStateFlag()`

    - #### getRunStateFlag

          public RunStateFlag getRunStateFlag()

      Description copied from interface: `AsyncExecutable`
      Returns the current `RunStateFlag`. Note that there is exactly one `RunStateFlag` per running task. Child-tasks as well as sub-tasks share it with their parents.
      Specified by:
        `getRunStateFlag` in interface `AsyncExecutable<C extends ApplicationContext>`

    - #### checkForErrorAndRethrow

          public void checkForErrorAndRethrow(java.lang.Exception e)
                                       throws java.lang.Exception

      Stores an Error (if any) or a cancellation in the `RunStateFlag` of this task. Note that `CancellationException`. `InterruptedException` and `StopException` are NOT considered to be an error. In any case the given Exception is rethrown.
      Specified by:
        `checkForErrorAndRethrow` in interface `AsyncExecutable<C extends ApplicationContext>`
      Throws:
        `java.lang.Exception`

    - #### registerTaskStateChange

          protected final void registerTaskStateChange()

    - #### handleCancellation

          public final void handleCancellation()

      This method is public as an implementation side effect. Do NOT call this method directly. Rather override `doOnCancel()`
      Specified by:
        `handleCancellation` in interface `AsyncExecutable<C extends ApplicationContext>`

    - #### handleFailure

          public final void handleFailure(java.lang.Exception error)

      This method is public as an implementation side effect. Do NOT call this method directly. Rather override `doOnFailure(Exception)`
      Specified by:
        `handleFailure` in interface `AsyncExecutable<C extends ApplicationContext>`

    - #### shouldFireMonitor

          protected final boolean shouldFireMonitor()

    - #### executeSubTask

          public void executeSubTask(AsyncExecutable subTask)
                              throws java.lang.Exception

      Runs the subTask synchronously within the same execution thread. Note that the subTask shares the `RunStateFlag` with the main-task. During subTask execution the monitor will receive CHILD_STARTED CHILD_SUCCEEDED and CHILD_FINISHED notifications. Any PROGRESS notifications in between are associated to the current subTask.
      Specified by:
        `executeSubTask` in interface `AsyncExecutable<C extends ApplicationContext>`
      Throws:
        `java.lang.Exception`

    - #### addMonitor

          public void addMonitor(TaskMonitor monitor)

      Description copied from interface: `TaskMonitorSupport`
      Adds a `TaskMonitor` which is notified about `RunStateFlag` changes
      Specified by:
        `addMonitor` in interface `TaskMonitorSupport`

    - #### removeMonitor

          public void removeMonitor(TaskMonitor monitor)

      Description copied from interface: `TaskMonitorSupport`
      Removes the given `TaskMonitor` from the registration
      Specified by:
        `removeMonitor` in interface `TaskMonitorSupport`

    - #### getMonitors

          public TaskMonitor[] getMonitors()

      Description copied from interface: `TaskMonitorSupport`
      Return the current `TaskMonitor`s if any
      Specified by:
        `getMonitors` in interface `TaskMonitorSupport`

    - #### hasMonitor

          public boolean hasMonitor()

      Description copied from interface: `TaskMonitorSupport`
      Tells whether there are `TaskMonitor`s registered
      Specified by:
        `hasMonitor` in interface `TaskMonitorSupport`

    - #### getMonitorCount

          public int getMonitorCount()

      Description copied from interface: `TaskMonitorSupport`
      Tells how many `TaskMonitor`s are registered
      Specified by:
        `getMonitorCount` in interface `TaskMonitorSupport`

    - #### clearMonitors

          public void clearMonitors()

      Description copied from interface: `TaskMonitorSupport`
      Removes all `TaskMonitor`s
      Specified by:
        `clearMonitors` in interface `TaskMonitorSupport`

    - #### setMonitor

          public void setMonitor(TaskMonitor monitor)

      Clears all monitors and adds the given monitor as the only one.

    - #### doOnFailure

          protected void doOnFailure(java.lang.Exception error)

      Is called when the task failed. Maybe overridden to perform any cleanup on error. Note that any Exceptions thrown are caught and just logged but do NOT affect the task.

    - #### doOnCancel

          protected void doOnCancel()

      This method is called after having detected cancellation. May be overridden to perform any cleanup. Note that any Exceptions thrown are caught and just logged but do NOT affect the task.

    - #### checkCancelled

          public final void checkCancelled()

      Checks whether the task was cancelled and throws a `CancellationException` just in case. This methods should be called within loops in order to react promptly on cancellation.
      Specified by:
        `checkCancelled` in interface `AsyncExecutable<C extends ApplicationContext>`

    - #### wasCancelled

          public final boolean wasCancelled()

      Description copied from interface: `CancellableTask`
      Tells whether ever an attempt has been made to cancel this task.
      Specified by:
        `wasCancelled` in interface `CancellableTask`

    - #### sleepChecked

          public final void sleepChecked(long millis)

      Used to delay task execution. This method may be called within loops in order to be friendly to other tasks and not making the system too busy. Note that when going to and awaking from sleep the cancel state is checked and a `CancellationException` is thrown just in case.
      Specified by:
        `sleepChecked` in interface `AsyncExecutable<C extends ApplicationContext>`

    - #### hasError

          public final boolean hasError()

    - #### getError

          public final java.lang.Exception getError()

    - #### isCancellable

          public final boolean isCancellable()

      Description copied from interface: `AsyncExecutable`
      Tells whether this task can be cancelled. A task may want to ignore canceling during critical phases. This flag may be set during task run in order to enable/disable canceling.
      Specified by:
        `isCancellable` in interface `AsyncExecutable<C extends ApplicationContext>`
      See Also:
        `AsyncExecutable.setCancellable(boolean)`

    - #### setCancellable

          public final void setCancellable(boolean isCancellable)

      Description copied from interface: `AsyncExecutable`
      Tells whether this task is cancellable - is true by default.
      Specified by:
        `setCancellable` in interface `AsyncExecutable<C extends ApplicationContext>`

    - #### setResult

          public final void setResult(java.lang.Object result)

      If this task produces any result it uses this method to store it.
      Specified by:
        `setResult` in interface `AsyncExecutable<C extends ApplicationContext>`
      See Also:
        `getResult()`

    - #### getResult

          public <R> R getResult()

      Description copied from interface: `AsyncExecutable`
      Returns the execution result of this task, if any. This call does NOT block but fetches the result whatever it is at the moment.
      Specified by:
        `getResult` in interface `AsyncExecutable<C extends ApplicationContext>`
      See Also:
        `AsyncExecutable.setResult(Object)`

    - #### notifyProceeded

          public void notifyProceeded(java.lang.Object result,
                             int step,
                             int maxSteps,
                             java.lang.String message)

      Notifies progress to an attached task-monitor. In fact delegates to `TaskMonitor.taskProceeded(RunStateFlag, Object, int, int, String)` IMPORTANT: the 'result' object passed here MUST NOT be changed any more by the running task. If this cannot be guaranteed make sure that you pass a copy here! A copy is not made automatically because in many cases this would not be necessary. The progressCount value is typically the same as returned by `getMaxProgressSteps()`. Similar the step value is typically the same as returned by `getProgressStepCount()`. Anyway you are allowed to pass these values explicitly because a running task may have complex behavior during runtime. For example: a task may not know at start time how many steps it will do - at that time the ProgressBar shows up floating. But later on it has calculated the steps it will need and then it performs step notifications for driving the progress bar on a percentage value.
      Specified by:
        `notifyProceeded` in interface `AsyncExecutable<C extends ApplicationContext>`
      Parameters:
        `result` - any intermediate result that may be achieved so far
        `step` - the count of progress steps
        `maxSteps` - the expected maximum number of progress steps
        `message` - any textual message explaining what the progress is
      Note
        You can switch off sending progress notification at all by setting `setMaxProgressSteps(int)` to a negative value. A notification with a negative value for the 'step' parameter will be ignored by the progress bar. That way you can send for instance a 'result' value without modifying the current progress.

    - #### handleStart

          protected void handleStart()
                              throws java.lang.Exception

      Throws:
        `java.lang.Exception`

    - #### handleSuccess

          protected void handleSuccess()

    - #### handleFinish

          protected void handleFinish()

    - #### executeAsync

          public abstract void executeAsync()
                                     throws java.lang.Exception

      Description copied from interface: `AsyncExecutable`
      Contains the code to be executed asynchronously. WARNING: This method should never be called directly by the programmer. It rather must be called by `Runnable.run()` for async execution.
      Specified by:
        `executeAsync` in interface `AsyncExecutable<C extends ApplicationContext>`
      Throws:
        `java.lang.Exception`
      See Also:
        `for synchronous execution`

    - #### execute

          public void execute()
                       throws java.lang.Exception

      This method just calls `executeAsync()` synchronously within the same thread (not putting the task into a thread-pool). Note that during sync execution the task is NOT registered at the `TaskManager` and no PROGRESS is fired (it would not be repainted anyway by the ET because the ET itself is the executor).
      Specified by:
        `execute` in interface `Executable`
      Throws:
        `java.lang.Exception` - on failure (but not on cancellation)
      See Also:
        `executeAsync()`

Copyright © 2014 EsprIT-Systems. All Rights Reserved.