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.exceptions.WikiException;
023import org.apache.wiki.event.WikiEventEmitter;
024import org.apache.wiki.event.WorkflowEvent;
025import org.apache.wiki.util.Synchronizer;
026
027import java.io.IOException;
028import java.io.ObjectInputStream;
029import java.io.Serializable;
030import java.security.Principal;
031import java.util.ArrayList;
032import java.util.Collections;
033import java.util.List;
034import java.util.Map;
035import java.util.concurrent.locks.ReentrantLock;
036
037
038/**
039 * <p>
040 * AbstractStep subclass that asks an actor Principal to choose an Outcome on behalf of an owner (also a Principal). The actor
041 * "makes the decision" by calling the {@link #decide(Outcome, Context)} method. When this method is called, it will set the Decision's Outcome to
042 * the one supplied. If the parent Workflow is in the {@link Workflow#WAITING} state, it will be re-started. Any checked WikiExceptions
043 * thrown by the workflow after re-start will be re-thrown to callers.
044 * </p>
045 * <p>
046 * When a Decision completes, its {@link #isCompleted()} method returns <code>true</code>. It also tells its parent WorkflowManager to
047 * remove it from the list of pending tasks by calling {@link DecisionQueue#remove(Decision)}.
048 * </p>
049 * <p>
050 * To enable actors to choose an appropriate Outcome, Decisions can store arbitrary key-value pairs called "facts." These facts can be
051 * presented by the user interface to show details the actor needs to know about. Facts are added by calling classes to the Decision,
052 * in order of expected presentation, by the {@link #addFact(Fact)} method. They can be retrieved, in order, via {@link #getFacts()}.
053 * </p>
054 *
055 * @since 2.5
056 */
057public abstract class Decision extends AbstractStep {
058
059    private static final long serialVersionUID = -6835601038263238062L;
060
061    private Principal m_actor;
062
063    private int m_id;
064
065    private final Outcome m_defaultOutcome;
066
067    private final List<Fact> m_facts;
068
069    /**
070     * A lock used to ensure thread safety when accessing shared resources.
071     * This lock provides more flexibility and capabilities than the intrinsic locking mechanism,
072     * such as the ability to attempt to acquire a lock with a timeout, or to interrupt a thread
073     * waiting to acquire a lock.
074     *
075     * @see java.util.concurrent.locks.ReentrantLock
076     */
077    private transient ReentrantLock lock = new ReentrantLock();
078
079    private void readObject( final ObjectInputStream in ) throws IOException, ClassNotFoundException {
080        in.defaultReadObject();
081        // Locks are not part of the serialized form, so data written by earlier releases has none either.
082        lock = new ReentrantLock();
083    }
084
085    /**
086     * Constructs a new Decision for a required "actor" Principal, having a default Outcome.
087     *
088     * @param workflowId the parent workflow id to set
089     * @param workflowContext the parent workflow context to set
090     * @param messageKey the i18n message key that represents the message the actor will see
091     * @param actor the Principal (<em>e.g.</em>, a WikiPrincipal, Role, GroupPrincipal) who is required to select an appropriate Outcome
092     * @param defaultOutcome the Outcome that the user interface will recommend as the default choice
093     */
094    public Decision( final int workflowId, final Map< String, Serializable > workflowContext, final String messageKey, final Principal actor, final Outcome defaultOutcome ) {
095        super( workflowId, workflowContext, messageKey );
096        m_actor = actor;
097        m_defaultOutcome = defaultOutcome;
098        m_facts = new ArrayList<>();
099        addSuccessor( defaultOutcome, null );
100    }
101
102    /**
103     * Appends a Fact to the list of Facts associated with this Decision.
104     * 
105     * @param fact the new fact to add
106     */
107    public final void addFact( final Fact fact )
108    {
109        m_facts.add( fact );
110    }
111
112    /**
113     * <p>
114     * Sets this Decision's outcome, and restarts the parent Workflow if it is
115     * in the {@link Workflow#WAITING} state and this Decision is its currently
116     * active Step. Any checked WikiExceptions thrown by the workflow after
117     * re-start will be re-thrown to callers.
118     * </p>
119     * <p>
120     * This method cannot be invoked if the Decision is not the current Workflow
121     * step; all other invocations will throw an IllegalStateException. If the
122     * Outcome supplied to this method is one one of the Outcomes returned by
123     * {@link #getAvailableOutcomes()}, an IllegalArgumentException will be
124     * thrown.
125     * </p>
126     * 
127     * @param outcome the Outcome of the Decision
128     * @param context wiki context of the Decision
129     * @throws WikiException if the act of restarting the Workflow throws an exception
130     */
131    public void decide( final Outcome outcome, final Context context ) throws WikiException {
132        super.setOutcome( outcome );
133        WikiEventEmitter.fireWorkflowEvent( this, WorkflowEvent.DQ_REMOVAL, context );
134    }
135
136    /**
137     * Default implementation that always returns {@link Outcome#STEP_CONTINUE} if the current Outcome isn't a completion (which will be
138     * true if the {@link #decide(Outcome, Context)} method hasn't been executed yet. This method will also add the Decision to the associated
139     * DecisionQueue.
140     * 
141     * @return the Outcome of the execution
142     * @throws WikiException never
143     */
144    @Override
145    public Outcome execute(final Context context ) throws WikiException {
146        if( getOutcome().isCompletion() ) {
147            return getOutcome();
148        }
149
150        // Put decision in the DecisionQueue
151        WikiEventEmitter.fireWorkflowEvent( this, WorkflowEvent.DQ_ADDITION );
152
153        // Indicate we are waiting for user input
154        return Outcome.STEP_CONTINUE;
155    }
156
157    /**
158     * {@inheritDoc}
159     */
160    @Override
161    public final Principal getActor() {
162        return m_actor;
163    }
164
165    /**
166     * Returns the default or suggested outcome, which must be one of those returned by {@link #getAvailableOutcomes()}. This method is
167     * guaranteed to return a non-<code>null</code> Outcome.
168     * 
169     * @return the default outcome.
170     */
171    public Outcome getDefaultOutcome() {
172        return m_defaultOutcome;
173    }
174
175    /**
176     * Returns the Facts associated with this Decision, in the order in which they were added.
177     * 
178     * @return the list of Facts
179     */
180    public final List< Fact > getFacts() {
181        return Collections.unmodifiableList( m_facts );
182    }
183
184    /**
185     * Returns the unique identifier for this Decision. Normally, this ID is programmatically assigned when the Decision is added to the
186     * DecisionQueue.
187     * 
188     * @return the identifier
189     */
190    public final int getId() {
191        return m_id;
192    }
193
194    /**
195     * Returns <code>true</code> if the Decision can be reassigned to another actor. This implementation always returns <code>true</code>.
196     *
197     * @return the result
198     */
199    public boolean isReassignable() {
200        return true;
201    }
202
203    /**
204     * Reassigns the Decision to a new actor (that is, provide an outcome). If the Decision is not reassignable, this method throws an
205     * IllegalArgumentException.
206     * 
207     * @param actor the actor to reassign the Decision to
208     */
209    public final void reassign( final Principal actor ) {
210        Synchronizer.synchronize(lock, () -> {
211            if( isReassignable() ) {
212                m_actor = actor;
213            } else {
214                throw new IllegalArgumentException( "Decision cannot be reassigned." );
215            }
216        });
217    }
218
219    /**
220     * Sets the unique identfier for this Decision.
221     * 
222     * @param id the identifier
223     */
224    public final void setId( final int id ) {
225        m_id = id;
226    }
227
228}