001    // Copyright 2004, 2005 The Apache Software Foundation
002    //
003    // Licensed under the Apache License, Version 2.0 (the "License");
004    // you may not use this file except in compliance with the License.
005    // You may obtain a copy of the License at
006    //
007    //     http://www.apache.org/licenses/LICENSE-2.0
008    //
009    // Unless required by applicable law or agreed to in writing, software
010    // distributed under the License is distributed on an "AS IS" BASIS,
011    // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
012    // See the License for the specific language governing permissions and
013    // limitations under the License.
014    
015    package org.apache.hivemind.util;
016    
017    import java.io.IOException;
018    import java.io.InputStream;
019    import java.net.MalformedURLException;
020    import java.net.URL;
021    import java.util.Locale;
022    
023    import org.apache.hivemind.ApplicationRuntimeException;
024    import org.apache.hivemind.Resource;
025    
026    /**
027     * An implementation of {@link org.apache.hivemind.Resource}
028     * built around a string representation of a URL.
029     *
030     * @author Howard Lewis Ship
031     */
032    public class URLResource extends AbstractResource
033    {
034        private URL _url;
035    
036        public URLResource( URL url )
037        {
038            super( url.toString() );
039            _url = url;
040        }
041    
042        public URLResource( String path )
043        {
044            super( path );
045        }
046    
047        public String toString()
048        {
049            return getPath();
050        }
051    
052        protected Resource newResource( String path )
053        {
054            return new URLResource( path );
055        }
056    
057        public URL getResourceURL()
058        {
059            if( _url == null )
060            {
061                try
062                {
063                    URL test = new URL( getPath() );
064                    InputStream stream = test.openStream();
065                    if( stream != null )
066                    {
067                        stream.close();
068                        _url = test;
069                    }
070                }
071                catch( MalformedURLException ex )
072                {
073                    throw new ApplicationRuntimeException( ex );
074                }
075                catch( IOException ex )
076                {
077                    // If the resource can't be opened,
078                    // then return null.
079                }
080            }
081            return _url;
082        }
083    
084        /**
085         * Always returns this location; no localization check occurs.
086         */
087        public Resource getLocalization( Locale locale )
088        {
089            return this;
090        }
091    }