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 net.sumaris.server.config.SumarisServerConfiguration;
29  import org.apache.commons.lang3.StringUtils;
30  import org.springframework.stereotype.Component;
31  
32  import java.util.Objects;
33  import java.util.concurrent.TimeUnit;
34  
35  /**
36   * Created by blavenie on 06/01/16.
37   */
38  public class ValidationExpiredCache {
39  
40      private final Cache<String, String> cache;
41  
42      public ValidationExpiredCache(final int lifeTimeInSeconds) {
43          this.cache = CacheBuilder.newBuilder()
44                  .expireAfterWrite(Math.max(lifeTimeInSeconds, 60 /* min value */), TimeUnit.SECONDS)
45                  .build();
46      }
47  
48      public boolean contains(String data) {
49          Preconditions.checkArgument(StringUtils.isNotBlank(data));
50          String storedData = cache.getIfPresent(data);
51          return Objects.equals(storedData, data);
52      }
53  
54      public void remove(String data) {
55          cache.invalidate(data);
56      }
57  
58      public void add(String data) {
59          cache.put(data, data);
60      }
61  
62      public void clean() {
63          this.cache.invalidateAll();
64      }
65  }