001/* 002 Licensed to the Apache Software Foundation (ASF) under one 003 or more contributor license agreements. See the NOTICE file 004 distributed with this work for additional information 005 regarding copyright ownership. The ASF licenses this file 006 to you under the Apache License, Version 2.0 (the 007 "License"); you may not use this file except in compliance 008 with the License. You may obtain a copy of the License at 009 010 http://www.apache.org/licenses/LICENSE-2.0 011 012 Unless required by applicable law or agreed to in writing, 013 software distributed under the License is distributed on an 014 "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 015 KIND, either express or implied. See the License for the 016 specific language governing permissions and limitations 017 under the License. 018 */ 019package org.apache.wiki.workflow; 020 021import org.apache.wiki.api.core.Context; 022import org.apache.wiki.api.core.Engine; 023import org.apache.wiki.api.exceptions.WikiException; 024import org.apache.wiki.event.WikiEventEmitter; 025import org.apache.wiki.event.WorkflowEvent; 026import org.apache.wiki.util.Synchronizer; 027 028import java.io.IOException; 029import java.io.ObjectInputStream; 030import java.io.Serializable; 031import java.security.Principal; 032import java.util.ArrayList; 033import java.util.Collections; 034import java.util.Date; 035import java.util.LinkedList; 036import java.util.List; 037import java.util.Map; 038import java.util.concurrent.ConcurrentHashMap; 039import java.util.concurrent.atomic.AtomicInteger; 040import java.util.concurrent.locks.ReentrantLock; 041 042 043/** 044 * <p> 045 * Sequence of {@link Step} objects linked together. Workflows are always initialized with a message key that denotes the name of the 046 * Workflow, and a Principal that represents its owner. 047 * </p> 048 * <h2>Workflow lifecycle</h2> 049 * A Workflow's state (obtained by {@link #getCurrentState()}) will be one of the following: 050 * </p> 051 * <ul> 052 * <li><strong>{@link #CREATED}</strong>: after the Workflow has been instantiated, but before it has been started using the {@link #start(Context)} 053 * method.</li> 054 * <li><strong>{@link #RUNNING}</strong>: after the Workflow has been started using the {@link #start(Context)} method, but before it has 055 * finished processing all Steps. Note that a Workflow can only be started once; attempting to start it again results in an 056 * IllegalStateException. Callers can place the Workflow into the WAITING state by calling {@link #waitstate()}.</li> 057 * <li><strong>{@link #WAITING}</strong>: when the Workflow has temporarily paused, for example because of a pending Decision. Once the 058 * responsible actor decides what to do, the caller can change the Workflow back to the RUNNING state by calling the {@link #restart(Context)} 059 * method (this is done automatically by the Decision class, for instance, when the {@link Decision#decide(Outcome, Context)} method is invoked)</li> 060 * <li><strong>{@link #COMPLETED}</strong>: after the Workflow has finished processing all Steps, without errors.</li> 061 * <li><strong>{@link #ABORTED}</strong>: if a Step has elected to abort the Workflow.</li> 062 * </ul> 063 * <h2>Steps and processing algorithm</h2> 064 * <p> 065 * Workflow Step objects can be of type {@link Decision}, {@link Task} or other Step subclasses. Decisions require user input, while Tasks 066 * do not. See the {@link Step} class for more details. 067 * </p> 068 * <p> 069 * After instantiating a new Workflow (but before telling it to {@link #start(Context)}), calling classes should specify the first Step by 070 * executing the {@link #setFirstStep(Step)} method. Additional Steps can be chained by invoking the first step's 071 * {@link Step#addSuccessor(Outcome, Step)} method. 072 * </p> 073 * <p> 074 * When a Workflow's <code>start</code> method is invoked, the Workflow retrieves the first Step and processes it. This Step, and subsequent 075 * ones, are processed as follows: 076 * </p> 077 * <p> 078 * <ul> 079 * <li>The Step's {@link Step#start()} method executes, which sets the start time.</li> 080 * <li>The Step's {@link Step#execute(Context)} method is called to begin processing, which will return an Outcome to indicate completion, 081 * continuation or errors:</li> 082 * <ul> 083 * <li>{@link Outcome#STEP_COMPLETE} indicates that the execution method ran without errors, and that the Step should be considered 084 * "completed."</li> 085 * <li>{@link Outcome#STEP_CONTINUE} indicates that the execution method ran without errors, but that the Step is not "complete" and should 086 * be put into the WAITING state.</li> 087 * <li>{@link Outcome#STEP_ABORT} indicates that the execution method encountered errors, and should abort the Step <em>and</em> the 088 * Workflow as a whole. When this happens, the Workflow will set the current Step's Outcome to {@link Outcome#STEP_ABORT} and invoke the 089 * Workflow's {@link #abort(Context)} method. The Step's processing errors, if any, can be retrieved by {@link Step#getErrors()}.</li> 090 * </ul> 091 * <li>The Outcome of the <code>execute</code> method also affects what happens next. Depending on the result (and assuming the Step did 092 * not abort), the Workflow will either move on to the next Step or put the Workflow into the {@link Workflow#WAITING} state:</li> 093 * <ul> 094 * <li>If the Outcome denoted "completion" (<em>i.e.</em>, its {@link Step#isCompleted()} method returns <code>true</code>) then the Step 095 * is considered complete; the Workflow looks up the next Step by calling the current Step's {@link Step#getSuccessor(Outcome)} method. If 096 * <code>successor()</code> returns a non-<code>null</code> Step, the return value is marked as the current Step and added to the Workflow's 097 * Step history. If <code>successor()</code> returns <code>null</code>, then the Workflow has no more Steps and it enters the 098 * {@link #COMPLETED} state.</li> 099 * <li>If the Outcome did not denote "completion" (<em>i.e.</em>, its {@link Step#isCompleted()} method returns <code>false</code>), then 100 * the Step still has further work to do. The Workflow enters the {@link #WAITING} state and stops further processing until a caller 101 * restarts it.</li> 102 * </ul> 103 * </ul> 104 * </p> 105 * <p> 106 * The currently executing Step can be obtained by {@link #getCurrentStep()}. The actor for the current Step is returned by 107 * {@link #getCurrentActor()}. 108 * </p> 109 * <p> 110 * To provide flexibility for specific implementations, the Workflow class provides two additional features that enable Workflow 111 * participants (<em>i.e.</em>, Workflow subclasses and Step/Task/Decision subclasses) to share context and state information. These two 112 * features are <em>named attributes</em> and <em>message arguments</em>: 113 * </p> 114 * <ul> 115 * <li><strong>Named attributes</strong> are simple key-value pairs that Workflow participants can get or set. Keys are Strings; values 116 * can be any Object. Named attributes are set with {@link #setAttribute(String, Serializable)} and retrieved with {@link #getAttribute(String)}.</li> 117 * <li><strong>Message arguments</strong> are used in combination with JSPWiki's {@link org.apache.wiki.i18n.InternationalizationManager} to 118 * create language-independent user interface messages. The message argument array is retrieved via {@link #getMessageArguments()}; the 119 * first two array elements will always be these: a String representing work flow owner's name, and a String representing the current 120 * actor's name. Workflow participants can add to this array by invoking {@link #addMessageArgument(Serializable)}.</li> 121 * </ul> 122 * <h2>Example</h2> 123 * <p> 124 * Workflow Steps can be very powerful when linked together. JSPWiki provides two abstract subclasses classes that you can use to build 125 * your own Workflows: Tasks and Decisions. As noted, Tasks are Steps that execute without user intervention, while Decisions require 126 * actors (<em>aka</em> Principals) to take action. Decisions and Tasks can be mixed freely to produce some highly elaborate branching 127 * structures. 128 * </p> 129 * <p> 130 * Here is a simple case. For example, suppose you would like to create a Workflow that (a) executes a initialization Task, (b) pauses to 131 * obtain an approval Decision from a user in the Admin group, and if approved, (c) executes a "finish" Task. Here's sample code that 132 * illustrates how to do it: 133 * </p> 134 * 135 * <pre> 136 * // Create workflow; owner is current user 137 * 1 Workflow workflow = new Workflow( " workflow.myworkflow ", context.getCurrentUser() ); 138 * 139 * // Create custom initialization task 140 * 2 Step initTask = new InitTask( this ); 141 * 142 * // Create finish task 143 * 3 Step finishTask = new FinishTask( this ); 144 * 145 * // Create an intermediate decision step 146 * 4 Principal actor = new GroupPrincipal( "Admin" ); 147 * 5 Step decision = new SimpleDecision( this, "decision.AdminDecision", actor ); 148 * 149 * // Hook the steps together 150 * 6 initTask.addSuccessor( Outcome.STEP_COMPLETE, decision ); 151 * 7 decision.addSuccessor( Outcome.DECISION_APPROVE, finishTask ); 152 * 153 * // Set workflow's first step 154 * 8 workflow.setFirstStep( initTask ); 155 * </pre> 156 * 157 * <p> 158 * Some comments on the source code: 159 * </p> 160 * <ul> 161 * <li>Line 1 instantiates the workflow with a sample message key and designated owner Principal, in this case the current wiki user</li> 162 * <li>Lines 2 and 3 instantiate the custom Task subclasses, which contain the business logic</li> 163 * <li>Line 4 creates the relevant GroupPrincipal for the <code>Admin</code> group, who will be the actor in the Decision step</li> 164 * <li>Line 5 creates the Decision step, passing the Workflow, sample message key, and actor in the constructor</li> 165 * <li>Line 6 specifies that if the InitTask's Outcome signifies "normal completion" (STEP_COMPLETE), the SimpleDecision step should be 166 * invoked next</li> 167 * <li>Line 7 specifies that if the actor (anyone possessing the <code>Admin</code> GroupPrincipal) selects DECISION_APPROVE, the FinishTask 168 * step should be invoked</li> 169 * <li>Line 8 adds the InitTask (and all of its successor Steps, nicely wired together) to the workflow</li> 170 * </ul> 171 */ 172public class Workflow implements Serializable { 173 174 private static final long serialVersionUID = 5228149040690660032L; 175 176 private static final AtomicInteger idsCounter = new AtomicInteger( 1 ); 177 178 /** ID value: the workflow ID has not been set. */ 179 public static final int ID_NOT_SET = 0; 180 181 /** State value: Workflow completed all Steps without errors. */ 182 public static final int COMPLETED = 50; 183 184 /** State value: Workflow aborted before completion. */ 185 public static final int ABORTED = 40; 186 187 /** State value: Workflow paused, typically because a Step returned an Outcome that doesn't signify "completion." */ 188 public static final int WAITING = 30; 189 190 /** State value: Workflow started, and is running. */ 191 public static final int RUNNING = -1; 192 193 /** State value: Workflow instantiated, but not started. */ 194 public static final int CREATED = -2; 195 196 /** attribute map. */ 197 private Map< String, Serializable > m_attributes; 198 199 /** The initial Step for this Workflow. */ 200 private Step m_firstStep; 201 202 /** Flag indicating whether the Workflow has started yet. */ 203 private boolean m_started; 204 205 private final LinkedList< Step > m_history; 206 207 private int m_id; 208 209 private final String m_key; 210 211 private final Principal m_owner; 212 213 private final List<Serializable> m_messageArgs; 214 215 private int m_state; 216 217 private Step m_currentStep; 218 219 /** 220 * A lock used to ensure thread safety when accessing shared resources. 221 * This lock provides more flexibility and capabilities than the intrinsic locking mechanism, 222 * such as the ability to attempt to acquire a lock with a timeout, or to interrupt a thread 223 * waiting to acquire a lock. 224 * 225 * @see java.util.concurrent.locks.ReentrantLock 226 */ 227 private transient ReentrantLock lock = new ReentrantLock(); 228 229 private void readObject( final ObjectInputStream in ) throws IOException, ClassNotFoundException { 230 in.defaultReadObject(); 231 // Locks are not part of the serialized form, so data written by earlier releases has none either. 232 lock = new ReentrantLock(); 233 } 234 235 /** 236 * Constructs a new Workflow object with a supplied message key, owner Principal, and undefined unique identifier {@link #ID_NOT_SET}. 237 * Once instantiated the Workflow is considered to be in the {@link #CREATED} state; a caller must explicitly invoke the 238 * {@link #start(Context)} method to begin processing. 239 * <p> 240 * The Workflow is not bound to any engine, so every {@link WorkflowManager} in the JVM is notified of its creation. Use 241 * {@link #Workflow(Engine, String, Principal)} when several engines share the same classpath. 242 * </p> 243 * 244 * @param messageKey the message key used to construct a localized workflow name, such as <code>workflow.saveWikiPage</code> 245 * @param owner the Principal who owns the Workflow. Typically, this is the user who created and submitted it 246 */ 247 public Workflow( final String messageKey, final Principal owner ) { 248 this( null, messageKey, owner ); 249 } 250 251 /** 252 * Constructs a new Workflow object like {@link #Workflow(String, Principal)}, bound to the engine that is going to track it. Only the 253 * {@link WorkflowManager} of that engine is notified of the creation of the Workflow. 254 * 255 * @param engine the engine that owns the Workflow, or {@code null} if it is not bound to any engine 256 * @param messageKey the message key used to construct a localized workflow name, such as <code>workflow.saveWikiPage</code> 257 * @param owner the Principal who owns the Workflow. Typically, this is the user who created and submitted it 258 * @since 3.0.1 259 */ 260 public Workflow( final Engine engine, final String messageKey, final Principal owner ) { 261 m_attributes = new ConcurrentHashMap<>(); 262 m_currentStep = null; 263 m_history = new LinkedList<>(); 264 m_id = idsCounter.getAndIncrement(); 265 m_key = messageKey; 266 m_messageArgs = new ArrayList<>(); 267 m_owner = owner; 268 m_started = false; 269 m_state = CREATED; 270 WikiEventEmitter.fireWorkflowEvent( this, WorkflowEvent.CREATED, engine ); 271 } 272 273 /** 274 * Aborts the Workflow by setting the current Step's Outcome to {@link Outcome#STEP_ABORT}, and the Workflow's overall state to 275 * {@link #ABORTED}. It also appends the aborted Step into the workflow history, and sets the current step to <code>null</code>. 276 * If the Step is a Decision, it is removed from the DecisionQueue. This method can be called at any point in the lifecycle prior 277 * to completion, but it cannot be called twice. It finishes by calling the {@link #cleanup()} method to flush retained objects. 278 * If the Workflow had been previously aborted, this method throws an IllegalStateException. 279 */ 280 public final void abort( final Context context ) { 281 Synchronizer.synchronize(lock, () -> { 282 // Check corner cases: previous abort or completion 283 if( m_state == ABORTED ) { 284 throw new IllegalStateException( "The workflow has already been aborted." ); 285 } 286 if( m_state == COMPLETED ) { 287 throw new IllegalStateException( "The workflow has already completed." ); 288 } 289 290 if( m_currentStep != null ) { 291 if( m_currentStep instanceof Decision ) { 292 WikiEventEmitter.fireWorkflowEvent( m_currentStep, WorkflowEvent.DQ_REMOVAL, context ); 293 } 294 m_currentStep.setOutcome( Outcome.STEP_ABORT ); 295 m_history.addLast( m_currentStep ); 296 } 297 m_state = ABORTED; 298 WikiEventEmitter.fireWorkflowEvent( this, WorkflowEvent.ABORTED ); 299 cleanup(); 300 }); 301 } 302 303 /** 304 * Appends a message argument object to the array returned by {@link #getMessageArguments()}. The object <em>must</em> be an type 305 * used by the {@link java.text.MessageFormat}: String, Date, or Number (BigDecimal, BigInteger, Byte, Double, Float, Integer, Long, 306 * Short). If the object is not of type String, Number or Date, this method throws an IllegalArgumentException. 307 * 308 * @param obj the object to add 309 */ 310 public final void addMessageArgument( final Serializable obj ) { 311 if( obj instanceof String || obj instanceof Date || obj instanceof Number ) { 312 m_messageArgs.add( obj ); 313 return; 314 } 315 throw new IllegalArgumentException( "Message arguments must be of type String, Date or Number." ); 316 } 317 318 /** 319 * Returns the actor Principal responsible for the current Step. If there is 320 * no current Step, this method returns <code>null</code>. 321 * 322 * @return the current actor 323 */ 324 public final Principal getCurrentActor() { 325 return Synchronizer.synchronize(lock, () -> { 326 if( m_currentStep == null ) { 327 return null; 328 } 329 return m_currentStep.getActor(); 330 }); 331 } 332 333 /** 334 * Returns the workflow state: {@link #CREATED}, {@link #RUNNING}, {@link #WAITING}, {@link #COMPLETED} or {@link #ABORTED}. 335 * 336 * @return the workflow state 337 */ 338 public final int getCurrentState() 339 { 340 return m_state; 341 } 342 343 /** 344 * Returns the current Step, or <code>null</code> if the workflow has not started or already completed. 345 * 346 * @return the current step 347 */ 348 public final Step getCurrentStep() 349 { 350 return m_currentStep; 351 } 352 353 /** 354 * Retrieves a named Object associated with this Workflow. If the Workflow has completed or aborted, this method always returns 355 * <code>null</code>. 356 * 357 * @param attr the name of the attribute 358 * @return the value 359 */ 360 public final Object getAttribute( final String attr ) { 361 return m_attributes.get( attr ); 362 } 363 364 /** 365 * Retrieves workflow's attributes. 366 * 367 * @return workflow's attributes. 368 */ 369 public final Map< String, Serializable > getAttributes() { 370 return m_attributes; 371 } 372 373 /** 374 * The end time for this Workflow, expressed as a system time number. This value is equal to the end-time value returned by the final 375 * Step's {@link Step#getEndTime()} method, if the workflow has completed. Otherwise, this method returns {@link Step#TIME_NOT_SET}. 376 * 377 * @return the end time 378 */ 379 public final Date getEndTime() { 380 if( isCompleted() ) { 381 final Step last = m_history.getLast(); 382 if( last != null ) { 383 return last.getEndTime(); 384 } 385 } 386 return Step.TIME_NOT_SET; 387 } 388 389 /** 390 * Returns the unique identifier for this Workflow. If not set, this method returns ID_NOT_SET ({@value #ID_NOT_SET}). 391 * 392 * @return the unique identifier 393 */ 394 public final int getId() 395 { 396 return Synchronizer.synchronize(lock, () -> m_id); 397 } 398 399 /** 400 * <p> 401 * Returns an array of message arguments, used by {@link java.text.MessageFormat} to create localized messages. The first 402 * two array elements will always be these: 403 * </p> 404 * <ul> 405 * <li>String representing the name of the workflow owner (<em>i.e.</em>,{@link #getOwner()})</li> 406 * <li>String representing the name of the current actor (<em>i.e.</em>,{@link #getCurrentActor()}). 407 * If the current step is <code>null</code> because the workflow hasn't started or has already 408 * finished, the value of this argument will be a dash character (<code>-</code>)</li> 409 * </ul> 410 * <p> 411 * Workflow and Step subclasses are free to append items to this collection with {@link #addMessageArgument(Serializable)}. 412 * </p> 413 * 414 * @return the array of message arguments 415 */ 416 public final Serializable[] getMessageArguments() { 417 final List< Serializable > args = new ArrayList<>(); 418 args.add( m_owner.getName() ); 419 final Principal actor = getCurrentActor(); 420 args.add( actor == null ? "-" : actor.getName() ); 421 args.addAll( m_messageArgs ); 422 return args.toArray( new Serializable[0] ); 423 } 424 425 /** 426 * Returns an i18n message key for the name of this workflow; for example, 427 * <code>workflow.saveWikiPage</code>. 428 * 429 * @return the name 430 */ 431 public final String getMessageKey() 432 { 433 return m_key; 434 } 435 436 /** 437 * The owner Principal on whose behalf this Workflow is being executed; that is, the user who created the workflow. 438 * 439 * @return the name of the Principal who owns this workflow 440 */ 441 public final Principal getOwner() 442 { 443 return m_owner; 444 } 445 446 /** 447 * The start time for this Workflow, expressed as a system time number. This value is equal to the start-time value returned by the 448 * first Step's {@link Step#getStartTime()} method, if the workflow has started already. Otherwise, this method returns 449 * {@link Step#TIME_NOT_SET}. 450 * 451 * @return the start time 452 */ 453 public final Date getStartTime() 454 { 455 return isStarted() ? m_firstStep.getStartTime() : Step.TIME_NOT_SET; 456 } 457 458 /** 459 * Returns a Step history for this Workflow as a List, chronologically, from the first Step to the currently executing one. The first 460 * step is the first item in the array. If the Workflow has not started, this method returns a zero-length array. 461 * 462 * @return a List of Steps representing those that have executed, or are currently executing. 463 */ 464 public final List< Step > getHistory() 465 { 466 return Collections.unmodifiableList( m_history ); 467 } 468 469 /** 470 * Returns <code>true</code> if the workflow had been previously aborted. 471 * 472 * @return the result 473 */ 474 public final boolean isAborted() 475 { 476 return m_state == ABORTED; 477 } 478 479 /** 480 * Determines whether this Workflow is completed; that is, if it has no additional Steps to perform. If the last Step in the workflow is 481 * finished, this method will return <code>true</code>. 482 * 483 * @return <code>true</code> if the workflow has been started but has no more steps to perform; <code>false</code> if not. 484 */ 485 public final boolean isCompleted() { 486 return Synchronizer.synchronize(lock, () -> { 487 // If current step is null, then we're done 488 return m_started && m_state == COMPLETED; 489 }); 490 } 491 492 /** 493 * Determines whether this Workflow has started; that is, its {@link #start(Context)} method has been executed. 494 * 495 * @return <code>true</code> if the workflow has been started; <code>false</code> if not. 496 */ 497 public final boolean isStarted() 498 { 499 return m_started; 500 } 501 502 /** 503 * Convenience method that returns the predecessor of the current Step. This method simply examines the Workflow history and returns the 504 * second-to-last Step. 505 * 506 * @return the predecessor, or <code>null</code> if the first Step is currently executing 507 */ 508 public final Step getPreviousStep() 509 { 510 return previousStep( m_currentStep ); 511 } 512 513 /** 514 * Restarts the Workflow from the {@link #WAITING} state and puts it into the {@link #RUNNING} state again. If the Workflow had not 515 * previously been paused, this method throws an IllegalStateException. If any of the Steps in this Workflow throw a WikiException, 516 * the Workflow will abort and propagate the exception to callers. 517 * 518 * @param context current wiki context 519 * @throws WikiException if the current task's {@link Task#execute( Context )} method throws an exception 520 */ 521 public final void restart( final Context context ) throws WikiException { 522 Synchronizer.synchronize(lock, () -> { 523 if( m_state != WAITING ) { 524 throw new IllegalStateException( "Workflow is not paused; cannot restart." ); 525 } 526 WikiEventEmitter.fireWorkflowEvent( this, WorkflowEvent.STARTED ); 527 m_state = RUNNING; 528 WikiEventEmitter.fireWorkflowEvent( this, WorkflowEvent.RUNNING ); 529 530 // Process current step 531 try { 532 processCurrentStep( context ); 533 } catch( final WikiException e ) { 534 abort( context ); 535 throw e; 536 } 537 }); 538 } 539 540 /** 541 * Temporarily associates an object with this Workflow, as a named attribute, for the duration of workflow execution. The passed 542 * object can be anything required by an executing Step, although it <em>should</em> be serializable. Note that when the workflow 543 * completes or aborts, all attributes will be cleared. 544 * 545 * @param attr the attribute name 546 * @param obj the value 547 */ 548 public final void setAttribute( final String attr, final Serializable obj ) { 549 m_attributes.put( attr, obj ); 550 } 551 552 /** 553 * Sets the first Step for this Workflow, which will be executed immediately 554 * after the {@link #start( Context )} method executes. Note than the Step is not 555 * marked as the "current" step or added to the Workflow history until the 556 * {@link #start( Context )} method is called. 557 * 558 * @param step the first step for the workflow 559 */ 560 public final void setFirstStep( final Step step ) 561 { 562 Synchronizer.synchronize(lock, () -> { 563 m_firstStep = step; 564 }); 565 } 566 567 /** 568 * Sets the unique identifier for this Workflow. 569 * 570 * @param id the unique identifier 571 */ 572 public final void setId( final int id ) 573 { 574 Synchronizer.synchronize(lock, () -> { 575 this.m_id = id; 576 }); 577 } 578 579 /** 580 * Starts the Workflow and sets the state to {@link #RUNNING}. If the Workflow has already been started (or previously aborted), this 581 * method returns an {@linkplain IllegalStateException}. If any of the Steps in this Workflow throw a WikiException, the Workflow will 582 * abort and propagate the exception to callers. 583 * 584 * @param context current wiki context. 585 * @throws WikiException if the current Step's {@link Step#start()} method throws an exception of any kind 586 */ 587 public final void start( final Context context ) throws WikiException { 588 Synchronizer.synchronize(lock, () -> { 589 if( m_state == ABORTED ) { 590 throw new IllegalStateException( "Workflow cannot be started; it has already been aborted." ); 591 } 592 if( m_started ) { 593 throw new IllegalStateException( "Workflow has already started." ); 594 } 595 WikiEventEmitter.fireWorkflowEvent( this, WorkflowEvent.STARTED ); 596 m_started = true; 597 m_state = RUNNING; 598 599 WikiEventEmitter.fireWorkflowEvent( this, WorkflowEvent.RUNNING ); 600 // Mark the first step as the current one & add to history 601 m_currentStep = m_firstStep; 602 m_history.add( m_currentStep ); 603 604 // Process current step 605 try { 606 processCurrentStep( context ); 607 } catch( final WikiException e ) { 608 abort( context ); 609 throw e; 610 } 611 }); 612 } 613 614 /** 615 * Sets the Workflow in the {@link #WAITING} state. If the Workflow is not running or has already been paused, this method throws an 616 * IllegalStateException. Once paused, the Workflow can be un-paused by executing the {@link #restart(Context)} method. 617 */ 618 public final void waitstate() { 619 Synchronizer.synchronize(lock, () -> { 620 if ( m_state != RUNNING ) { 621 throw new IllegalStateException( "Workflow is not running; cannot pause." ); 622 } 623 m_state = WAITING; 624 WikiEventEmitter.fireWorkflowEvent( this, WorkflowEvent.WAITING ); 625 }); 626 } 627 628 /** 629 * Clears the attribute map and sets the current step field to <code>null</code>. 630 */ 631 protected void cleanup() { 632 m_currentStep = null; 633 m_attributes = null; 634 } 635 636 /** 637 * Protected helper method that changes the Workflow's state to {@link #COMPLETED} and sets the current Step to <code>null</code>. It 638 * calls the {@link #cleanup()} method to flush retained objects. This method will no-op if it has previously been called. 639 */ 640 protected final void complete() { 641 Synchronizer.synchronize(lock, () -> { 642 if( !isCompleted() ) { 643 m_state = COMPLETED; 644 WikiEventEmitter.fireWorkflowEvent( this, WorkflowEvent.COMPLETED ); 645 cleanup(); 646 } 647 }); 648 } 649 650 /** 651 * Protected method that returns the predecessor for a supplied Step. 652 * 653 * @param step the Step for which the predecessor is requested 654 * @return its predecessor, or <code>null</code> if the first Step was supplied. 655 */ 656 protected final Step previousStep( final Step step ) { 657 final int index = m_history.indexOf( step ); 658 return index < 1 ? null : m_history.get( index - 1 ); 659 } 660 661 /** 662 * Protected method that processes the current Step by calling {@link Step#execute( Context )}. If the <code>execute</code> throws an 663 * exception, this method will propagate the exception immediately to callers without aborting. 664 * 665 * @throws WikiException if the current Step's {@link Step#start()} method throws an exception of any kind 666 */ 667 protected final void processCurrentStep( final Context context ) throws WikiException { 668 while ( m_currentStep != null ) { 669 // Start and execute the current step 670 if( !m_currentStep.isStarted() ) { 671 m_currentStep.start(); 672 } 673 final Outcome result = m_currentStep.execute( context ); 674 if( Outcome.STEP_ABORT.equals( result ) ) { 675 abort( context ); 676 break; 677 } 678 679 if( !m_currentStep.isCompleted() ) { 680 m_currentStep.setOutcome( result ); 681 } 682 683 // Get the execution Outcome; if not complete, pause workflow and exit 684 final Outcome outcome = m_currentStep.getOutcome(); 685 if ( !outcome.isCompletion() ) { 686 waitstate(); 687 break; 688 } 689 690 // Get the next Step; if null, we're done 691 final Step nextStep = m_currentStep.getSuccessor( outcome ); 692 if ( nextStep == null ) { 693 complete(); 694 break; 695 } 696 697 // Add the next step to Workflow history, and mark as current 698 m_history.add( nextStep ); 699 m_currentStep = nextStep; 700 } 701 702 } 703}