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