View Javadoc
1   /* 
2    * Licensed under the Apache License, Version 2.0 (the "License");
3    * you may not use this file except in compliance with the License.
4    * You may obtain a copy of the License at
5    *
6    * http://www.apache.org/licenses/LICENSE-2.0
7    *
8    * Unless required by applicable law or agreed to in writing, software
9    * distributed under the License is distributed on an "AS IS" BASIS,
10   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11   * See the License for the specific language governing permissions and
12   * limitations under the License.
13   *
14   */
15  
16  package org.esigate;
17  
18  import java.io.Serializable;
19  
20  import org.esigate.api.Session;
21  import org.esigate.http.IncomingRequest;
22  
23  /**
24   * User context that can be used in the master application to define the user id. This context will be transmitted to
25   * the provider applications.<br>
26   * There is one instance of user context associated with each session.
27   * 
28   * @author Francois-Xavier Bonnet
29   * @author Nicolas Richeton
30   * 
31   */
32  public class UserContext {
33      private static final String USER_KEY = "user";
34      private final IncomingRequest httpRequest;
35      private final String key;
36  
37      public UserContext(IncomingRequest httpRequest, String key) {
38          this.httpRequest = httpRequest;
39          this.key = UserContext.class.getName() + "#" + key;
40      }
41  
42      private String prefixAttributeName(String name) {
43          return key + "#" + name;
44      }
45  
46      public Object getAttribute(String name) {
47          Session session = httpRequest.getSession();
48          if (session == null) {
49              return null;
50          }
51          return session.getAttribute(prefixAttributeName(name));
52      }
53  
54      public void setAttribute(String name, Serializable value) {
55          httpRequest.getSession().setAttribute(prefixAttributeName(name), value);
56      }
57  
58      public String getUser() {
59          return (String) getAttribute(USER_KEY);
60      }
61  
62      public void setUser(String user) {
63          setAttribute(USER_KEY, user);
64      }
65  
66      /*
67       * @see java.lang.Object#toString()
68       */
69      @Override
70      public String toString() {
71          return "User=" + getUser();
72      }
73  
74      /**
75       * Returns the key under which the user name is to be stored in the session for a given provider.
76       * 
77       * @param providerName
78       *            The name of the provider
79       * @return The session key
80       */
81      public static String getUserSessionKey(String providerName) {
82          return UserContext.class.getName() + "#" + providerName + "#" + USER_KEY;
83      }
84  }