KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > avalon > framework > parameters > Parameters


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

55 package org.apache.avalon.framework.parameters;
56
57 import java.io.Serializable JavaDoc;
58 import java.util.Enumeration JavaDoc;
59 import java.util.HashMap JavaDoc;
60 import java.util.Iterator JavaDoc;
61 import java.util.Map JavaDoc;
62 import java.util.Properties JavaDoc;
63 import org.apache.avalon.framework.configuration.Configuration;
64 import org.apache.avalon.framework.configuration.ConfigurationException;
65
66 /**
67  * The <code>Parameters</code> class represents a set of key-value
68  * pairs.
69  * <p>
70  * The <code>Parameters</code> object provides a mechanism to obtain
71  * values based on a <code>String</code> name. There are convenience
72  * methods that allow you to use defaults if the value does not exist,
73  * as well as obtain the value in any of the same formats that are in
74  * the {@link Configuration} interface.
75  * </p><p>
76  * While there are similarities between the <code>Parameters</code>
77  * object and the java.util.Properties object, there are some
78  * important semantic differences. First, <code>Parameters</code> are
79  * <i>read-only</i>. Second, <code>Parameters</code> are easily
80  * derived from {@link Configuration} objects. Lastly, the
81  * <code>Parameters</code> object is derived from XML fragments that
82  * look like this:
83  * <pre><code>
84  * &lt;parameter name="param-name" value="param-value" /&gt;
85  * </code></pre>
86  * </p><p>
87  * <strong>Note: this class is not thread safe by default.</strong> If you
88  * require thread safety please synchronize write access to this class to
89  * prevent potential data corruption.
90  * </p>
91  *
92  * @author <a HREF="mailto:dev@avalon.apache.org">Avalon Development Team</a>
93  * @version CVS $Revision: 1.38 $ $Date: 2003/02/11 16:25:49 $
94  */

