KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > avalon > repository > main > DefaultInitialContextFactory


1 /*
2  * Copyright 2004 Apache Software Foundation
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  * http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
12  * implied.
13  *
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  */

17
18 package org.apache.avalon.repository.main;
19
20
21 import java.io.File JavaDoc;
22 import java.io.IOException JavaDoc;
23 import java.io.InputStream JavaDoc;
24 import java.util.ArrayList JavaDoc;
25 import java.util.Properties JavaDoc;
26 import java.util.StringTokenizer JavaDoc;
27
28 import org.apache.avalon.repository.Artifact;
29 import org.apache.avalon.repository.RepositoryRuntimeException;
30 import org.apache.avalon.repository.provider.InitialContext;
31 import org.apache.avalon.repository.provider.InitialContextFactory;
32
33 import org.apache.avalon.util.defaults.DefaultsBuilder;
34 import org.apache.avalon.util.defaults.Defaults;
35
36
37 /**
38  * A utility class used to establish a new {@link InitialContext}
39  * instance. An initial context is normally created by simply
40  * instantiating the factory using a application key and a working
41  * directory.
42  *
43  * <pre>
44  * final String key = "demo";
45  * final File work = new File( System.getProperty( "user.dir" ) );
46  * final InitialContextFactory factory =
47  * new DefaultInitialContextFactory( key, work );
48  * InitialContext context = factory.createInitialContext();
49  * </pre>
50  *
51  * @author <a HREF="mailto:dev@avalon.apache.org">Avalon Development Team</a>
52  * @version $Revision: 1.11 $
53  */

