001    /*
002     * Sonar, open source software quality management tool.
003     * Copyright (C) 2009 SonarSource SA
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.squid.indexer;
021    
022    import java.util.Collection;
023    import java.util.HashSet;
024    import java.util.Map;
025    import java.util.Observable;
026    import java.util.Observer;
027    import java.util.Set;
028    import java.util.TreeMap;
029    
030    import org.sonar.squid.api.SourceCode;
031    
032    public class SquidIndex implements Observer {
033    
034      Map<String, SourceCode> index = new TreeMap<String, SourceCode>();
035    
036      public Collection<SourceCode> search(Query... query) {
037        Set<SourceCode> result = new HashSet<SourceCode>();
038        for (SourceCode unit : index.values()) {
039          if (isSquidUnitMatchQueries(unit, query)) {
040            result.add(unit);
041          }
042        }
043        return result;
044      }
045    
046      private boolean isSquidUnitMatchQueries(SourceCode unit, Query... query) {
047        boolean match;
048        for (int i = 0; i < query.length; i++) {
049          match = query[i].match(unit);
050          if (!match) {
051            return false;
052          }
053        }
054        return true;
055      }
056    
057      public SourceCode search(String key) {
058        return index.get(key);
059      }
060    
061      public void index(SourceCode project) {
062        project.addObserver(this);
063        index.put(project.getKey(), project);
064      }
065    
066      public void update(Observable parentResource, Object resourceAdded) {
067        if (!(resourceAdded instanceof SourceCode)) {
068          throw new IllegalStateException("ResourceIndexer expected a Resource object but get a : " + resourceAdded.getClass().getName());
069        }
070        SourceCode resource = (SourceCode) resourceAdded;
071        resource.addObserver(this);
072        index.put(resource.getKey(), resource);
073      }
074    }