View Javadoc
1   package net.sumaris.server.http.security;
2   
3   /*
4    * #%L
5    * duniter4j :: UI Wicket
6    * %%
7    * Copyright (C) 2014 - 2016 EIS
8    * %%
9    * This program is free software: you can redistribute it and/or modify
10   * it under the terms of the GNU General Public License as
11   * published by the Free Software Foundation, either version 3 of the 
12   * License, or (at your option) any later version.
13   * 
14   * This program is distributed in the hope that it will be useful,
15   * but WITHOUT ANY WARRANTY; without even the implied warranty of
16   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17   * GNU General Public License for more details.
18   * 
19   * You should have received a copy of the GNU General Public 
20   * License along with this program.  If not, see
21   * <http://www.gnu.org/licenses/gpl-3.0.html>.
22   * #L%
23   */
24  
25  import com.google.common.base.Preconditions;
26  import com.google.common.cache.Cache;
27  import com.google.common.cache.CacheBuilder;
28  import org.apache.commons.lang3.StringUtils;
29  
30  import java.util.concurrent.TimeUnit;
31  
32  /**
33   * Expiring cache URI_2_CLASS
34   *
35   * Created by lpecquot on 03/12/18.
36   */
37  public class ValidationExpiredCacheMap<T> {
38  
39      private final Cache<String, T> cache;
40  
41      public ValidationExpiredCacheMap(final int lifeTimeInSeconds) {
42          this.cache = CacheBuilder.newBuilder()
43                  .expireAfterWrite(Math.max(lifeTimeInSeconds, 60 /* min value */), TimeUnit.SECONDS)
44                  .build();
45      }
46  
47      public boolean contains(String key) {
48          return StringUtils.isNotBlank(key) && get(key) != null;
49      }
50  
51      public T get(String key) {
52          Preconditions.checkArgument(StringUtils.isNotBlank(key));
53          return cache.getIfPresent(key);
54      }
55  
56      public void remove(String key) {
57          cache.invalidate(key);
58      }
59  
60      public void add(String key, T data) {
61          cache.put(key, data);
62      }
63  
64      public void clean() {
65          this.cache.invalidateAll();
66      }
67  }