001 /*
002 * SonarQube, open source software quality management tool.
003 * Copyright (C) 2008-2014 SonarSource
004 * mailto:contact AT sonarsource DOT com
005 *
006 * SonarQube 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 * SonarQube 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 License
017 * along with this program; if not, write to the Free Software Foundation,
018 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
019 */
020 package org.sonar.batch.tasks;
021
022 import com.google.common.collect.ImmutableSortedMap;
023 import com.google.common.collect.Maps;
024 import org.sonar.api.task.Task;
025 import org.sonar.api.task.TaskComponent;
026 import org.sonar.api.task.TaskDefinition;
027 import org.sonar.api.utils.SonarException;
028
029 import java.util.Collection;
030 import java.util.Map;
031 import java.util.SortedMap;
032
033 public class Tasks implements TaskComponent {
034
035 private final SortedMap<String, TaskDefinition> byKey;
036
037 public Tasks(TaskDefinition[] definitions) {
038 SortedMap<String, TaskDefinition> map = Maps.newTreeMap();
039 for (TaskDefinition definition : definitions) {
040 if (map.containsKey(definition.key())) {
041 throw new SonarException("Task '" + definition.key() + "' is declared twice");
042 }
043 map.put(definition.key(), definition);
044 }
045 this.byKey = ImmutableSortedMap.copyOf(map);
046 }
047
048 public TaskDefinition definition(String taskKey) {
049 return byKey.get(taskKey);
050 }
051
052 public Collection<TaskDefinition> definitions() {
053 return byKey.values();
054 }
055
056 /**
057 * Perform validation of task definitions
058 */
059 public void start() {
060 checkDuplicatedClasses();
061 }
062
063 private void checkDuplicatedClasses() {
064 Map<Class<? extends Task>, TaskDefinition> byClass = Maps.newHashMap();
065 for (TaskDefinition def : definitions()) {
066 TaskDefinition other = byClass.get(def.taskClass());
067 if (other == null) {
068 byClass.put(def.taskClass(), def);
069 } else {
070 throw new SonarException("Task '" + def.taskClass().getName() + "' is defined twice: first by '" + other.key() + "' and then by '" + def.key() + "'");
071 }
072 }
073 }
074 }