001/*
002 * Licensed to the Apache Software Foundation (ASF) under one
003 * or more contributor license agreements.  See the NOTICE file
004 * distributed with this work for additional information
005 * regarding copyright ownership.  The ASF licenses this file
006 * to you under the Apache License, Version 2.0 (the
007 * "License"); you may not use this file except in compliance
008 * with the License.  You may obtain a copy of the License at
009 *
010 *   http://www.apache.org/licenses/LICENSE-2.0
011 *
012 * Unless required by applicable law or agreed to in writing,
013 * software distributed under the License is distributed on an
014 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
015 * KIND, either express or implied.  See the License for the
016 * specific language governing permissions and limitations
017 * under the License.
018 */
019package org.apache.maven.plugins.enforcer.internal;
020
021import javax.annotation.PreDestroy;
022import javax.inject.Named;
023import javax.inject.Singleton;
024
025import java.util.ArrayList;
026import java.util.HashMap;
027import java.util.List;
028import java.util.Map;
029
030import org.apache.maven.enforcer.rule.api.AbstractEnforcerRule;
031import org.slf4j.Logger;
032import org.slf4j.LoggerFactory;
033
034/**
035 * Service for manage rules cache storage.
036 *
037 * @author Slawomir Jaranowski
038 * @since 3.2.0
039 */
040@Named
041@Singleton
042public class EnforcerRuleCache {
043
044    private final Logger logger = LoggerFactory.getLogger(EnforcerRuleCache.class);
045
046    private final Map<Class<? extends AbstractEnforcerRule>, List<String>> cache = new HashMap<>();
047
048    public boolean isCached(AbstractEnforcerRule rule) {
049
050        String cacheId = rule.getCacheId();
051
052        if (cacheId == null) {
053            return false;
054        }
055
056        Class<? extends AbstractEnforcerRule> ruleClass = rule.getClass();
057        logger.debug("Check cache for {} with id {}", ruleClass, cacheId);
058
059        synchronized (this) {
060            List<String> cacheIdList = cache.computeIfAbsent(ruleClass, k -> new ArrayList<>());
061            if (cacheIdList.contains(cacheId)) {
062                logger.debug("Already cached {} with id {}", ruleClass, cacheId);
063                return true;
064            }
065            logger.debug("Add cache {} with id {}", ruleClass, cacheId);
066            cacheIdList.add(cacheId);
067        }
068
069        return false;
070    }
071
072    @PreDestroy
073    public void cleanup() {
074        synchronized (this) {
075            cache.clear();
076        }
077    }
078}