01: /*
02: * Copyright 2004-2006 the original author or authors.
03: *
04: * Licensed under the Apache License, Version 2.0 (the "License");
05: * you may not use this file except in compliance with the License.
06: * You may obtain a copy of the License at
07: *
08: * http://www.apache.org/licenses/LICENSE-2.0
09: *
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: package org.compass.core.config.builder;
18:
19: import java.io.*;
20: import java.net.URL;
21:
22: import org.apache.commons.logging.Log;
23: import org.apache.commons.logging.LogFactory;
24: import org.compass.core.config.CompassConfiguration;
25: import org.compass.core.config.CompassEnvironment;
26: import org.compass.core.config.ConfigurationException;
27:
28: /**
29: * @author kimchy
30: */
31: public abstract class AbstractInputStreamConfigurationBuilder implements
32: ConfigurationBuilder {
33:
34: protected Log log = LogFactory.getLog(getClass());
35:
36: public void configure(String resource, CompassConfiguration config)
37: throws ConfigurationException {
38: InputStream stream = CompassEnvironment.class
39: .getResourceAsStream(resource);
40: if (stream == null) {
41: stream = Thread.currentThread().getContextClassLoader()
42: .getResourceAsStream(resource);
43: }
44: if (stream == null) {
45: throw new ConfigurationException("Resource [" + resource
46: + "] not found in class path");
47: }
48: configure(stream, resource, config);
49: }
50:
51: public void configure(URL url, CompassConfiguration config)
52: throws ConfigurationException {
53: try {
54: configure(url.openStream(), url.toExternalForm(), config);
55: } catch (IOException e) {
56: throw new ConfigurationException("Failed to open url ["
57: + url.toExternalForm() + "]", e);
58: }
59: }
60:
61: public void configure(File file, CompassConfiguration config)
62: throws ConfigurationException {
63: try {
64: configure(new FileInputStream(file),
65: file.getAbsolutePath(), config);
66: } catch (FileNotFoundException fnfe) {
67: throw new ConfigurationException(
68: "Could not find configuration file ["
69: + file.getAbsolutePath() + "]", fnfe);
70: }
71: }
72:
73: private void configure(InputStream is, String resourceName,
74: CompassConfiguration config) {
75: try {
76: doConfigure(is, resourceName, config);
77: } finally {
78: try {
79: is.close();
80: } catch (IOException e) {
81: log.warn("Failed to close input stream for ["
82: + resourceName + "]", e);
83: }
84: }
85: }
86:
87: protected abstract void doConfigure(InputStream is,
88: String resourceName, CompassConfiguration config)
89: throws ConfigurationException;
90: }
|