2 * Copyright (c) 2016 Inocybe Technologies. and others. All rights reserved.
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
8 package org.opendaylight.aaa.datastore.h2;
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 net.sf.ehcache.config.Configuration;
15 import net.sf.ehcache.config.ConfigurationFactory;
16 import org.opendaylight.aaa.api.Authentication;
17 import org.opendaylight.aaa.api.TokenStore;
18 import org.slf4j.Logger;
19 import org.slf4j.LoggerFactory;
21 public class H2TokenStore implements AutoCloseable, TokenStore {
23 private static final Logger LOG = LoggerFactory.getLogger(H2TokenStore.class);
25 private static final String TOKEN_CACHE_MANAGER = "org.opendaylight.aaa";
26 private static final String TOKEN_CACHE = "tokens";
28 private int maxCachedTokensInMemory = 10000;
29 private int maxCachedTokensOnDisk = 100000;
30 private final Cache tokens;
32 public H2TokenStore(long secondsToLive, long secondsToIdle) {
33 // When we restart, the cache manager and token cache are already there
34 CacheManager cm = CacheManager.getCacheManager(TOKEN_CACHE_MANAGER);
36 Configuration configuration = ConfigurationFactory.parseConfiguration();
37 configuration.setName(TOKEN_CACHE_MANAGER);
38 cm = CacheManager.newInstance(configuration);
40 Cache existingCache = cm.getCache(TOKEN_CACHE);
41 if (existingCache != null) {
42 tokens = existingCache;
44 tokens = new Cache(new CacheConfiguration(TOKEN_CACHE, maxCachedTokensInMemory)
45 .maxEntriesLocalDisk(maxCachedTokensOnDisk)
46 .timeToLiveSeconds(secondsToLive)
47 .timeToIdleSeconds(secondsToIdle));
50 LOG.info("Initialized token store with default cache config");
55 LOG.info("Shutting down token store...");
56 CacheManager.getInstance().shutdown();
60 public Authentication get(String token) {
61 Element elem = tokens.get(token);
62 return (Authentication) (elem != null ? elem.getObjectValue() : null);
66 public void put(String token, Authentication auth) {
67 tokens.put(new Element(token, auth));
71 public boolean delete(String token) {
72 return tokens.remove(token);
76 public long tokenExpiration() {
77 return tokens.getCacheConfiguration().getTimeToLiveSeconds();