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.tapestry.asset;
016    
017    import java.io.InputStream;
018    import java.net.URL;
019    
020    import org.apache.hivemind.ApplicationRuntimeException;
021    import org.apache.hivemind.Location;
022    import org.apache.hivemind.Resource;
023    import org.apache.hivemind.util.Defense;
024    import org.apache.tapestry.IAsset;
025    import org.apache.tapestry.Tapestry;
026    
027    /**
028     * An asset whose path is relative to the {@link javax.servlet.ServletContext}containing the
029     * application.
030     * 
031     * @author Howard Lewis Ship
032     */
033    
034    public class ContextAsset extends AbstractAsset implements IAsset
035    {
036        private String _contextPath;
037    
038        private String _resolvedURL;
039    
040        public ContextAsset(String contextPath, Resource resource, Location location)
041        {
042            super(resource, location);
043    
044            Defense.notNull(contextPath, "contextPath");
045    
046            _contextPath = contextPath;
047        }
048    
049        /**
050         * Generates a URL for the client to retrieve the asset. The context path is prepended to the
051         * asset path, which means that assets deployed inside web applications will still work (if
052         * things are configured properly).
053         */
054    
055        public String buildURL()
056        {
057            if (_resolvedURL == null)
058                _resolvedURL = _contextPath + getResourceLocation().getPath();
059    
060            return _resolvedURL;
061        }
062    
063        public InputStream getResourceAsStream()
064        {
065            try
066            {
067                URL url = getResourceLocation().getResourceURL();
068    
069                return url.openStream();
070            }
071            catch (Exception ex)
072            {
073                throw new ApplicationRuntimeException(Tapestry.format(
074                        "ContextAsset.resource-missing",
075                        getResourceLocation()), ex);
076            }
077        }
078    }