001/*
002 * SonarQube
003 * Copyright (C) 2009-2017 SonarSource SA
004 * mailto:info AT sonarsource DOT com
005 *
006 * This program 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 * This program 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 */
020package org.sonar.api.batch.bootstrap;
021
022import org.sonar.api.batch.ScannerSide;
023
024import java.util.ArrayList;
025import java.util.List;
026
027/**
028 * Mutable project definitions that can be modified by {@link ProjectBuilder} extensions.
029 * @since 2.9
030 */
031@ScannerSide
032public class ProjectReactor implements ProjectKey {
033
034  private ProjectDefinition root;
035
036  public ProjectReactor(ProjectDefinition root) {
037    if (root.getParent() != null) {
038      throw new IllegalArgumentException("Not a root project: " + root);
039    }
040    this.root = root;
041  }
042
043  public List<ProjectDefinition> getProjects() {
044    return collectProjects(root, new ArrayList<ProjectDefinition>());
045  }
046
047  /**
048   * Populates list of projects from hierarchy.
049   */
050  private static List<ProjectDefinition> collectProjects(ProjectDefinition def, List<ProjectDefinition> collected) {
051    collected.add(def);
052    for (ProjectDefinition child : def.getSubProjects()) {
053      collectProjects(child, collected);
054    }
055    return collected;
056  }
057
058  public ProjectDefinition getRoot() {
059    return root;
060  }
061
062  public ProjectDefinition getProject(String key) {
063    for (ProjectDefinition p : getProjects()) {
064      if (key.equals(p.getKey())) {
065        return p;
066      }
067    }
068    return null;
069  }
070
071  @Override
072  public String get() {
073    if (root != null) {
074      return root.getKeyWithBranch();
075    }
076    return null;
077  }
078}