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.utils;
021
022import java.io.IOException;
023import java.net.URL;
024import java.util.ArrayList;
025import java.util.Enumeration;
026import java.util.List;
027import java.util.jar.Attributes;
028import java.util.jar.Manifest;
029
030/**
031 * @since 2.2
032 */
033public final class ManifestUtils {
034
035  private ManifestUtils() {
036  }
037
038  /**
039   * Search for a property in all the manifests found in the classloader
040   *
041   * @return the values, an empty list if the property is not found.
042   */
043  public static List<String> getPropertyValues(ClassLoader classloader, String key) {
044    List<String> values = new ArrayList<>();
045    try {
046      Enumeration<URL> resources = classloader.getResources("META-INF/MANIFEST.MF");
047      while (resources.hasMoreElements()) {
048        Manifest manifest = new Manifest(resources.nextElement().openStream());
049        Attributes attributes = manifest.getMainAttributes();
050        String value = attributes.getValue(key);
051        if (value != null) {
052          values.add(value);
053        }
054      }
055    } catch (IOException e) {
056      throw new SonarException("Fail to load manifests from classloader: " + classloader, e);
057    }
058    return values;
059  }
060}