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