KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > openejb > alt > config > ConfigUtils


1 /**
2  * Redistribution and use of this software and associated documentation
3  * ("Software"), with or without modification, are permitted provided
4  * that the following conditions are met:
5  *
6  * 1. Redistributions of source code must retain copyright
7  * statements and notices. Redistributions must also contain a
8  * copy of this document.
9  *
10  * 2. Redistributions in binary form must reproduce the
11  * above copyright notice, this list of conditions and the
12  * following disclaimer in the documentation and/or other
13  * materials provided with the distribution.
14  *
15  * 3. The name "OpenEJB" must not be used to endorse or promote
16  * products derived from this Software without prior written
17  * permission of The OpenEJB Group. For written permission,
18  * please contact dev@openejb.org.
19  *
20  * 4. Products derived from this Software may not be called "OpenEJB"
21  * nor may "OpenEJB" appear in their names without prior written
22  * permission of The OpenEJB Group. OpenEJB is a registered
23  * trademark of The OpenEJB Group.
24  *
25  * 5. Due credit should be given to the OpenEJB Project
26  * (http://www.openejb.org/).
27  *
28  * THIS SOFTWARE IS PROVIDED BY THE OPENEJB GROUP AND CONTRIBUTORS
29  * ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT
30  * NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
31  * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
32  * THE OPENEJB GROUP OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
33  * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
34  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
35  * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
36  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
37  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
38  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
39  * OF THE POSSIBILITY OF SUCH DAMAGE.
40  *
41  * Copyright 2001 (C) The OpenEJB Group. All Rights Reserved.
42  *
43  * $Id: ConfigUtils.java 2487 2006-02-22 22:05:03Z dblevins $
44  */

45 package org.openejb.alt.config;
46
47 import org.exolab.castor.xml.MarshalException;
48 import org.exolab.castor.xml.ValidationException;
49 import org.openejb.OpenEJBException;
50 import org.openejb.alt.config.sys.Deployments;
51 import org.openejb.alt.config.sys.Openejb;
52 import org.openejb.loader.SystemInstance;
53 import org.openejb.util.Logger;
54 import org.openejb.util.Messages;
55
56 import java.io.File JavaDoc;
57 import java.io.FileNotFoundException JavaDoc;
58 import java.io.FileOutputStream JavaDoc;
59 import java.io.FileReader JavaDoc;
60 import java.io.FileWriter JavaDoc;
61 import java.io.IOException JavaDoc;
62 import java.io.InputStream JavaDoc;
63 import java.io.OutputStream JavaDoc;
64 import java.io.Reader JavaDoc;
65 import java.io.Writer JavaDoc;
66 import java.net.URL JavaDoc;
67 import java.net.UnknownHostException JavaDoc;
68 import java.util.Enumeration JavaDoc;
69 import java.util.Properties JavaDoc;
70
71 /**
72  * Utility methods for reading and writing config files
73  *
74  * @author <a HREF="mailto:david.blevins@visi.com">David Blevins</a>
75  */

