KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > beehive > netui > util > config > ConfigUtil


1 /*
2  * Copyright 2004 The Apache Software Foundation.
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  * $Header:$
17  */

18 package org.apache.beehive.netui.util.config;
19
20 import org.apache.beehive.netui.util.internal.InternalStringBuilder;
21
22 import java.io.InputStream JavaDoc;
23 import java.io.IOException JavaDoc;
24 import java.util.ArrayList JavaDoc;
25
26 import org.apache.beehive.netui.util.config.bean.NetuiConfigDocument;
27 import org.apache.beehive.netui.util.config.bean.NetuiConfigDocument.NetuiConfig;
28 import org.apache.beehive.netui.util.logging.Logger;
29
30 import org.apache.xmlbeans.XmlException;
31 import org.apache.xmlbeans.XmlOptions;
32 import org.apache.xmlbeans.XmlError;
33
34 /**
35  * <p/>
36  * Utility class for reading properties from the NetUI configuration file.
37  * <br/>
38  * <br/>
39  * The webapp runtime is read from the InputStream passed to the {@link #init(InputStream)} method.
40  * The configuration should be initialized with this method and a valid {@link java.io.InputStream}
41  * before the first time the {@link #getConfig()} method is called. If the configuration
42  * has not been initialized, {@link #getConfig()} will initialize a bare bones runtime
43  * configuration. Depending on the web application, this default configuration
44  * may lead to runtime errors.
45  * <br/>
46  * <br/>
47  * </p>
48  */

49 public class ConfigUtil {
50
51     // @todo: need to change NetuiConfigDocument.NetuiConfig to NetUIConfig
52
// @todo: need to provide a read-only implementation so that users can't edit the config file on the fly
53

54     private static final Logger LOGGER = Logger.getInstance(ConfigUtil.class);
55
56     private static final String JavaDoc DEFAULT_CONFIG = "org/apache/beehive/netui/util/config/beehive-netui-config-default.xml";
57
58     private static NetuiConfigDocument _config = null;
59
60     /* do not construct */
61     protected ConfigUtil() {
62     }
63
64     /**
65      * <p/>
66      * Initialize the NetUI configuration data.
67      * <br/>
68      * <br/>
69      * This method can be called exactly once in a J2EE web application. The
70      * {@link java.io.InputStream} parameter should reference a
71      * netui-config.xml file. If an error occurs loading the configuration
72      * file, a {@link ConfigInitializationException} will be thrown.
73      * </p>
74      *
75      * @param is the {@link java.io.InputStream} from which to read the configuration file
76      * @throws ConfigInitializationException thrown when an error occurs loading the configuration file
77      * or when the configuration is reinitialized.
78      */

79     public static final void init(InputStream JavaDoc is)
80         throws ConfigInitializationException {
81         if(_config != null)
82             throw new ConfigInitializationException("Config initialization already completed; unable to reload the NetUI config file.");
83
84         internalInit(is);
85     }
86     
87     public static final boolean isInit() {
88         return (_config != null);
89     }
90
91     /**
92      * Internal method used to re-initialize the static class member that holds the
93      * ConfigDocument. Note, this method does <b>no</b> checks to ensure that an
94      * existing document is being overwritten. The behavior of ConfigUtil clients
95      * is undefined if their initial configuration is re-loaded.
96      *
97      * @param is The {@link java.io.InputStream} that contains the config document to load
98      * @throws ConfigInitializationException thrown when an error occurs loading the
99      * configuration file.
100      */

101     protected static final void internalInit(InputStream JavaDoc is)
102         throws ConfigInitializationException {
103
104         // when initialized with a null InputStream, revert to using a default, barebones config file
105
if(is == null) {
106             ClassLoader JavaDoc cl = Thread.currentThread().getContextClassLoader();
107             is = cl.getResourceAsStream(DEFAULT_CONFIG);
108
109             if(is == null)
110                 throw new ConfigInitializationException("The NetUI runtime could not find the default config file. " +
111                     "The webapp may not function properly.");
112
113             if(LOGGER.isInfoEnabled())
114                 LOGGER.info("Loading the default NetUI config file. The runtime will be configured " +
115                     "with a set of minimum parameters.");
116         }
117
118         if(_config == null) {
119             try {
120                 XmlOptions loadOptions = new XmlOptions();
121                 loadOptions.setLoadLineNumbers();
122                 _config = NetuiConfigDocument.Factory.parse(is, loadOptions);
123             }
124                 // XmlException | IOException
125
catch(Exception JavaDoc ex) {
126                 assert ex instanceof XmlException || ex instanceof IOException JavaDoc;
127
128                 throw new ConfigInitializationException("Unable load the NetUI config file. Cause: " + ex, ex);
129             }
130         }
131
132         assert _config != null;
133
134         // Validate the document.
135
XmlOptions validateOptions = new XmlOptions();
136         ArrayList JavaDoc errorList = new ArrayList JavaDoc();
137         validateOptions.setErrorListener(errorList);
138         boolean isValid = _config.validate(validateOptions);
139
140         // Throw an exception if the XML is invalid.
141
if(!isValid) {
142             InternalStringBuilder msg = new InternalStringBuilder("Invalid NetUI configuration file.");
143
144             for(int i = 0; i < errorList.size(); i++) {
145                 XmlError error = (XmlError)errorList.get(i);
146                 msg.append("\n line ");
147                 msg.append(error.getLine());
148                 msg.append(": ");
149                 msg.append(error.getMessage());
150                 msg.append(" (");
151                 msg.append(error.getCursorLocation().toString());
152                 msg.append(")");
153             }
154
155             throw new ConfigInitializationException(msg.toString());
156         }
157     }
158
159     /**
160      * Get the NetUI configuration object.
161      *
162      * @return a configuration bean that contains data
163      * parsed from the netui-config.xml file.
164      */

165     public static NetuiConfig getConfig() {
166         if(_config != null) {
167             return _config.getNetuiConfig();
168         }
169         /*
170           If the config file wasn't initialized, attempt to initialize a configuration
171           from the default config file contained in the utility JAR.
172          */

173         else {
174             /*
175               This hopefully never happens and would only occur if the default config file isn't found in the util JAR.
176              */

177             if(LOGGER.isErrorEnabled())
178                 LOGGER.error("An error occurred parsing the default config file. " +
179                     "The NetUI runtime is not properly configured.");
180
181             throw new IllegalStateException JavaDoc("The NetUI runtime could not find the default config file. The webapp may not function properly.");
182         }
183     }
184 }
185
Popular Tags