1 /* *************************************************************************** 2 * Copyright (c) 2012 Brabenetz Harald, Austria. 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 * 16 *****************************************************************************/ 17 18 package org.settings4j.helper.configuration; 19 20 import org.apache.commons.configuration.Configuration; 21 import org.settings4j.connector.AbstractPropertyConnector; 22 23 24 /** 25 * Adapter to use an <a href="http://commons.apache.org/proper/commons-configuration/">Apache Commons Configuration</a> 26 * as Settings4j connector. 27 * <p> 28 * <h3>Example Usage</h3><br /> 29 * Create a {@link org.apache.commons.configuration.XMLConfiguration} instance and add it to the Settings4j instance as 30 * Connector. 31 * 32 * <pre> 33 * String connectorName = "myCommonsConfigXmlConfigConnector"; 34 * Connector connector = Settings4j.getSettings().getConnector(connectorName); 35 * if (connector == null) { 36 * XMLConfiguration configuration = new XMLConfiguration(new File(.....)); 37 * 38 * connector = new ConfigurationToConnectorAdapter(connectorName, configuration); 39 * 40 * // add the connecter after the last SystemPropertyConnector or add it as first connector. 41 * Settings4j.getSettings().addConnector(connector, // 42 * ConnectorPositions.firstValid(// 43 * ConnectorPositions.afterLast(SystemPropertyConnector.class), // 44 * ConnectorPositions.atFirst() // if no SystemPropertyConnector is configured. 45 * )// 46 * ); 47 * } 48 * </pre> 49 * 50 * @author brabenetz 51 */ 52 public class ConfigurationToConnectorAdapter extends AbstractPropertyConnector { 53 54 private final Configuration configuration; 55 56 /** 57 * @param name The unique name of this connector. 58 * @param configuration The apache commons configuration instance to wrap and use as Settings4j connector. 59 */ 60 public ConfigurationToConnectorAdapter(final String name, final Configuration configuration) { 61 super(); 62 this.configuration = configuration; 63 this.setName(name); 64 } 65 66 @Override 67 protected String getProperty(final String key, final String defaultValue) { 68 return configuration.getString(key, defaultValue); 69 } 70 71 public Configuration getConfiguration() { 72 return configuration; 73 } 74 75 }