1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.acegisecurity.context;
17
18 import org.springframework.util.Assert;
19
20
21 /***
22 * Associates a given {@link SecurityContext} with the current execution
23 * thread and any new threads the current execution thread may spawn.
24 *
25 * <p>
26 * To guarantee that {@link #getContext()} never returns <code>null</code>, this
27 * class defaults to returning <code>SecurityContextImpl</code> if no
28 * <code>SecurityContext</code> has ever been associated with the current
29 * thread of execution. Despite this behaviour, in general another class will
30 * select the concrete <code>SecurityContext</code> implementation to use and
31 * expressly set an instance of that implementation against the
32 * <code>SecurityContextHolder</code>.
33 * </p>
34 *
35 * @author Ben Alex
36 * @version $Id: SecurityContextHolder.java,v 1.4 2005/11/17 00:55:49 benalex Exp $
37 *
38 * @see java.lang.ThreadLocal
39 * @see org.acegisecurity.context.HttpSessionContextIntegrationFilter
40 */
41 public class SecurityContextHolder {
42
43
44 private static ThreadLocal contextHolder = new ThreadLocal();
45
46
47
48 /***
49 * Associates a new <code>SecurityContext</code> with the current thread of
50 * execution.
51 *
52 * @param context the new <code>SecurityContext</code> (may not be
53 * <code>null</code>)
54 */
55 public static void setContext(SecurityContext context) {
56 Assert.notNull(context,
57 "Only non-null SecurityContext instances are permitted");
58 contextHolder.set(context);
59 }
60
61 /***
62 * Obtains the <code>SecurityContext</code> associated with the current
63 * thread of execution. If no <code>SecurityContext</code> has been
64 * associated with the current thread of execution, a new instance of
65 * {@link SecurityContextImpl} is associated with the current thread and
66 * then returned.
67 *
68 * @return the current <code>SecurityContext</code> (guaranteed to never be
69 * <code>null</code>)
70 */
71 public static SecurityContext getContext() {
72 if (contextHolder.get() == null) {
73 contextHolder.set(new SecurityContextImpl());
74 }
75
76 return (SecurityContext) contextHolder.get();
77 }
78 }