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 org.apache.hivemind.ApplicationRuntimeException; 018 import org.apache.hivemind.Location; 019 import org.apache.hivemind.Resource; 020 import org.apache.hivemind.util.Defense; 021 import org.apache.tapestry.IAsset; 022 import org.apache.tapestry.IRequestCycle; 023 import org.apache.tapestry.Tapestry; 024 025 import java.io.InputStream; 026 import java.net.URL; 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 private IRequestCycle _requestCycle; 042 043 public ContextAsset(String contextPath, Resource resource, Location location, IRequestCycle cycle) 044 { 045 super(resource, location); 046 047 Defense.notNull(contextPath, "contextPath"); 048 049 _contextPath = contextPath; 050 051 _requestCycle = cycle; 052 } 053 054 /** 055 * Generates a URL for the client to retrieve the asset. The context path is prepended to the 056 * asset path, which means that assets deployed inside web applications will still work (if 057 * things are configured properly). 058 */ 059 060 public String buildURL() 061 { 062 if (_resolvedURL == null) 063 _resolvedURL = _contextPath + getResourceLocation().getPath(); 064 065 return _resolvedURL; 066 } 067 068 public InputStream getResourceAsStream() 069 { 070 try 071 { 072 URL url = getResourceLocation().getResourceURL(); 073 074 return url.openStream(); 075 } 076 catch (Exception ex) 077 { 078 throw new ApplicationRuntimeException(Tapestry.format( 079 "ContextAsset.resource-missing", 080 getResourceLocation()), ex); 081 } 082 } 083 }