95 public class Parameters
96     implements Serializable JavaDoc
97 {
98     /**
99      * Empty Parameters object
100      *
101      * @since 4.1.2
102      */

103     public static final Parameters EMPTY_PARAMETERS;
104
105     /** Static initializer to initialize the empty Parameters object */
106     static
107     {
108         EMPTY_PARAMETERS = new Parameters();
109         EMPTY_PARAMETERS.makeReadOnly();
110     }
111
112     ///Underlying store of parameters
113
private Map JavaDoc m_parameters = new HashMap JavaDoc();
114
115     private boolean m_readOnly;
116
117     /**
118      * Set the <code>String</code> value of a specified parameter.
119      * <p />
120      * If the specified value is <b>null</b> the parameter is removed.
121      *
122      * @param name a <code>String</code> value
123      * @param value a <code>String</code> value
124      * @return The previous value of the parameter or <b>null</b>.
125      * @throws IllegalStateException if the Parameters object is read-only
126      */

127     public String JavaDoc setParameter( final String JavaDoc name, final String JavaDoc value )
128         throws IllegalStateException JavaDoc
129     {
130         checkWriteable();
131
132         if( null == name )
133         {
134             return null;
135         }
136
137         if( null == value )
138         {
139             return (String JavaDoc)m_parameters.remove( name );
140         }
141
142         return (String JavaDoc)m_parameters.put( name, value );
143     }
144
145     /**
146      * Remove a parameter from the parameters object
147      * @param name a <code>String</code> value
148      * @since 4.1
149      */

150     public void removeParameter( final String JavaDoc name )
151     {
152         setParameter( name, null );
153     }
154
155     /**
156      * Return an <code>Iterator</code> view of all parameter names.
157      *
158      * @return a iterator of parameter names
159      * @deprecated Use getNames() instead
160      */

161     public Iterator JavaDoc getParameterNames()
162     {
163         return m_parameters.keySet().iterator();
164     }
165
166     /**
167      * Retrieve an array of all parameter names.
168      *
169      * @return the parameters names
170      */

171     public String JavaDoc[] getNames()
172     {
173         return (String JavaDoc[])m_parameters.keySet().toArray( new String JavaDoc[ 0 ] );
174     }
175
176     /**
177      * Test if the specified parameter can be retrieved.
178      *
179      * @param name the parameter name
180      * @return true if parameter is a name
181      */

182     public boolean isParameter( final String JavaDoc name )
183     {
184         return m_parameters.containsKey( name );
185     }
186
187     /**
188      * Retrieve the <code>String</code> value of the specified parameter.
189      * <p />
190      * If the specified parameter cannot be found, an exception is thrown.
191      *
192      * @param name the name of parameter
193      * @return the value of parameter
194      * @throws ParameterException if the specified parameter cannot be found
195      */

196     public String JavaDoc getParameter( final String JavaDoc name )
197         throws ParameterException
198     {
199         if( null == name )
200         {
201             throw new ParameterException( "You cannot lookup a null parameter" );
202         }
203
204         final String JavaDoc test = (String JavaDoc)m_parameters.get( name );
205
206         if( null == test )
207         {
208             throw new ParameterException( "The parameter '" + name
209                                           + "' does not contain a value" );
210         }
211         else
212         {
213             return test;
214         }
215     }
216
217     /**
218      * Retrieve the <code>String</code> value of the specified parameter.
219      * <p />
220      * If the specified parameter cannot be found, <code>defaultValue</code>
221      * is returned.
222      *
223      * @param name the name of parameter
224      * @param defaultValue the default value, returned if parameter does not exist
225      * or parameter's name is null
226      * @return the value of parameter
227      */

228     public String JavaDoc getParameter( final String JavaDoc name, final String JavaDoc defaultValue )
229     {
230         if( name == null )
231         {
232             return defaultValue;
233         }
234
235         final String JavaDoc test = (String JavaDoc)m_parameters.get( name );
236
237         if( test == null )
238         {
239             return defaultValue;
240         }
241         else
242         {
243             return test;
244         }
245     }
246
247     /**
248      * Parses string represenation of the <code>int</code> value.
249      * <p />
250      * Hexadecimal numbers begin with 0x, Octal numbers begin with 0o and binary
251      * numbers begin with 0b, all other values are assumed to be decimal.
252      *
253      * @param value the value to parse
254      * @return the integer value
255      * @throws NumberFormatException if the specified value can not be parsed
256      */

257     private int parseInt( final String JavaDoc value )
258         throws NumberFormatException JavaDoc
259     {
260         if( value.startsWith( "0x" ) )
261         {
262             return Integer.parseInt( value.substring( 2 ), 16 );
263         }
264         else if( value.startsWith( "0o" ) )
265         {
266             return Integer.parseInt( value.substring( 2 ), 8 );
267         }
268         else if( value.startsWith( "0b" ) )
269         {
270             return Integer.parseInt( value.substring( 2 ), 2 );
271         }
272         else
273         {
274             return Integer.parseInt( value );
275         }
276     }
277
278     /**
279      * Retrieve the <code>int</code> value of the specified parameter.
280      * <p />
281      * If the specified parameter cannot be found, an exception is thrown.
282      *
283      * Hexadecimal numbers begin with 0x, Octal numbers begin with 0o and binary
284      * numbers begin with 0b, all other values are assumed to be decimal.
285      *
286      * @param name the name of parameter
287      * @return the integer parameter type
288      * @throws ParameterException if the specified parameter cannot be found
289      * or is not an Integer value
290      */

291     public int getParameterAsInteger( final String JavaDoc name )
292         throws ParameterException
293     {
294         try
295         {
296             return parseInt( getParameter( name ) );
297         }
298         catch( final NumberFormatException JavaDoc e )
299         {
300             throw new ParameterException( "Could not return an integer value", e );
301         }
302     }
303
304     /**
305      * Retrieve the <code>int</code> value of the specified parameter.
306      * <p />
307      * If the specified parameter cannot be found, <code>defaultValue</code>
308      * is returned.
309      *
310      * Hexadecimal numbers begin with 0x, Octal numbers begin with 0o and binary
311      * numbers begin with 0b, all other values are assumed to be decimal.
312      *
313      * @param name the name of parameter
314      * @param defaultValue value returned if parameter does not exist or is of wrong type
315      * @return the integer parameter type
316      */

317     public int getParameterAsInteger( final String JavaDoc name, final int defaultValue )
318     {
319         try
320         {
321             final String JavaDoc value = getParameter( name, null );
322             if( value == null )
323             {
324                 return defaultValue;
325             }
326
327             return parseInt( value );
328         }
329         catch( final NumberFormatException JavaDoc e )
330         {
331             return defaultValue;
332         }
333     }
334
335     /**
336      * Parses string represenation of the <code>long</code> value.
337      * <p />
338      * Hexadecimal numbers begin with 0x, Octal numbers begin with 0o and binary
339      * numbers begin with 0b, all other values are assumed to be decimal.
340      *
341      * @param value the value to parse
342      * @return the long value
343      * @throws NumberFormatException if the specified value can not be parsed
344      */

345     private long parseLong( final String JavaDoc value )
346         throws NumberFormatException JavaDoc
347     {
348         if( value.startsWith( "0x" ) )
349         {
350             return Long.parseLong( value.substring( 2 ), 16 );
351         }
352         else if( value.startsWith( "0o" ) )
353         {
354             return Long.parseLong( value.substring( 2 ), 8 );
355         }
356         else if( value.startsWith( "0b" ) )
357         {
358             return Long.parseLong( value.substring( 2 ), 2 );
359         }
360         else
361         {
362             return Long.parseLong( value );
363         }
364     }
365
366     /**
367      * Retrieve the <code>long</code> value of the specified parameter.
368      * <p />
369      * If the specified parameter cannot be found, an exception is thrown.
370      *
371      * Hexadecimal numbers begin with 0x, Octal numbers begin with 0o and binary
372      * numbers begin with 0b, all other values are assumed to be decimal.
373      *
374      * @param name the name of parameter
375      * @return the long parameter type
376      * @throws ParameterException if the specified parameter cannot be found
377      * or is not a Long value.
378      */

379     public long getParameterAsLong( final String JavaDoc name )
380         throws ParameterException
381     {
382         try
383         {
384             return parseLong( getParameter( name ) );
385         }
386         catch( final NumberFormatException JavaDoc e )
387         {
388             throw new ParameterException( "Could not return a long value", e );
389         }
390     }
391
392     /**
393      * Retrieve the <code>long</code> value of the specified parameter.
394      * <p />
395      * If the specified parameter cannot be found, <code>defaultValue</code>
396      * is returned.
397      *
398      * Hexadecimal numbers begin with 0x, Octal numbers begin with 0o and binary
399      * numbers begin with 0b, all other values are assumed to be decimal.
400      *
401      * @param name the name of parameter
402      * @param defaultValue value returned if parameter does not exist or is of wrong type
403      * @return the long parameter type
404      */

405     public long getParameterAsLong( final String JavaDoc name, final long defaultValue )
406     {
407         try
408         {
409             final String JavaDoc value = getParameter( name, null );
410             if( value == null )
411             {
412                 return defaultValue;
413             }
414
415             return parseLong( value );
416         }
417         catch( final NumberFormatException JavaDoc e )
418         {
419             return defaultValue;
420         }
421     }
422
423     /**
424      * Retrieve the <code>float</code> value of the specified parameter.
425      * <p />
426      * If the specified parameter cannot be found, an exception is thrown.
427      *
428      * @param name the parameter name
429      * @return the value
430      * @throws ParameterException if the specified parameter cannot be found
431      * or is not a Float value
432      */

433     public float getParameterAsFloat( final String JavaDoc name )
434         throws ParameterException
435     {
436         try
437         {
438             return Float.parseFloat( getParameter( name ) );
439         }
440         catch( final NumberFormatException JavaDoc e )
441         {
442             throw new ParameterException( "Could not return a float value", e );
443         }
444     }
445
446     /**
447      * Retrieve the <code>float</code> value of the specified parameter.
448      * <p />
449      * If the specified parameter cannot be found, <code>defaultValue</code>
450      * is returned.
451      *
452      * @param name the parameter name
453      * @param defaultValue the default value if parameter does not exist or is of wrong type
454      * @return the value
455      */

456     public float getParameterAsFloat( final String JavaDoc name, final float defaultValue )
457     {
458         try
459         {
460             final String JavaDoc value = getParameter( name, null );
461             if( value == null )
462             {
463                 return defaultValue;
464             }
465
466             return Float.parseFloat( value );
467         }
468         catch( final NumberFormatException JavaDoc pe )
469         {
470             return defaultValue;
471         }
472     }
473
474     /**
475      * Retrieve the <code>boolean</code> value of the specified parameter.
476      * <p />
477      * If the specified parameter cannot be found, an exception is thrown.
478      *
479      * @param name the parameter name
480      * @return the value
481      * @throws ParameterException if an error occurs
482      * @throws ParameterException
483      */

484     public boolean getParameterAsBoolean( final String JavaDoc name )
485         throws ParameterException
486     {
487         final String JavaDoc value = getParameter( name );
488
489         if( value.equalsIgnoreCase( "true" ) )
490         {
491             return true;
492         }
493         else if( value.equalsIgnoreCase( "false" ) )
494         {
495             return false;
496         }
497         else
498         {
499             throw new ParameterException( "Could not return a boolean value" );
500         }
501     }
502
503     /**
504      * Retrieve the <code>boolean</code> value of the specified parameter.
505      * <p />
506      * If the specified parameter cannot be found, <code>defaultValue</code>
507      * is returned.
508      *
509      * @param name the parameter name
510      * @param defaultValue the default value if parameter does not exist or is of wrong type
511      * @return the value
512      */

513     public boolean getParameterAsBoolean( final String JavaDoc name, final boolean defaultValue )
514     {
515         final String JavaDoc value = getParameter( name, null );
516         if( value == null )
517         {
518             return defaultValue;
519         }
520
521         if( value.equalsIgnoreCase( "true" ) )
522         {
523             return true;
524         }
525         else if( value.equalsIgnoreCase( "false" ) )
526         {
527             return false;
528         }
529         else
530         {
531             return defaultValue;
532         }
533     }
534
535     /**
536      * Merge parameters from another <code>Parameters</code> instance
537      * into this.
538      *
539      * @param other the other Parameters
540      * @return This <code>Parameters</code> instance.
541      */

542     public Parameters merge( final Parameters other )
543     {
544         checkWriteable();
545
546         final String JavaDoc[] names = other.getNames();
547
548         for( int i = 0; i < names.length; i++ )
549         {
550             final String JavaDoc name = names[ i ];
551             String JavaDoc value = null;
552             try
553             {
554                 value = other.getParameter( name );
555             }
556             catch( final ParameterException pe )
557             {
558                 value = null;
559             }
560
561             setParameter( name, value );
562         }
563
564         return this;
565     }
566
567     /**
568      * Make this Parameters read-only so that it will throw a
569      * <code>IllegalStateException</code> if someone tries to
570      * modify it.
571      */

572     public void makeReadOnly()
573     {
574         m_readOnly = true;
575     }
576
577     /**
578      * Checks is this <code>Parameters</code> object is writeable.
579      *
580      * @throws IllegalStateException if this <code>Parameters</code> object is read-only
581      */

582     protected final void checkWriteable()
583         throws IllegalStateException JavaDoc
584     {
585         if( m_readOnly )
586         {
587             throw new IllegalStateException JavaDoc( "Context is read only and can not be modified" );
588         }
589     }
590
591     /**
592      * Create a <code>Parameters</code> object from a <code>Configuration</code>
593      * object. This acts exactly like the following method call:
594      * <pre>
595      * Parameters.fromConfiguration(configuration, "parameter");
596      * </pre>
597      *
598      * @param configuration the Configuration
599      * @return This <code>Parameters</code> instance.
600      * @throws ConfigurationException if an error occurs
601      */

602     public static Parameters fromConfiguration( final Configuration configuration )
603         throws ConfigurationException
604     {
605         return fromConfiguration( configuration, "parameter" );
606     }
607
608     /**
609      * Create a <code>Parameters</code> object from a <code>Configuration</code>
610      * object using the supplied element name.
611      *
612      * @param configuration the Configuration
613      * @param elementName the element name for the parameters
614      * @return This <code>Parameters</code> instance.
615      * @throws ConfigurationException if an error occurs
616      * @since 4.1
617      */

618     public static Parameters fromConfiguration( final Configuration configuration,
619                                                 final String JavaDoc elementName )
620         throws ConfigurationException
621     {
622         if( null == configuration )
623         {
624             throw new ConfigurationException(
625                "You cannot convert to parameters with a null Configuration" );
626         }
627
628         final Configuration[] parameters = configuration.getChildren( elementName );
629         final Parameters params = new Parameters();
630
631         for( int i = 0; i < parameters.length; i++ )
632         {
633             try
634             {
635                 final String JavaDoc name = parameters[ i ].getAttribute( "name" );
636                 final String JavaDoc value = parameters[ i ].getAttribute( "value" );
637                 params.setParameter( name, value );
638             }
639             catch( final Exception JavaDoc e )
640             {
641                 throw new ConfigurationException( "Cannot process Configurable", e );
642             }
643         }
644
645         return params;
646     }
647
648     /**
649      * Create a <code>Parameters</code> object from a <code>Properties</code>
650      * object.
651      *
652      * @param properties the Properties
653      * @return This <code>Parameters</code> instance.
654      */

655     public static Parameters fromProperties( final Properties JavaDoc properties )
656     {
657         final Parameters parameters = new Parameters();
658         final Enumeration JavaDoc names = properties.propertyNames();
659
660         while( names.hasMoreElements() )
661         {
662             final String JavaDoc key = (String JavaDoc)names.nextElement().toString();
663             final String JavaDoc value = properties.getProperty( key );
664             parameters.setParameter( key, value );
665         }
666
667         return parameters;
668     }
669
670     /**
671      * Creates a <code>java.util.Properties</code> object from an Avalon
672      * Parameters object.
673      *
674      * @param params a <code>Parameters</code> instance
675      * @return a <code>Properties</code> instance
676      */

677     public static Properties JavaDoc toProperties( final Parameters params )
678     {
679         final Properties JavaDoc properties = new Properties JavaDoc();
680         final String JavaDoc[] names = params.getNames();
681
682         for( int i = 0; i < names.length; ++i )
683         {
684             // "" is the default value, since getNames() proves it will exist
685
properties.setProperty( names[ i ], params.getParameter( names[ i ], "" ) );
686         }
687
688         return properties;
689     }
690 }
691
Popular Tags