KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > mchange > v2 > c3p0 > cfg > C3P0ConfigXmlUtils


1 /*
2  * Distributed as part of c3p0 v.0.9.1
3  *
4  * Copyright (C) 2005 Machinery For Change, Inc.
5  *
6  * Author: Steve Waldman <swaldman@mchange.com>
7  *
8  * This library is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU Lesser General Public License version 2.1, as
10  * published by the Free Software Foundation.
11  *
12  * This software is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15  * GNU Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public License
18  * along with this software; see the file LICENSE. If not, write to the
19  * Free Software Foundation, Inc., 59 Temple Place, Suite 330,
20  * Boston, MA 02111-1307, USA.
21  */

22
23
24 package com.mchange.v2.c3p0.cfg;
25
26 import java.io.*;
27 import java.util.*;
28 import javax.xml.parsers.*;
29 import org.w3c.dom.*;
30 import com.mchange.v2.log.*;
31
32 import com.mchange.v1.xml.DomParseUtils;
33
34 public final class C3P0ConfigXmlUtils
35 {
36     public final static String JavaDoc XML_CONFIG_RSRC_PATH = "/c3p0-config.xml";
37
38     final static MLogger logger = MLog.getLogger( C3P0ConfigXmlUtils.class );
39
40     public final static String JavaDoc LINESEP;
41
42     private final static String JavaDoc[] MISSPELL_PFXS = {"/c3p0", "/c3pO", "/c3po", "/C3P0", "/C3PO"};
43     private final static char[] MISSPELL_LINES = {'-', '_'};
44     private final static String JavaDoc[] MISSPELL_CONFIG = {"config", "CONFIG"};
45     private final static String JavaDoc[] MISSPELL_XML = {"xml", "XML"};
46
47     // its an ugly way to do this, but since resources are not listable...
48
//
49
// this is only executed once, and does about 40 tests (for now)
50
// should I care about the cost in initialization time?
51
//
52
// should only be run if we've checked for the correct file, but
53
// not found it
54
private final static void warnCommonXmlConfigResourceMisspellings()
55     {
56         if (logger.isLoggable( MLevel.WARNING) )
57         {
58             for (int a = 0, lena = MISSPELL_PFXS.length; a < lena; ++a)
59             {
60                 StringBuffer JavaDoc sb = new StringBuffer JavaDoc(16);
61                 sb.append( MISSPELL_PFXS[a] );
62                 for (int b = 0, lenb = MISSPELL_LINES.length; b < lenb; ++b)
63                 {
64                     sb.append(MISSPELL_LINES[b]);
65                     for (int c = 0, lenc = MISSPELL_CONFIG.length; c < lenc; ++c)
66                     {
67                         sb.append(MISSPELL_CONFIG[c]);
68                         sb.append('.');
69                         for (int d = 0, lend = MISSPELL_XML.length; d < lend; ++d)
70                         {
71                             sb.append(MISSPELL_XML[d]);
72                             String JavaDoc test = sb.toString();
73                             if (!test.equals(XML_CONFIG_RSRC_PATH))
74                             {
75                                 Object JavaDoc hopefullyNull = C3P0ConfigXmlUtils.class.getResource( test );
76                                 if (hopefullyNull != null)
77                                 {
78                                     logger.warning("POSSIBLY MISSPELLED c3p0-conf.xml RESOURCE FOUND. " +
79                                                    "Please ensure the file name is c3p0-config.xml, all lower case, " +
80                                                    "with the digit 0 (NOT the letter O) in c3p0. It should be placed " +
81                                                    " in the top level of c3p0's effective classpath.");
82                                     return;
83                                 }
84                             }
85                         }
86                     }
87
88                 }
89             }
90         }
91     }
92
93     static
94     {
95         String JavaDoc ls;
96
97         try
98         { ls = System.getProperty("line.separator", "\r\n"); }
99         catch (Exception JavaDoc e)
100         { ls = "\r\n"; }
101
102         LINESEP = ls;
103
104     }
105
106     public static C3P0Config extractXmlConfigFromDefaultResource() throws Exception JavaDoc
107     {
108         InputStream is = null;
109
110         try
111         {
112             is = C3P0ConfigUtils.class.getResourceAsStream(XML_CONFIG_RSRC_PATH);
113             if ( is == null )
114             {
115                 warnCommonXmlConfigResourceMisspellings();
116                 return null;
117             }
118             else
119                 return extractXmlConfigFromInputStream( is );
120         }
121         finally
122         {
123             try { if (is != null) is.close(); }
124             catch (Exception JavaDoc e)
125             {
126                 if ( logger.isLoggable( MLevel.FINE ) )
127                     logger.log(MLevel.FINE,"Exception on resource InputStream close.", e);
128             }
129         }
130     }
131
132     public static C3P0Config extractXmlConfigFromInputStream(InputStream is) throws Exception JavaDoc
133     {
134         DocumentBuilderFactory fact = DocumentBuilderFactory.newInstance();
135         DocumentBuilder db = fact.newDocumentBuilder();
136         Document doc = db.parse( is );
137
138         return extractConfigFromXmlDoc(doc);
139     }
140
141     public static C3P0Config extractConfigFromXmlDoc(Document doc) throws Exception JavaDoc
142     {
143         Element docElem = doc.getDocumentElement();
144         if (docElem.getTagName().equals("c3p0-config"))
145         {
146             NamedScope defaults;
147             HashMap configNamesToNamedScopes = new HashMap();
148
149             Element defaultConfigElem = DomParseUtils.uniqueChild( docElem, "default-config" );
150             if (defaultConfigElem != null)
151                 defaults = extractNamedScopeFromLevel( defaultConfigElem );
152             else
153                 defaults = new NamedScope();
154             NodeList nl = DomParseUtils.immediateChildElementsByTagName(docElem, "named-config");
155             for (int i = 0, len = nl.getLength(); i < len; ++i)
156             {
157                 Element namedConfigElem = (Element) nl.item(i);
158                 String JavaDoc configName = namedConfigElem.getAttribute("name");
159                 if (configName != null && configName.length() > 0)
160                 {
161                     NamedScope namedConfig = extractNamedScopeFromLevel( namedConfigElem );
162                     configNamesToNamedScopes.put( configName, namedConfig);
163                 }
164                 else
165                     logger.warning("Configuration XML contained named-config element without name attribute: " + namedConfigElem);
166             }
167             return new C3P0Config( defaults, configNamesToNamedScopes );
168         }
169         else
170             throw new Exception JavaDoc("Root element of c3p0 config xml should be 'c3p0-config', not '" + docElem.getTagName() + "'.");
171     }
172
173     private static NamedScope extractNamedScopeFromLevel(Element elem)
174     {
175         HashMap props = extractPropertiesFromLevel( elem );
176         HashMap userNamesToOverrides = new HashMap();
177
178         NodeList nl = DomParseUtils.immediateChildElementsByTagName(elem, "user-overrides");
179         for (int i = 0, len = nl.getLength(); i < len; ++i)
180         {
181             Element perUserConfigElem = (Element) nl.item(i);
182             String JavaDoc userName = perUserConfigElem.getAttribute("user");
183             if (userName != null && userName.length() > 0)
184             {
185                 HashMap userProps = extractPropertiesFromLevel( perUserConfigElem );
186                 userNamesToOverrides.put( userName, userProps );
187             }
188             else
189                 logger.warning("Configuration XML contained user-overrides element without user attribute: " + LINESEP + perUserConfigElem);
190         }
191
192         return new NamedScope(props, userNamesToOverrides);
193     }
194
195     private static HashMap extractPropertiesFromLevel(Element elem)
196     {
197         // System.err.println( "extractPropertiesFromLevel()" );
198

199         HashMap out = new HashMap();
200
201         try
202         {
203             NodeList nl = DomParseUtils.immediateChildElementsByTagName(elem, "property");
204             int len = nl.getLength();
205             for (int i = 0; i < len; ++i)
206             {
207                 Element propertyElem = (Element) nl.item(i);
208                 String JavaDoc propName = propertyElem.getAttribute("name");
209                 if (propName != null && propName.length() > 0)
210                 {
211                     String JavaDoc propVal = DomParseUtils.allTextFromElement(propertyElem, true);
212                     out.put( propName, propVal );
213                     //System.err.println( propName + " -> " + propVal );
214
}
215                 else
216                     logger.warning("Configuration XML contained property element without name attribute: " + LINESEP + propertyElem);
217             }
218         }
219         catch (Exception JavaDoc e)
220         {
221             logger.log( MLevel.WARNING,
222                             "An exception occurred while reading config XML. " +
223                             "Some configuration information has probably been ignored.",
224                             e );
225         }
226
227         return out;
228     }
229
230     private C3P0ConfigXmlUtils()
231     {}
232 }
Popular Tags