001    /*
002     * Sonar, open source software quality management tool.
003     * Copyright (C) 2008-2011 SonarSource
004     * mailto:contact AT sonarsource DOT com
005     *
006     * Sonar is free software; you can redistribute it and/or
007     * modify it under the terms of the GNU Lesser General Public
008     * License as published by the Free Software Foundation; either
009     * version 3 of the License, or (at your option) any later version.
010     *
011     * Sonar is distributed in the hope that it will be useful,
012     * but WITHOUT ANY WARRANTY; without even the implied warranty of
013     * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
014     * Lesser General Public License for more details.
015     *
016     * You should have received a copy of the GNU Lesser General Public
017     * License along with Sonar; if not, write to the Free Software
018     * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02
019     */
020    package org.sonar.core.components;
021    
022    import com.google.common.collect.BiMap;
023    import com.google.common.collect.HashBiMap;
024    import com.google.common.collect.Maps;
025    import org.sonar.api.rules.Rule;
026    import org.sonar.jpa.session.DatabaseSessionFactory;
027    
028    import java.util.Map;
029    
030    public final class CacheRuleFinder extends DefaultRuleFinder {
031    
032      private BiMap<Integer, Rule> rulesById = HashBiMap.create();
033      private Map<String, Map<String, Rule>> rulesByKey = Maps.newHashMap();
034    
035      public CacheRuleFinder(DatabaseSessionFactory sessionFactory) {
036        super(sessionFactory);
037      }
038    
039      @Override
040      public Rule findById(int ruleId) {
041        Rule rule = rulesById.get(ruleId);
042        if (rule==null) {
043          rule = doFindById(ruleId);
044          addToCache(rule);
045        }
046        return rule;
047      }
048    
049      @Override
050      public Rule findByKey(String repositoryKey, String key) {
051        Map<String,Rule> repoRules = rulesByKey.get(repositoryKey);
052        Rule rule = null;
053        if (repoRules!=null) {
054          rule = repoRules.get(key);
055        }
056        if (rule == null) {
057          rule = doFindByKey(repositoryKey, key);
058          addToCache(rule);
059        }
060        return rule;
061      }
062    
063      private void addToCache(Rule rule) {
064        if (rule != null) {
065          rulesById.put(rule.getId(), rule);
066          Map<String, Rule> repoRules = rulesByKey.get(rule.getKey());
067          if (repoRules==null) {
068            repoRules = Maps.newHashMap();
069            rulesByKey.put(rule.getRepositoryKey(), repoRules);
070          }
071          repoRules.put(rule.getKey(), rule);
072        }
073      }
074    }