Formatting applied to aaa-authn bundle
[aaa.git] / aaa-authn / src / main / java / org / opendaylight / aaa / AuthenticationManager.java
1 /*
2  * Copyright (c) 2014 Hewlett-Packard Development Company, L.P. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8 package org.opendaylight.aaa;
9
10 import java.util.Dictionary;
11 import java.util.Hashtable;
12 import org.opendaylight.aaa.api.Authentication;
13 import org.opendaylight.aaa.api.AuthenticationService;
14 import org.osgi.service.cm.ConfigurationException;
15 import org.osgi.service.cm.ManagedService;
16
17 /**
18  * An {@link InheritableThreadLocal}-based {@link AuthenticationService}.
19  *
20  * @author liemmn
21  */
22 public class AuthenticationManager implements AuthenticationService, ManagedService {
23     private static final String AUTH_ENABLED_ERR = "Error setting authEnabled";
24
25     static final String AUTH_ENABLED = "authEnabled";
26     static final Dictionary<String, String> defaults = new Hashtable<>();
27     static {
28         defaults.put(AUTH_ENABLED, Boolean.FALSE.toString());
29     }
30
31     // In non-Karaf environments, authEnabled is set to false by default
32     private static volatile boolean authEnabled = false;
33
34     private final static AuthenticationManager am = new AuthenticationManager();
35     private final ThreadLocal<Authentication> auth = new InheritableThreadLocal<>();
36
37     private AuthenticationManager() {
38     }
39
40     static AuthenticationManager instance() {
41         return am;
42     }
43
44     @Override
45     public Authentication get() {
46         return auth.get();
47     }
48
49     @Override
50     public void set(Authentication a) {
51         auth.set(a);
52     }
53
54     @Override
55     public void clear() {
56         auth.remove();
57     }
58
59     @Override
60     public boolean isAuthEnabled() {
61         return authEnabled;
62     }
63
64     @Override
65     public void updated(Dictionary<String, ?> properties) throws ConfigurationException {
66         if (properties == null) {
67             return;
68         }
69
70         String propertyValue = (String) properties.get(AUTH_ENABLED);
71         boolean isTrueString = Boolean.parseBoolean(propertyValue);
72         if (!isTrueString && !"false".equalsIgnoreCase(propertyValue)) {
73             throw new ConfigurationException(AUTH_ENABLED, AUTH_ENABLED_ERR);
74         }
75         authEnabled = isTrueString;
76     }
77 }