View Javadoc
1   /**
2    * Licensed to the Apache Software Foundation (ASF) under one
3    * or more contributor license agreements. See the NOTICE file
4    * distributed with this work for additional information
5    * regarding copyright ownership. The ASF licenses this file
6    * to you under the Apache License, Version 2.0 (the
7    * "License"); you may not use this file except in compliance
8    * with the License. You may obtain a copy of the License at
9    *
10   * http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing,
13   * software distributed under the License is distributed on an
14   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15   * KIND, either express or implied. See the License for the
16   * specific language governing permissions and limitations
17   * under the License.
18   */
19  
20  package org.apache.wss4j.common.cache;
21  
22  import java.time.Duration;
23  import java.time.Instant;
24  import java.time.temporal.ChronoUnit;
25  import java.util.function.Supplier;
26  
27  import org.ehcache.expiry.ExpiryPolicy;
28  
29  /**
30   * A custom Expiry implementation for EhCache. It uses the supplied expiry which is part of the cache value.
31   * If it doesn't exist, it falls back to the default value (3600 seconds).
32   */
33  public class EHCacheExpiry implements ExpiryPolicy<String, EHCacheValue> {
34  
35      /**
36       * The default time to live in seconds (60 minutes)
37       */
38      public static final long DEFAULT_TTL = 3600L;
39  
40      /**
41       * The max time to live in seconds (12 hours)
42       */
43      public static final long MAX_TTL = DEFAULT_TTL * 12L;
44  
45  
46      @Override
47      public Duration getExpiryForCreation(String s, EHCacheValue ehCacheValue) {
48          Instant expiry = ehCacheValue.getExpiry();
49          Instant now = Instant.now();
50  
51          if (expiry == null || expiry.isBefore(now) || expiry.isAfter(now.plusSeconds(MAX_TTL))) {
52              return Duration.of(DEFAULT_TTL, ChronoUnit.SECONDS);
53          }
54  
55          return Duration.of(expiry.toEpochMilli() - now.toEpochMilli(), ChronoUnit.MILLIS);
56      }
57  
58      @Override
59      public Duration getExpiryForAccess(String s, Supplier<? extends EHCacheValue> supplier) {
60          return null;
61      }
62  
63      @Override
64      public Duration getExpiryForUpdate(String s, Supplier<? extends EHCacheValue> supplier, EHCacheValue ehCacheValue) {
65          return null;
66      }
67  
68  
69  }