001 /* 002 * (c) 2010 ThoughtWorks Ltd 003 * All rights reserved. 004 * 005 * The software in this package is published under the terms of the BSD 006 * style license a copy of which has been included with this distribution in 007 * the LICENSE.txt file. 008 * 009 * Created on 10-04-2010. 010 */ 011 package com.thoughtworks.proxy.toys.privilege; 012 013 import java.security.AccessControlContext; 014 import java.security.PrivilegedActionException; 015 import java.security.PrivilegedExceptionAction; 016 017 import javax.security.auth.Subject; 018 019 020 /** 021 * Execution of a {@link PrivilegedExceptionAction} with a {@link Subject}. 022 * 023 * @author Jörg Schaible 024 * @since 1.0 025 */ 026 public class SubjectExecutor implements ActionExecutor { 027 private final AccessControlContext context; 028 private final Subject subject; 029 030 /** 031 * Construct a SubjectExecutor that runs a {@link PrivilegedExceptionAction} with 032 * the {@link Subject#doAs(Subject, PrivilegedExceptionAction)} method. 033 * 034 * @param subject the subject used to run the methods 035 * @since 1.0 036 */ 037 public SubjectExecutor(Subject subject) { 038 this(subject, null); 039 } 040 041 /** 042 * Construct a SubjectExecutor that runs a {@link PrivilegedExceptionAction} with 043 * the {@link Subject#doAsPrivileged(Subject, PrivilegedExceptionAction, AccessControlContext)} method. 044 * 045 * @param subject the subject used to run the methods 046 * @param context the {@link AccessControlContext} defining privileges for the subject 047 * @since 1.0 048 */ 049 public SubjectExecutor(Subject subject, AccessControlContext context) { 050 this.subject = subject; 051 this.context = context; 052 } 053 054 public Object execute(PrivilegedExceptionAction<Object> action) 055 throws PrivilegedActionException { 056 if (context == null) { 057 return Subject.doAs(subject, action); 058 } else { 059 return Subject.doAsPrivileged(subject, action, context); 060 } 061 } 062 }