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.shiro.subject.support;
020
021import org.apache.shiro.subject.Subject;
022import org.apache.shiro.util.ThreadState;
023
024/**
025 * A {@code SubjectRunnable} ensures that a target/delegate {@link Runnable Runnable} will execute such that any
026 * call to {@code SecurityUtils.}{@link org.apache.shiro.SecurityUtils#getSubject() getSubject()} during the
027 * {@code Runnable}'s execution will return the associated {@code Subject} instance.  The {@code SubjectRunnable}
028 * instance can be run on any thread (the current thread or asynchronously on another thread) and the
029 * {@code SecurityUtils.getSubject()} call will still work properly.  This implementation also guarantees that Shiro's
030 * thread state will be identical before and after execution to ensure threads remain clean in any thread-pooled
031 * environment.
032 * <p/>
033 * When instances of this class {@link Runnable#run() run()}, the following occurs:
034 * <ol>
035 * <li>The Subject and any of its associated thread state is first bound to the thread that executes the
036 * {@code Runnable}.</li>
037 * <li>The delegate/target {@code Runnable} is {@link #doRun(Runnable) run}</li>
038 * <li>Any previous thread state that might have existed before the {@code Subject} was bound is fully restored</li>
039 * </ol>
040 * <p/>
041 *
042 * <h3>Usage</h3>
043 *
044 * This is typically considered a support class and is not often directly referenced.  Most people prefer to use
045 * the {@code Subject.}{@link Subject#execute(Runnable) execute} or
046 * {@code Subject.}{@link Subject#associateWith(Runnable) associateWith} methods, which transparently perform the
047 * necessary association logic.
048 * <p/>
049 * An even more convenient alternative is to use a
050 * {@link org.apache.shiro.concurrent.SubjectAwareExecutor SubjectAwareExecutor}, which transparently uses
051 * instances of this class but does not require referencing Shiro's API at all.
052 *
053 * @see Subject#associateWith(Runnable)
054 * @see org.apache.shiro.concurrent.SubjectAwareExecutor SubjectAwareExecutor
055 * @since 1.0
056 */
057public class SubjectRunnable implements Runnable {
058
059    protected final ThreadState threadState;
060    private final Runnable runnable;
061
062    /**
063     * Creates a new {@code SubjectRunnable} that, when executed, will execute the target {@code delegate}, but
064     * guarantees that it will run associated with the specified {@code Subject}.
065     *
066     * @param subject  the Subject to associate with the delegate's execution.
067     * @param delegate the runnable to run.
068     */
069    public SubjectRunnable(Subject subject, Runnable delegate) {
070        this(new SubjectThreadState(subject), delegate);
071    }
072
073    /**
074     * Creates a new {@code SubjectRunnable} that, when executed, will perform thread state
075     * {@link ThreadState#bind binding} and guaranteed {@link ThreadState#restore restoration} before and after the
076     * {@link Runnable Runnable}'s execution, respectively.
077     *
078     * @param threadState the thread state to bind and unbind before and after the runnable's execution.
079     * @param delegate    the delegate {@code Runnable} to execute when this instance is {@link #run() run()}.
080     * @throws IllegalArgumentException if either the {@code ThreadState} or {@link Runnable} arguments are {@code null}.
081     */
082    protected SubjectRunnable(ThreadState threadState, Runnable delegate) throws IllegalArgumentException {
083        if (threadState == null) {
084            throw new IllegalArgumentException("ThreadState argument cannot be null.");
085        }
086        this.threadState = threadState;
087        if (delegate == null) {
088            throw new IllegalArgumentException("Runnable argument cannot be null.");
089        }
090        this.runnable = delegate;
091    }
092
093    /**
094     * {@link ThreadState#bind Bind}s the Subject thread state, executes the target {@code Runnable} and then guarantees
095     * the previous thread state's {@link ThreadState#restore restoration}:
096     * <pre>
097     * try {
098     *     threadState.{@link ThreadState#bind bind()};
099     *     {@link #doRun doRun}(targetRunnable);
100     * } finally {
101     *     threadState.{@link ThreadState#restore restore()}
102     * }
103     * </pre>
104     */
105    public void run() {
106        try {
107            threadState.bind();
108            doRun(this.runnable);
109        } finally {
110            threadState.restore();
111        }
112    }
113
114    /**
115     * Simply calls the target {@link Runnable Runnable}'s {@link Runnable#run run()} method.
116     *
117     * @param runnable the target runnable to run.
118     */
119    protected void doRun(Runnable runnable) {
120        runnable.run();
121    }
122}