KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > excalibur > configuration > ContextFactory


1 /*
2
3  ============================================================================
4                    The Apache Software License, Version 1.1
5  ============================================================================
6  
7  Copyright (C) 1999-2003 The Apache Software Foundation. All rights reserved.
8  
9  Redistribution and use in source and binary forms, with or without modifica-
10  tion, are permitted provided that the following conditions are met:
11  
12  1. Redistributions of source code must retain the above copyright notice,
13     this list of conditions and the following disclaimer.
14  
15  2. Redistributions in binary form must reproduce the above copyright notice,
16     this list of conditions and the following disclaimer in the documentation
17     and/or other materials provided with the distribution.
18  
19  3. The end-user documentation included with the redistribution, if any, must
20     include the following acknowledgment: "This product includes software
21     developed by the Apache Software Foundation (http://www.apache.org/)."
22     Alternately, this acknowledgment may appear in the software itself, if
23     and wherever such third-party acknowledgments normally appear.
24  
25  4. The names "Jakarta", "Avalon", "Excalibur" and "Apache Software Foundation"
26     must not be used to endorse or promote products derived from this software
27     without prior written permission. For written permission, please contact
28     apache@apache.org.
29  
30  5. Products derived from this software may not be called "Apache", nor may
31     "Apache" appear in their name, without prior written permission of the
32     Apache Software Foundation.
33  
34  THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
35  INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
36  FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
37  APACHE SOFTWARE FOUNDATION OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
38  INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLU-
39  DING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
40  OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
41  ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
42  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
43  THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
44  
45  This software consists of voluntary contributions made by many individuals
46  on behalf of the Apache Software Foundation. For more information on the
47  Apache Software Foundation, please see <http://www.apache.org/>.
48  
49 */

50 package org.apache.excalibur.configuration;
51
52 import java.lang.reflect.Constructor JavaDoc;
53 import java.util.Hashtable JavaDoc;
54 import java.util.Map JavaDoc;
55
56 import org.apache.avalon.framework.configuration.Configuration;
57 import org.apache.avalon.framework.configuration.ConfigurationException;
58 import org.apache.avalon.framework.context.Context;
59 import org.apache.avalon.framework.logger.Logger;
60
61 /**
62  * ContextFactory is a utility class that provides support for the creation
63  * context instances based on a XML context desciption.
64  *
65  * @version $Id: ContextFactory.java,v 1.7 2003/02/25 16:28:35 bloritsch Exp $
66  * @author Stephen McConnell <mcconnell@osm.net>
67  */

