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