001/*
002 * Copyright 2006-2007 the original author or authors.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *      https://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016package org.springframework.batch.support;
017
018import org.springframework.beans.factory.InitializingBean;
019import org.springframework.util.Assert;
020
021/**
022 * Helper class that sets up a System property with a default value. A System
023 * property is created with the specified key name, and default value (i.e. if
024 * the property already exists it is not changed).
025 * 
026 * @author Dave Syer
027 * 
028 */
029public class SystemPropertyInitializer implements InitializingBean {
030
031        /**
032         * Name of system property used by default.
033         */
034        public static final String ENVIRONMENT = "org.springframework.batch.support.SystemPropertyInitializer.ENVIRONMENT";
035
036        private String keyName = ENVIRONMENT;
037
038        private String defaultValue;
039
040        /**
041         * Set the key name for the System property that is created. Defaults to
042         * {@link #ENVIRONMENT}.
043         * 
044         * @param keyName the key name to set
045         */
046        public void setKeyName(String keyName) {
047                this.keyName = keyName;
048        }
049
050        /**
051         * Mandatory property specifying the default value of the System property.
052         * 
053         * @param defaultValue the default value to set
054         */
055        public void setDefaultValue(String defaultValue) {
056                this.defaultValue = defaultValue;
057        }
058
059        /**
060         * Sets the System property with the provided name and default value.
061         * 
062         * @see InitializingBean#afterPropertiesSet()
063         */
064    @Override
065        public void afterPropertiesSet() throws Exception {
066                Assert.state(defaultValue != null || System.getProperty(keyName) != null,
067                                "Either a default value must be specified or the value should already be set for System property: "
068                                                + keyName);
069                System.setProperty(keyName, System.getProperty(keyName, defaultValue));
070        }
071
072}