Drop explicit jetty-servlets dependency
[aaa.git] / aaa-shiro / impl / src / main / java / org / opendaylight / aaa / impl / datastore / h2 / H2TokenStore.java
1 /*
2  * Copyright (c) 2016 Inocybe Technologies. 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.impl.datastore.h2;
9
10 import net.sf.ehcache.Cache;
11 import net.sf.ehcache.CacheManager;
12 import net.sf.ehcache.Element;
13 import net.sf.ehcache.config.CacheConfiguration;
14 import org.opendaylight.aaa.api.Authentication;
15 import org.opendaylight.aaa.api.TokenStore;
16 import org.slf4j.Logger;
17 import org.slf4j.LoggerFactory;
18
19 public class H2TokenStore implements AutoCloseable, TokenStore {
20
21     private static final Logger LOG = LoggerFactory.getLogger(H2TokenStore.class);
22
23     private static final String TOKEN_CACHE_MANAGER = "org.opendaylight.aaa";
24     private static final String TOKEN_CACHE = "tokens";
25
26     private int maxCachedTokensInMemory = 10000;
27     private int maxCachedTokensOnDisk = 100000;
28     private final Cache tokens;
29
30     public H2TokenStore(long secondsToLive, long secondsToIdle) {
31         CacheManager cm = CacheManager.newInstance();
32         tokens = new Cache(new CacheConfiguration(TOKEN_CACHE, maxCachedTokensInMemory)
33                                     .maxEntriesLocalDisk(maxCachedTokensOnDisk)
34                                     .timeToLiveSeconds(secondsToLive)
35                                     .timeToIdleSeconds(secondsToIdle));
36         cm.addCache(tokens);
37         cm.setName(TOKEN_CACHE_MANAGER);
38         LOG.info("Initialized token store with default cache config");
39     }
40
41     @Override
42     public void close() throws Exception {
43         LOG.info("Shutting down token store...");
44         CacheManager.getInstance().shutdown();
45     }
46
47     @Override
48     public Authentication get(String token) {
49         Element elem = tokens.get(token);
50         return (Authentication) (elem != null ? elem.getObjectValue() : null);
51     }
52
53     @Override
54     public void put(String token, Authentication auth) {
55         tokens.put(new Element(token, auth));
56     }
57
58     @Override
59     public boolean delete(String token) {
60         return tokens.remove(token);
61     }
62
63     @Override
64     public long tokenExpiration() {
65         return tokens.getCacheConfiguration().getTimeToLiveSeconds();
66     }
67 }