001: /*
002: * Copyright 2005-2006 The Kuali Foundation.
003: *
004: * Licensed under the Educational Community License, Version 1.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: * http://www.opensource.org/licenses/ecl1.php
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: */
016: package org.kuali.core.util.properties;
017:
018: import java.io.IOException;
019: import java.io.InputStream;
020: import java.net.URL;
021: import java.util.Properties;
022:
023: import org.apache.commons.lang.StringUtils;
024: import org.apache.commons.logging.Log;
025: import org.apache.commons.logging.LogFactory;
026: import org.kuali.core.exceptions.PropertiesException;
027:
028: /**
029: * This class is used to obtain properties from a properites file.
030: *
031: *
032: */
033: public class FilePropertySource implements PropertySource {
034: private static Log log = LogFactory
035: .getLog(FilePropertySource.class);
036:
037: private String fileName;
038:
039: /**
040: * Set source fileName.
041: *
042: * @param fileName
043: */
044: public void setFileName(String fileName) {
045: this .fileName = fileName;
046: }
047:
048: /**
049: * @return source fileName
050: */
051: public String getFileName() {
052: return this .fileName;
053: }
054:
055: /**
056: * Attempts to load properties from a properties file which has the current fileName and is located on the classpath.
057: *
058: * @see org.kuali.core.util.properties.PropertySource#loadProperties()
059: * @throws IllegalStateException if the fileName is null or empty
060: */
061: public Properties loadProperties() {
062: if (StringUtils.isBlank(getFileName())) {
063: throw new IllegalStateException("invalid (blank) fileName");
064: }
065:
066: Properties properties = new Properties();
067:
068: ClassLoader loader = Thread.currentThread()
069: .getContextClassLoader();
070: URL url = loader.getResource(getFileName());
071: if (url == null) {
072: throw new PropertiesException(
073: "unable to locate properties file '"
074: + getFileName() + "'");
075: }
076:
077: InputStream in = null;
078:
079: try {
080: in = url.openStream();
081: properties.load(in);
082: } catch (IOException e) {
083: throw new PropertiesException(
084: "error loading from properties file '"
085: + getFileName() + "'", e);
086: } finally {
087: if (in != null) {
088: try {
089: in.close();
090: } catch (IOException e) {
091: log.error("caught exception closing InputStream: "
092: + e);
093: }
094:
095: }
096: }
097:
098: return properties;
099: }
100: }
|