76 public class ConfigUtils {
77
78     public static Messages messages = new Messages("org.openejb.util.resources");
79     public static Logger logger = Logger.getInstance("OpenEJB", "org.openejb.util.resources");
80
81     public static Openejb readConfig() throws OpenEJBException {
82         return readConfig(searchForConfiguration());
83     }
84
85     public static Openejb readConfig(String JavaDoc confFile) throws OpenEJBException {
86         File JavaDoc file = new File JavaDoc(confFile);
87         return (Openejb) Unmarshaller.unmarshal(Openejb.class, file.getName(), file.getParent());
88     }
89     /*
90      * TODO: Use the java.net.URL instead of java.io.File so configs
91      * and jars can be located remotely in the network
92      */

93     public static Openejb _readConfig(String JavaDoc confFile) throws OpenEJBException {
94         Openejb obj = null;
95         Reader JavaDoc reader = null;
96         try {
97             reader = new FileReader JavaDoc(confFile);
98             org.exolab.castor.xml.Unmarshaller unmarshaller = new org.exolab.castor.xml.Unmarshaller(Openejb.class);
99             unmarshaller.setWhitespacePreserve(true);
100             obj = (Openejb) unmarshaller.unmarshal(reader);
101         } catch (FileNotFoundException JavaDoc e) {
102             throw new OpenEJBException(messages.format("conf.1900", confFile, e.getLocalizedMessage()));
103         } catch (MarshalException e) {
104             if (e.getException() instanceof IOException JavaDoc) {
105                 throw new OpenEJBException(messages.format("conf.1110", confFile, e.getLocalizedMessage()));
106             } else if (e.getException() instanceof UnknownHostException JavaDoc) {
107                 throw new OpenEJBException(messages.format("conf.1121", confFile, e.getLocalizedMessage()));
108             } else {
109                 throw new OpenEJBException(messages.format("conf.1120", confFile, e.getLocalizedMessage()));
110             }
111         } catch (ValidationException e) {
112             /* TODO: Implement informative error handling here.
113                The exception will say "X doesn't match the regular
114                expression Y"
115                This should be checked and more relevant information
116                should be given -- not everyone understands regular
117                expressions.
118              */

119             /*
120             NOTE: This doesn't seem to ever happen, anyone know why?
121             */

122             throw new OpenEJBException(messages.format("conf.1130", confFile, e.getLocalizedMessage()));
123         }
124         try {
125             reader.close();
126         } catch (Exception JavaDoc e) {
127             throw new OpenEJBException(messages.format("file.0020", confFile, e.getLocalizedMessage()));
128         }
129         return obj;
130     }
131
132
133     public static void writeConfig(String JavaDoc confFile, Openejb confObject) throws OpenEJBException {
134         /* TODO: Just to be picky, the xml file created by
135         Castor is really hard to read -- it is all on one line.
136         People might want to edit this in the future by hand, so if Castor can
137         make the output look better that would be great! Otherwise we could
138         just spruce the output up by adding a few new lines and tabs.
139         */

140         Writer JavaDoc writer = null;
141         try {
142             File JavaDoc file = new File JavaDoc(confFile);
143             writer = new FileWriter JavaDoc(file);
144             confObject.marshal(writer);
145         } catch (IOException JavaDoc e) {
146             throw new OpenEJBException(messages.format("conf.1040", confFile, e.getLocalizedMessage()));
147         } catch (MarshalException e) {
148             if (e.getException() instanceof IOException JavaDoc) {
149                 throw new OpenEJBException(messages.format("conf.1040", confFile, e.getLocalizedMessage()));
150             } else {
151                 throw new OpenEJBException(messages.format("conf.1050", confFile, e.getLocalizedMessage()));
152             }
153         } catch (ValidationException e) {
154             /* TODO: Implement informative error handling here.
155                The exception will say "X doesn't match the regular
156                expression Y"
157                This should be checked and more relevant information
158                should be given -- not everyone understands regular
159                expressions.
160              */

161             /* NOTE: This doesn't seem to ever happen. When the object graph
162              * is invalid, the MarshalException is thrown, not this one as you
163              * would think.
164              */

165             throw new OpenEJBException(messages.format("conf.1060", confFile, e.getLocalizedMessage()));
166         }
167         try {
168             writer.close();
169         } catch (Exception JavaDoc e) {
170             throw new OpenEJBException(messages.format("file.0020", confFile, e.getLocalizedMessage()));
171         }
172     }
173
174     /**
175      * Search for the config file.
176      * <p/>
177      * OPENJB_HOME/conf/openejb.conf
178      * OPENJB_HOME/conf/default.openejb.conf
179      *
180      * @return String
181      */

182     public static String JavaDoc searchForConfiguration() throws OpenEJBException {
183         return searchForConfiguration(System.getProperty("openejb.configuration"));
184     }
185
186     public static String JavaDoc searchForConfiguration(String JavaDoc path) throws OpenEJBException {
187         return ConfigUtils.searchForConfiguration(path, System.getProperties());
188     }
189
190     public static String JavaDoc searchForConfiguration(String JavaDoc path, Properties JavaDoc props) throws OpenEJBException {
191         File JavaDoc file = null;
192         if (path != null) {
193             /*
194              * [1] Try finding the file relative to the current working
195              * directory
196              */

197             file = new File JavaDoc(path);
198             if (file != null && file.exists() && file.isFile()) {
199                 return file.getAbsolutePath();
200             }
201             
202             /*
203              * [2] Try finding the file relative to the openejb.base directory
204              */

205             try {
206                 file = SystemInstance.get().getBase().getFile(path);
207                 if (file != null && file.exists() && file.isFile()) {
208                     return file.getAbsolutePath();
209                 }
210             } catch (FileNotFoundException JavaDoc ignored) {
211             } catch (IOException JavaDoc ignored) {
212             }
213             
214             /*
215              * [3] Try finding the file relative to the openejb.home directory
216              */

217             try {
218                 file = SystemInstance.get().getHome().getFile(path);
219                 if (file != null && file.exists() && file.isFile()) {
220                     return file.getAbsolutePath();
221                 }
222             } catch (FileNotFoundException JavaDoc ignored) {
223             } catch (IOException JavaDoc ignored) {
224             }
225
226         }
227
228         logger.warning("Cannot find the configuration file [" + path + "], Trying conf/openejb.conf instead.");
229
230         try {
231             /*
232              * [4] Try finding the standard openejb.conf file relative to the
233              * openejb.base directory
234              */

235             try {
236                 file = SystemInstance.get().getBase().getFile("conf/openejb.conf");
237                 if (file != null && file.exists() && file.isFile()) {
238                     return file.getAbsolutePath();
239                 }
240             } catch (java.io.FileNotFoundException JavaDoc e) {
241             }
242                         
243             /*
244              * [5] Try finding the standard openejb.conf file relative to the
245              * openejb.home directory
246              */

247             try {
248                 file = SystemInstance.get().getHome().getFile("conf/openejb.conf");
249                 if (file != null && file.exists() && file.isFile()) {
250                     return file.getAbsolutePath();
251                 }
252             } catch (java.io.FileNotFoundException JavaDoc e) {
253             }
254
255             logger.warning("Cannot find the configuration file [conf/openejb.conf], Creating one.");
256
257             /* [6] No config found! Create a config for them
258              * using the default.openejb.conf file from
259              * the openejb-x.x.x.jar
260              */

261             //Gets the conf directory, creating it if needed.
262
File JavaDoc confDir = SystemInstance.get().getBase().getDirectory("conf", true);
263             
264             //TODO:1: We cannot find the user's conf file and
265
// are taking the liberty of creating one for them.
266
// We should log this.
267
file = createConfig(new File JavaDoc(confDir, "openejb.conf"));
268
269         } catch (java.io.IOException JavaDoc e) {
270             e.printStackTrace();
271             throw new OpenEJBException("Could not locate config file: ", e);
272         }
273         
274         /*TODO:2: Check these too.
275         * OPENJB_HOME/lib/openejb-x.x.x.jar
276         * OPENJB_HOME/dist/openejb-x.x.x.jar
277         */

278         return (file == null) ? null : file.getAbsolutePath();
279     }
280
281     public static File JavaDoc createConfig(File JavaDoc config) throws java.io.IOException JavaDoc {
282         InputStream JavaDoc in = null;
283         OutputStream JavaDoc out = null;
284         try {
285             URL JavaDoc defaultConfig = new URL JavaDoc("resource:/default.openejb.conf");
286             in = defaultConfig.openStream();
287             out = new FileOutputStream JavaDoc(config);
288
289             int b;
290             while ((b = in.read()) != -1) {
291                 out.write(b);
292             }
293         } finally {
294             if (in != null) {
295                 in.close();
296             }
297             if (out != null) {
298                 out.close();
299             }
300
301         }
302         return config;
303     }
304
305     public static boolean addDeploymentEntryToConfig(String JavaDoc jarLocation, Openejb config) {
306         Enumeration JavaDoc enumeration = config.enumerateDeployments();
307         File JavaDoc jar = new File JavaDoc(jarLocation);
308
309         /* Check to see if the entry is already listed */
310         while (enumeration.hasMoreElements()) {
311             Deployments d = (Deployments) enumeration.nextElement();
312
313             if (d.getJar() != null) {
314                 try {
315                     File JavaDoc target = SystemInstance.get().getBase().getFile(d.getJar(), false);
316                     
317                     /*
318                      * If the jar entry is already there, no need
319                      * to add it to the config or go any futher.
320                      */

321                     if (jar.equals(target)) return false;
322                 } catch (java.io.IOException JavaDoc e) {
323                     /* No handling needed. If there is a problem
324                      * resolving a config file path, it is better to
325                      * just add this jars path explicitly.
326                      */

327                 }
328             } else if (d.getDir() != null) {
329                 try {
330                     File JavaDoc target = SystemInstance.get().getBase().getFile(d.getDir(), false);
331                     File JavaDoc jarDir = jar.getAbsoluteFile().getParentFile();
332
333                     /*
334                      * If a dir entry is already there, the jar
335                      * will be loaded automatically. No need
336                      * to add it explicitly to the config or go
337                      * any futher.
338                      */

339                     if (jarDir != null && jarDir.equals(target)) return false;
340                 } catch (java.io.IOException JavaDoc e) {
341                     /* No handling needed. If there is a problem
342                      * resolving a config file path, it is better to
343                      * just add this jars path explicitly.
344                      */

345                 }
346             }
347         }
348
349         /* Create a new Deployments entry */
350         Deployments dep = new Deployments();
351         dep.setJar(jarLocation);
352         config.addDeployments(dep);
353         return true;
354     }
355 }
356
Popular Tags