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  package org.apache.maven.plugins.enforcer.internal;
20  
21  import javax.annotation.PreDestroy;
22  import javax.inject.Named;
23  import javax.inject.Singleton;
24  
25  import java.util.ArrayList;
26  import java.util.HashMap;
27  import java.util.List;
28  import java.util.Map;
29  
30  import org.apache.maven.enforcer.rule.api.AbstractEnforcerRule;
31  import org.slf4j.Logger;
32  import org.slf4j.LoggerFactory;
33  
34  /**
35   * Service for manage rules cache storage.
36   *
37   * @author Slawomir Jaranowski
38   * @since 3.2.0
39   */
40  @Named
41  @Singleton
42  public class EnforcerRuleCache {
43  
44      private final Logger logger = LoggerFactory.getLogger(EnforcerRuleCache.class);
45  
46      private final Map<Class<? extends AbstractEnforcerRule>, List<String>> cache = new HashMap<>();
47  
48      public boolean isCached(AbstractEnforcerRule rule) {
49  
50          String cacheId = rule.getCacheId();
51  
52          if (cacheId == null) {
53              return false;
54          }
55  
56          Class<? extends AbstractEnforcerRule> ruleClass = rule.getClass();
57          logger.debug("Check cache for {} with id {}", ruleClass, cacheId);
58  
59          synchronized (this) {
60              List<String> cacheIdList = cache.computeIfAbsent(ruleClass, k -> new ArrayList<>());
61              if (cacheIdList.contains(cacheId)) {
62                  logger.debug("Already cached {} with id {}", ruleClass, cacheId);
63                  return true;
64              }
65              logger.debug("Add cache {} with id {}", ruleClass, cacheId);
66              cacheIdList.add(cacheId);
67          }
68  
69          return false;
70      }
71  
72      @PreDestroy
73      public void cleanup() {
74          synchronized (this) {
75              cache.clear();
76          }
77      }
78  }