54 public class DefaultInitialContextFactory implements InitialContextFactory
55 {
56     //------------------------------------------------------------------
57
// private static
58
//------------------------------------------------------------------
59

60    /**
61     * The name of a properties resource contained within the repository
62     * bootstrap jar file. Property values contained in this resource
63     * consitute the most primative static default values.
64     */

65     private static final String JavaDoc AVALON_PROPERTIES = "avalon.properties";
66
67     //------------------------------------------------------------------
68
// immutable state
69
//------------------------------------------------------------------
70

71     private final String JavaDoc m_key;
72
73     private final File JavaDoc m_work;
74
75     private final DefaultsBuilder m_defaults;
76
77     private final Properties JavaDoc m_properties;
78
79     //------------------------------------------------------------------
80
// mutable state
81
//------------------------------------------------------------------
82

83     private File JavaDoc m_cache;
84
85     private Artifact m_artifact;
86
87     private ClassLoader JavaDoc m_classloader;
88
89     private String JavaDoc[] m_hosts;
90
91     private String JavaDoc m_proxyHost;
92
93     private int m_proxyPort;
94
95     private String JavaDoc m_proxyUsername;
96
97     private String JavaDoc m_proxyPassword;
98
99     private boolean m_online = true;
100
101     private Artifact[] m_registry;
102
103     // ------------------------------------------------------------------------
104
// constructor
105
// ------------------------------------------------------------------------
106

107     /**
108      * <p>Creates an initial repository context factory relative to
109      * the current working directory. This is equivalent to the following
110      * invocation:</p>
111      * <pre>
112      * final String key = "demo";
113      * final File work = new File( System.getProperty( "user.dir" );
114      * InitialContextFactory factory =
115      * new DefaultInitialContextFactory( key, work );
116      * </pre>
117      *
118      * @param key the application key
119      * @throws IOException if an error occurs during establishment
120      * @exception NullPointerException if tyhe supplied key is null
121      */

122     public DefaultInitialContextFactory( String JavaDoc key )
123       throws IOException JavaDoc
124     {
125         this( key, new File JavaDoc( System.getProperty( "user.dir" ) ) );
126     }
127
128     /**
129      * <p>Creates an initial repository context factory. The supplied
130      * key is used to establish the application root directory and
131      * property files at application, user and working directory
132      * levels. A key such as 'merlin' will be transformed to the
133      * environment symbol 'MERLIN_HOME' (i.e. uppercase of key plus
134      * _HOME) and resolved to a value. If the symbol is undefined,
135      * the application home directory defaults to a file path
136      * ${user.home}/.[key] (so for example, if MERLIN_HOME is
137      * undefined the default application home for Merlin is
138      * ${user.home}/.merlin. Based on the application root directory,
139      * a set of property files with the name [key].properties are
140      * resolved from the following locations:</p>
141      *
142      * <ul>
143      * <li>the current working directory</li>
144      * <li>user's home directory</li>
145      * <li>application home directory</li>
146      * </ul>
147      *
148      * <p>The order in which properties are evaluated in in accordance
149      * the above list. The current working directory properties take
150      * precedence over properties defined in the user's home directory
151      * which in turn take precedence over properties defined under the
152      * application home directory. System properties take precedence
153      * over all properties.</p>
154      *
155      * @param key the application key
156      * @param work the working directory
157      * @throws IOException if an error occurs during establishment
158      * @exception NullPointerException if the supplied key or work
159      * arguments are null
160      */

161     public DefaultInitialContextFactory( String JavaDoc key, File JavaDoc work )
162       throws IOException JavaDoc
163     {
164         if( null == key ) throw new NullPointerException JavaDoc( "key" );
165         if( null == work ) throw new NullPointerException JavaDoc( "work" );
166
167         m_key = key;
168         m_work = work;
169
170         m_defaults = new DefaultsBuilder( key, work );
171
172         //
173
// pull in the set of properties we need for the construction of
174
// the initial context
175
//
176

177         m_properties =
178           m_defaults.getConsolidatedProperties(
179             getDefaultProperties(), KEYS );
180         Defaults.macroExpand(
181             m_properties,
182             new Properties JavaDoc[]{ m_properties } );
183
184         //
185
// retrieve the property defining the implementation
186
// artifact for the initial repository
187
//
188

189         String JavaDoc spec = m_properties.getProperty(
190           InitialContext.IMPLEMENTATION_KEY );
191         if( null != spec )
192         {
193             m_artifact = Artifact.createArtifact( spec );
194         }
195         else
196         {
197             final String JavaDoc error =
198               "Required implementation key ["
199               + InitialContext.IMPLEMENTATION_KEY
200               + "] not found.";
201             throw new IllegalStateException JavaDoc( error );
202         }
203     }
204
205     // ------------------------------------------------------------------------
206
// InitialContextFactory
207
// ------------------------------------------------------------------------
208

209    /**
210     * Register a set of factory artifacts.
211     * @param artifacts the artifact references
212     */

213     public void setFactoryArtifacts( Artifact[] artifacts )
214     {
215         m_registry = artifacts;
216     }
217
218    /**
219     * Set the online mode of the repository. The default policy is to
220     * to enable online access to remote repositories. Setting the onLine
221     * mode to false disables remote repository access.
222     *
223     * @param policy the connected policy
224     */

225     public void setOnlineMode( boolean policy )
226     {
227         m_online = policy;
228     }
229
230    /**
231     * Set the parent classloader. If not defined, the default
232     * classloader is the classloader holding this class.
233     *
234     * @param classloader the parent classloader
235     */

236     public void setParentClassLoader( ClassLoader JavaDoc classloader )
237     {
238         m_classloader = classloader;
239     }
240
241    /**
242     * The initial context factory support the establishment of an
243     * initial context which is associated with a repository cache
244     * manager implementation. A client can override the default
245     * repository cache manager implementation by declaring an
246     * artifact referencing a compliant factory (not normally
247     * required).
248     *
249     * @param artifact the repository cache manager artifact
250     */

251     public void setImplementation( Artifact artifact )
252     {
253         m_artifact = artifact;
254     }
255
256    /**
257     * The cache directory is the directory into which resources
258     * such as jar files are loaded by a repository cache manager.
259     *
260     * @param cache the repository cache directory
261     */

262     public void setCacheDirectory( File JavaDoc cache )
263     {
264         m_cache = cache;
265     }
266
267    /**
268     * Set the initial hosts to be used by a repository cache manager
269     * implementation and the initial context implementation when
270     * resolving dependent resources. If is resource is not present
271     * in a local cache, remote hosts are checked in the order presented
272     * in the supplied list. A host may be a file url or a http url.
273     *
274     * @param hosts a sequence of remote host urls
275     */

276     public void setHosts( String JavaDoc[] hosts )
277     {
278         m_hosts = hosts;
279     }
280
281    /**
282     * Set the proxy host name. If not supplied proxy usage will be
283     * disabled.
284     *
285     * @param host the proxy host name
286     */

287     public void setProxyHost( String JavaDoc host )
288     {
289         m_proxyHost = host;
290     }
291
292    /**
293     * Set the proxy host port.
294     *
295     * @param port the proxy port
296     */

297     public void setProxyPort( int port )
298     {
299         m_proxyPort = port;
300     }
301
302    /**
303     * Set the proxy username.
304     *
305     * @param username the proxy username
306     */

307     public void setProxyUsername( String JavaDoc username )
308     {
309         m_proxyUsername = username;
310     }
311
312    /**
313     * Set the proxy account password.
314     *
315     * @param password the proxy password
316     */

317     public void setProxyPassword( String JavaDoc password )
318     {
319         m_proxyPassword = password;
320     }
321
322    /**
323     * Creation of an inital context based on the system and working
324     * directory, parent classloader, repository cache manager implementation
325     * artifact, cache directory, and remote hosts sequence supplied to the
326     * factory.
327     *
328     * @return a new initial context
329     */

330     public InitialContext createInitialContext()
331     {
332         try
333         {
334             return new DefaultInitialContext(
335               getApplicationKey(),
336               getParentClassLoader(),
337               getImplementation(),
338               getRegisteredArtifacts(),
339               getWorkingDirectory(),
340               getCacheDirectory(),
341               getProxyHost(),
342               getProxyPort(),
343               getProxyUsername(),
344               getProxyPassword(),
345               getHosts(),
346               getOnlineMode() );
347         }
348         catch( Throwable JavaDoc e )
349         {
350             final String JavaDoc error =
351               "Could not create initial context.";
352             throw new RepositoryRuntimeException( error, e );
353         }
354     }
355
356    /**
357     * Return the registory.
358     */

359     public Artifact[] getRegisteredArtifacts()
360     {
361         if( null != m_registry ) return m_registry;
362         return new Artifact[0];
363     }
364
365    /**
366     * Return the application key.
367     */

368     public boolean getOnlineMode()
369     {
370         return m_online;
371     }
372
373    /**
374     * Return the application key.
375     */

376     public String JavaDoc getApplicationKey()
377     {
378         return m_key;
379     }
380
381    /**
382     * Return the home directory value direved from the application key.
383     * @return the home directory.
384     */

385     public File JavaDoc getHomeDirectory()
386     {
387         return m_defaults.getHomeDirectory();
388     }
389
390    /**
391     * Return the working directory value.
392     * @return the working directory.
393     */

394     public File JavaDoc getWorkingDirectory()
395     {
396         return m_work;
397     }
398
399    /**
400     * Return the parent classloader. The default classloader returned
401     * from this operation is the classloader containing this class.
402     *
403     * @return the parent classloader
404     */

405     public ClassLoader JavaDoc getParentClassLoader()
406     {
407         if( null != m_classloader ) return m_classloader;
408         return DefaultInitialContext.class.getClassLoader();
409     }
410
411    /**
412     * Return the implementation artifact. If not overriden, a default
413     * artifact referencing avalon-repository-impl will be returned.
414     *
415     * @return the implementation artifact
416     */

417     public Artifact getImplementation()
418     {
419         return m_artifact;
420     }
421
422    /**
423     * Return the assigned or default cache directory. If undefined
424     * the cache directory shall default to ${avalon.home}/repository.
425     *
426     * @return the cache directory
427     */

428     public File JavaDoc getCacheDirectory()
429     {
430         if( null != m_cache ) return m_cache;
431         String JavaDoc value = m_properties.getProperty( InitialContext.CACHE_KEY );
432         if( null != value ) return new File JavaDoc( value );
433         return new File JavaDoc( getHomeDirectory(), "repository" );
434     }
435
436    /**
437     * Return the assigned or default host sequence.
438     * @return the remote host url sequence
439     */

440     public String JavaDoc[] getHosts()
441     {
442         if( null != m_hosts ) return m_hosts;
443         String JavaDoc value = m_properties.getProperty( InitialContext.HOSTS_KEY );
444         if( null == value ) return new String JavaDoc[0];
445         return expandHosts( value );
446     }
447
448    /**
449     * Get the proxy host name.
450     *
451     * @return the proxy host name
452     */

453     public String JavaDoc getProxyHost()
454     {
455         if( null != m_proxyHost ) return m_proxyHost;
456         return m_properties.getProperty( InitialContext.PROXY_HOST_KEY );
457     }
458
459    /**
460     * Get the proxy host port.
461     *
462     * @return the proxy port
463     */

464     public int getProxyPort()
465     {
466         if( m_proxyPort > -1 ) return m_proxyPort;
467         String JavaDoc value = m_properties.getProperty( InitialContext.PROXY_PORT_KEY );
468         if( value != null ) return Integer.parseInt( value );
469         return -1;
470     }
471
472    /**
473     * Get the proxy username.
474     *
475     * @return the proxy username
476     */

477     public String JavaDoc getProxyUsername()
478     {
479         if( null != m_proxyUsername ) return m_proxyUsername;
480         return m_properties.getProperty( InitialContext.PROXY_USERNAME_KEY );
481     }
482
483    /**
484     * Set the proxy account password.
485     *
486     * @return the proxy password
487     */

488     public String JavaDoc getProxyPassword()
489     {
490         if( null != m_proxyPassword ) return m_proxyPassword;
491         return m_properties.getProperty( InitialContext.PROXY_PASSWORD_KEY );
492     }
493
494     // ------------------------------------------------------------------------
495
// implementation
496
// ------------------------------------------------------------------------
497

498     private Properties JavaDoc getDefaultProperties() throws IOException JavaDoc
499     {
500         Properties JavaDoc properties = new Properties JavaDoc();
501         ClassLoader JavaDoc classloader =
502           DefaultInitialContextFactory.class.getClassLoader();
503         InputStream JavaDoc input =
504           classloader.getResourceAsStream( AVALON_PROPERTIES );
505         if( input == null )
506         {
507             final String JavaDoc error =
508               "Missing resource: [" + AVALON_PROPERTIES + "]";
509             throw new Error JavaDoc( error );
510         }
511         properties.load( input );
512         return properties;
513     }
514
515     private static String JavaDoc[] expandHosts( String JavaDoc arg )
516     {
517         ArrayList JavaDoc list = new ArrayList JavaDoc();
518         StringTokenizer JavaDoc tokenizer = new StringTokenizer JavaDoc( arg, "," );
519         while( tokenizer.hasMoreTokens() )
520         {
521             list.add( tokenizer.nextToken() );
522         }
523         return (String JavaDoc[]) list.toArray( new String JavaDoc[0] );
524     }
525 }
526
Popular Tags