001    /*
002     * Sonar, open source software quality management tool.
003     * Copyright (C) 2008-2012 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    
021    package org.sonar.squid.indexer;
022    
023    import java.util.Collection;
024    import java.util.HashSet;
025    import java.util.Map;
026    import java.util.Set;
027    import java.util.TreeMap;
028    
029    import org.sonar.squid.api.Query;
030    import org.sonar.squid.api.SourceCode;
031    import org.sonar.squid.api.SourceCodeIndexer;
032    import org.sonar.squid.api.SourceCodeSearchEngine;
033    
034    public class SquidIndex implements SourceCodeIndexer, SourceCodeSearchEngine {
035    
036      private Map<String, SourceCode> index = new TreeMap<String, SourceCode>();
037    
038      public Collection<SourceCode> search(Query... query) {
039        Set<SourceCode> result = new HashSet<SourceCode>();
040        for (SourceCode unit : index.values()) {
041          if (isSquidUnitMatchQueries(unit, query)) {
042            result.add(unit);
043          }
044        }
045        return result;
046      }
047    
048      private boolean isSquidUnitMatchQueries(SourceCode unit, Query... queries) {
049        boolean match;
050        for (Query query : queries) {
051          match = query.match(unit);
052          if (!match) {
053            return false;
054          }
055        }
056        return true;
057      }
058    
059      public SourceCode search(String key) {
060        return index.get(key);
061      }
062    
063      public void index(SourceCode sourceCode) {
064        sourceCode.setSourceCodeIndexer(this);
065        index.put(sourceCode.getKey(), sourceCode);
066      }
067    }