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 015package org.apache.tapestry.asset; 016 017import java.io.InputStream; 018import java.net.URL; 019 020import org.apache.hivemind.ApplicationRuntimeException; 021import org.apache.hivemind.Location; 022import org.apache.hivemind.Resource; 023import org.apache.hivemind.util.Defense; 024import org.apache.tapestry.IAsset; 025import org.apache.tapestry.IRequestCycle; 026import 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 035public 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 _requestCycle.encodeURL(_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}