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.Session;
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.Collection;
034import java.util.LinkedList;
035import java.util.concurrent.atomic.AtomicInteger;
036import java.util.concurrent.locks.ReentrantLock;
037
038
039/**
040 * Keeps a queue of pending Decisions that need to be acted on by named Principals.
041 *
042 * @since 2.5
043 */
044public class DecisionQueue implements Serializable {
045
046    private static final long serialVersionUID = -7172912793410302533L;
047
048    private final LinkedList< Decision > m_queue = new LinkedList<>();
049
050    private final AtomicInteger next = new AtomicInteger( 1_000 );
051
052    /**
053     * A lock used to ensure thread safety when accessing shared resources.
054     * This lock provides more flexibility and capabilities than the intrinsic locking mechanism,
055     * such as the ability to attempt to acquire a lock with a timeout, or to interrupt a thread
056     * waiting to acquire a lock.
057     *
058     * @see java.util.concurrent.locks.ReentrantLock
059     */
060    private transient ReentrantLock lock = new ReentrantLock();
061
062    private void readObject( final ObjectInputStream in ) throws IOException, ClassNotFoundException {
063        in.defaultReadObject();
064        // Locks are not part of the serialized form, so data written by earlier releases has none either.
065        lock = new ReentrantLock();
066    }
067
068    /** Constructs a new DecisionQueue. */
069    public DecisionQueue() {
070    }
071
072    /**
073     * Adds a Decision to the DecisionQueue; also sets the Decision's unique identifier.
074     *
075     * @param decision the Decision to add
076     */
077    protected void add( final Decision decision ) {
078        Synchronizer.synchronize(lock, () -> {
079            m_queue.addLast( decision );
080            decision.setId( next.getAndIncrement() );
081        });
082    }
083
084    /**
085     * Protected method that returns all pending Decisions in the queue, in  order of submission. If no Decisions are pending, this
086     * method returns a zero-length array.
087     *
088     * @return the pending decisions 
089     */
090    protected Decision[] decisions() {
091        return m_queue.toArray( new Decision[0] );
092    }
093
094    /**
095     * Protected method that removes a Decision from the queue.
096     *
097     * @param decision the decision to remove
098     */
099    protected void remove( final Decision decision ) {
100        Synchronizer.synchronize(lock, () -> {
101            m_queue.remove( decision );
102        });
103    }
104
105    /**
106     * Returns a Collection representing the current Decisions that pertain to a users's Session. The Decisions are obtained by iterating
107     * through the Session's Principals and selecting those Decisions whose {@link Decision#getActor()} value match. If the session
108     * is not authenticated, this method returns an empty Collection.
109     *
110     * @param session the wiki session
111     * @return the collection of Decisions, which may be empty
112     */
113    public Collection<Decision> getActorDecisions( final Session session ) {
114        final ArrayList< Decision > decisions = new ArrayList<>();
115        if( session.isAuthenticated() ) {
116            final Principal[] principals = session.getPrincipals();
117            final Principal[] rolePrincipals = session.getRoles();
118            for( final Decision decision : m_queue ) {
119                // Iterate through the Principal set
120                for( final Principal principal : principals ) {
121                    if( principal.equals( decision.getActor() ) ) {
122                        decisions.add( decision );
123                    }
124                }
125                // Iterate through the Role set
126                for( final Principal principal : rolePrincipals ) {
127                    if( principal.equals( decision.getActor() ) ) {
128                        decisions.add( decision );
129                    }
130                }
131            }
132        }
133        return decisions;
134    }
135
136    /**
137     * Attempts to complete a Decision by calling {@link Decision#decide(Outcome, Context)}. This will cause the Step immediately following the
138     * Decision (if any) to start. If the decision completes successfully, this method also removes the completed decision from the queue.
139     *
140     * @param decision the Decision for which the Outcome will be supplied
141     * @param outcome the Outcome of the Decision
142     * @throws WikiException if the succeeding Step cannot start for any reason
143     */
144    public void decide( final Decision decision, final Outcome outcome, final Context context ) throws WikiException {
145        decision.decide( outcome, context );
146        if ( decision.isCompleted() ) {
147            remove( decision );
148        }
149
150        WikiEventEmitter.fireWorkflowEvent( decision, WorkflowEvent.DQ_DECIDE );
151    }
152
153    /**
154     * Reassigns the owner of the Decision to a new owner. Under the covers, this method calls {@link Decision#reassign(Principal)}.
155     *
156     * @param decision the Decision to reassign
157     * @param owner the new owner
158     * @throws WikiException never
159     */
160    public void reassign( final Decision decision, final Principal owner ) throws WikiException {
161        Synchronizer.synchronize(lock, () -> {
162            if( decision.isReassignable() ) {
163                decision.reassign( owner );
164
165                WikiEventEmitter.fireWorkflowEvent( decision, WorkflowEvent.DQ_REASSIGN );
166                return;
167            }
168            throw new IllegalStateException( "Reassignments not allowed for this decision." );
169        });
170    }
171
172}