Home | History | Annotate | Download | only in defaultprovider
      1 /**
      2  * Copyright (C) 2010 the original author or authors.
      3  * See the notice.md file distributed with this work for additional
      4  * information regarding copyright ownership.
      5  *
      6  * Licensed under the Apache License, Version 2.0 (the "License");
      7  * you may not use this file except in compliance with the License.
      8  * You may obtain a copy of the License at
      9  *
     10  *     http://www.apache.org/licenses/LICENSE-2.0
     11  *
     12  * Unless required by applicable law or agreed to in writing, software
     13  * distributed under the License is distributed on an "AS IS" BASIS,
     14  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     15  * See the License for the specific language governing permissions and
     16  * limitations under the License.
     17  */
     18 
     19 package com.beust.jcommander.defaultprovider;
     20 
     21 import com.beust.jcommander.IDefaultProvider;
     22 import com.beust.jcommander.ParameterException;
     23 
     24 import java.io.IOException;
     25 import java.net.URL;
     26 import java.util.Properties;
     27 
     28 /**
     29  * A default provider that reads its default values from a property file.
     30  *
     31  * @author cbeust
     32  */
     33 public class PropertyFileDefaultProvider implements IDefaultProvider {
     34   public static final String DEFAULT_FILE_NAME = "jcommander.properties";
     35   private Properties m_properties;
     36 
     37   public PropertyFileDefaultProvider() {
     38     init(DEFAULT_FILE_NAME);
     39   }
     40 
     41   public PropertyFileDefaultProvider(String fileName) {
     42     init(fileName);
     43   }
     44 
     45   private void init(String fileName) {
     46     try {
     47       m_properties = new Properties();
     48       URL url = ClassLoader.getSystemResource(fileName);
     49       if (url != null) {
     50         m_properties.load(url.openStream());
     51       } else {
     52         throw new ParameterException("Could not find property file: " + fileName
     53             + " on the class path");
     54       }
     55     }
     56     catch (IOException e) {
     57       throw new ParameterException("Could not open property file: " + fileName);
     58     }
     59   }
     60 
     61   public String getDefaultValueFor(String optionName) {
     62     int index = 0;
     63     while (index < optionName.length() && ! Character.isLetterOrDigit(optionName.charAt(index))) {
     64       index++;
     65     }
     66     String key = optionName.substring(index);
     67     return m_properties.getProperty(key);
     68   }
     69 
     70 }
     71