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 */
020package org.sonar.process;
021
022import org.apache.commons.io.Charsets;
023import org.apache.commons.io.FileUtils;
024import org.apache.commons.io.IOUtils;
025import org.apache.commons.lang.text.StrSubstitutor;
026
027import java.io.File;
028import java.io.FileInputStream;
029import java.io.InputStreamReader;
030import java.io.Reader;
031import java.util.Enumeration;
032import java.util.Map;
033import java.util.Properties;
034
035public final class ConfigurationUtils {
036
037  private ConfigurationUtils() {
038    // Utility class
039  }
040
041  public static Properties interpolateVariables(Properties properties, Map<String, String> variables) {
042    Properties result = new Properties();
043    Enumeration keys = properties.keys();
044    while (keys.hasMoreElements()) {
045      String key = (String) keys.nextElement();
046      String value = (String) properties.get(key);
047      String interpolatedValue = StrSubstitutor.replace(value, variables, "${env:", "}");
048      result.setProperty(key, interpolatedValue);
049    }
050    return result;
051  }
052
053  static Props loadPropsFromCommandLineArgs(String[] args) {
054    if (args.length != 1) {
055      throw new IllegalArgumentException("Only a single command-line argument is accepted " +
056        "(absolute path to configuration file)");
057    }
058
059    File propertyFile = new File(args[0]);
060    Properties properties = new Properties();
061    Reader reader = null;
062    try {
063      reader = new InputStreamReader(new FileInputStream(propertyFile), Charsets.UTF_8);
064      properties.load(reader);
065    } catch (Exception e) {
066      throw new IllegalStateException("Could not read properties from file: " + args[0], e);
067    } finally {
068      IOUtils.closeQuietly(reader);
069      FileUtils.deleteQuietly(propertyFile);
070    }
071    return new Props(properties);
072  }
073}