68 public class ContextFactory
69 {
70
71     //==========================================================
72
// context utilities
73
//==========================================================
74

75     /**
76      * Create context-attributes from entrys within &lt;context/&gt;-tag in config
77      * @param config the context configuration
78      * @return Context a context instance
79      * @exception ConfigurationException if a context related error occurs
80      */

81     public static Context createContextFromConfiguration( Configuration config )
82         throws ConfigurationException
83     {
84         return createContextFromConfiguration( null, config );
85     }
86
87     /**
88      * Create context-attributes from entrys within &lt;context/&gt;-tag in config
89      * @param parent the parent context
90      * @param config the configuration element describing the context parameters
91      * @return Context a context instance
92      * @exception ConfigurationException if a context related error occurs
93      */

94     public static Context createContextFromConfiguration(
95         Context parent, Configuration config )
96         throws ConfigurationException
97     {
98         return createContextFromConfiguration( parent, config, null );
99     }
100
101     /**
102      * Create context-attributes from entrys within &lt;context/&gt;-tag in config
103      * @param parent the parent context
104      * @param config the configuration element describing the context parameters
105      * @param log a logging channel
106      * @return Context a context instance
107      * @exception ConfigurationException if a context related error occurs
108      */

109     public static Context createContextFromConfiguration(
110         Context parent, Configuration config, Logger log )
111         throws ConfigurationException
112     {
113
114         ClassLoader JavaDoc loader = Thread.currentThread().getContextClassLoader();
115         String JavaDoc contextClassName = config.getAttribute(
116             "class",
117             "org.apache.avalon.framework.context.DefaultContext" );
118
119         Class JavaDoc contextClass = null;
120
121         try
122         {
123             contextClass = loader.loadClass( contextClassName );
124         }
125         catch( ClassNotFoundException JavaDoc cnfe )
126         {
127             throw new ConfigurationException(
128                 "Could not find context class " + contextClassName, cnfe );
129         }
130
131         Map JavaDoc map = new Hashtable JavaDoc();
132         Context context = null;
133         try
134         {
135             Constructor JavaDoc constructor = contextClass.getConstructor(
136                 new Class JavaDoc[]{Map JavaDoc.class, Context.class} );
137             context = (Context)constructor.newInstance( new Object JavaDoc[]{map, parent} );
138         }
139         catch( Throwable JavaDoc e )
140         {
141             throw new ConfigurationException(
142                 "Unexpected exception while creating custom context form "
143                 + contextClassName, e );
144         }
145
146         final Configuration[] entrys = config.getChildren( "entry" );
147
148         for( int i = 0; i < entrys.length; i++ )
149         {
150             final String JavaDoc className = entrys[ i ].getAttribute(
151                 "type", "java.lang.String" );
152             final String JavaDoc paramName = entrys[ i ].getAttribute(
153                 "name", null );
154
155             if( paramName == null )
156             {
157                 throw new ConfigurationException(
158                     "missing name for context-entry" );
159             }
160
161             try
162             {
163                 Class JavaDoc[] params;
164                 Object JavaDoc[] values;
165                 Configuration entry = entrys[ i ];
166
167                 if( entry.getAttribute( "value", null ) != null )
168                 {
169                     // Single argument String-constructor
170
params = new Class JavaDoc[ 1 ];
171                     params[ 0 ] = Class.forName( "java.lang.String" );
172                     Class JavaDoc[] consObjects = {Class.forName( "java.lang.String" )};
173                     Constructor JavaDoc cons = params[ 0 ].getConstructor( consObjects );
174                     values = new Object JavaDoc[ 1 ];
175                     Object JavaDoc[] consValues = {
176                         getContextValue( map, entry.getAttribute( "value" ) )
177                     };
178                     values[ 0 ] = cons.newInstance( consValues );
179
180                     if( log != null )
181                     {
182                         log.debug( "add context-attr '" + paramName
183                                    + "' class '" + className
184                                    + "' with value '" + consValues[ 0 ] + "'" );
185                     }
186                 }
187                 else
188                 {
189                     // Multiple argument constructor
190
Configuration[] entryChilds = entry.getChildren( "parameter" );
191
192                     params = new Class JavaDoc[ entryChilds.length ];
193                     values = new Object JavaDoc[ entryChilds.length ];
194
195                     if( log != null )
196                     {
197                         log.debug( "add context-attr '" + paramName
198                                    + "' class '" + className + "' with "
199                                    + entryChilds.length + " values" );
200                     }
201
202                     for( int p = 0; p < entryChilds.length; p++ )
203                     {
204                         String JavaDoc paramClassName = entryChilds[ p ].getAttribute(
205                             "type", "java.lang.String" );
206                         String JavaDoc paramValue = entryChilds[ p ].getAttribute( "value", null );
207
208                         if( paramValue == null )
209                         {
210                             if( log != null )
211                             {
212                                 log.debug( "value" + ( p + 1 ) + ": class '"
213                                            + paramClassName + "' no value" );
214                             }
215                         }
216                         else
217                         {
218                             paramValue = getContextValue( map, paramValue );
219                             if( log != null )
220                             {
221                                 log.debug( "value" + ( p + 1 ) + ": class '"
222                                            + paramClassName + "' value '" + paramValue + "'" );
223                             }
224                         }
225
226                         try
227                         {
228                             params[ p ] = loader.loadClass( paramClassName );
229
230                             if( paramValue == null )
231                             {
232                                 values[ p ] = params[ p ].newInstance();
233                             }
234                             else
235                             {
236                                 Class JavaDoc[] consObjects = {Class.forName( "java.lang.String" )};
237                                 Constructor JavaDoc cons = params[ p ].getConstructor( consObjects );
238                                 Object JavaDoc[] consValues = {paramValue};
239                                 values[ p ] = cons.newInstance( consValues );
240                             }
241                         }
242                         catch( ClassNotFoundException JavaDoc e )
243                         {
244                             // Class not found
245
// -> perhaps a primitve class?
246
if( paramClassName.equals( "int" ) )
247                             {
248                                 params[ p ] = int.class;
249                                 values[ p ] = new Integer JavaDoc( paramValue );
250                             }
251                             else if( paramClassName.equals( "short" ) )
252                             {
253                                 params[ p ] = short.class;
254                                 values[ p ] = new Short JavaDoc( paramValue );
255                             }
256                             else if( paramClassName.equals( "long" ) )
257                             {
258                                 params[ p ] = long.class;
259                                 values[ p ] = new Long JavaDoc( paramValue );
260                             }
261                             else if( paramClassName.equals( "byte" ) )
262                             {
263                                 params[ p ] = byte.class;
264                                 values[ p ] = new Byte JavaDoc( paramValue );
265                             }
266                             else if( paramClassName.equals( "double" ) )
267                             {
268                                 params[ p ] = double.class;
269                                 values[ p ] = new Double JavaDoc( paramValue );
270                             }
271                             else if( paramClassName.equals( "float" ) )
272                             {
273                                 params[ p ] = float.class;
274                                 values[ p ] = new Float JavaDoc( paramValue );
275                             }
276                             else if( paramClassName.equals( "char" ) )
277                             {
278                                 params[ p ] = char.class;
279                                 values[ p ] = new Character JavaDoc( paramValue.charAt( 0 ) );
280                             }
281                             else if( paramClassName.equals( "boolean" ) )
282                             {
283                                 params[ p ] = boolean.class;
284                                 values[ p ] = new Boolean JavaDoc( paramValue );
285                             }
286                             else
287                             {
288                                 throw new ConfigurationException(
289                                     "incorrect type '" + paramClassName
290                                     + "' for context-attribute '" + paramName + "'", e );
291                             }
292                         }
293                     }
294                 }
295
296                 Class JavaDoc paramClass;
297                 try
298                 {
299                     paramClass = loader.loadClass( className );
300                 }
301                 catch( final ClassNotFoundException JavaDoc e )
302                 {
303                     throw new ConfigurationException(
304                         "incorrect type '" + className
305                         + "' for context-attribute '" + paramName + "'",
306                         e );
307                 }
308
309                 Object JavaDoc paramInstance;
310
311                 if( params.length > 0 )
312                 {
313                     // using param contructor
314
Constructor JavaDoc cons = paramClass.getConstructor( params );
315                     paramInstance = cons.newInstance( values );
316                 }
317                 else
318                 {
319                     // using default constructor
320
paramInstance = paramClass.newInstance();
321                 }
322
323                 map.put( paramName, paramInstance );
324             }
325             catch( ConfigurationException e )
326             {
327                 throw e;
328             }
329             catch( Exception JavaDoc e )
330             {
331                 throw new ConfigurationException(
332                     "Error add context-attribute '" + paramName
333                     + "' from Configuration", e );
334             }
335         }
336         return context;
337     }
338
339     /**
340      * Resolving an attribute value by replacing ${context-param} with
341      * the corresponding param out of current context.
342      * @param map a map
343      * @param rawValue a raw value
344      * @return String the context attribute value
345      * @exception ConfigurationException if context-param does not exists
346      */

347     private static String JavaDoc getContextValue( Map JavaDoc map, String JavaDoc rawValue )
348         throws ConfigurationException
349     {
350         StringBuffer JavaDoc result = new StringBuffer JavaDoc( "" );
351         int i = 0;
352         int j = -1;
353         while( ( j = rawValue.indexOf( "${", i ) ) > -1 )
354         {
355             if( i < j )
356             {
357                 result.append( rawValue.substring( i, j ) );
358             }
359             int k = rawValue.indexOf( '}', j );
360             final String JavaDoc ctxName = rawValue.substring( j + 2, k );
361             final Object JavaDoc ctx = map.get( ctxName );
362             if( ctx == null )
363             {
364                 throw new ConfigurationException(
365                     "missing entry '" + ctxName + "' in Context" );
366             }
367             result.append( ctx.toString() );
368             i = k + 1;
369         }
370         if( i < rawValue.length() )
371         {
372             result.append( rawValue.substring( i, rawValue.length() ) );
373         }
374         return result.toString();
375     }
376
377 }
378
379
380
381
Popular Tags