001 // Copyright 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.web; 016 017 import java.net.MalformedURLException; 018 import java.net.URL; 019 import java.util.List; 020 021 import javax.servlet.ServletContext; 022 023 import org.apache.commons.logging.Log; 024 import org.apache.commons.logging.LogFactory; 025 import org.apache.hivemind.util.Defense; 026 import org.apache.tapestry.describe.DescriptionReceiver; 027 028 /** 029 * Adapts {@link javax.servlet.ServletContext} as {@link org.apache.tapestry.web.WebContext}. 030 * 031 * @author Howard M. Lewis Ship 032 * @since 4.0 033 */ 034 public class ServletWebContext implements WebContext 035 { 036 private static final Log LOG = LogFactory.getLog(ServletWebContext.class); 037 038 private final ServletContext _servletContext; 039 040 public void describeTo(DescriptionReceiver receiver) 041 { 042 receiver.describeAlternate(_servletContext); 043 } 044 045 public ServletWebContext(ServletContext context) 046 { 047 Defense.notNull(context, "context"); 048 049 _servletContext = context; 050 } 051 052 public List getAttributeNames() 053 { 054 return WebUtils.toSortedList(_servletContext.getAttributeNames()); 055 } 056 057 public Object getAttribute(String name) 058 { 059 return _servletContext.getAttribute(name); 060 } 061 062 public void setAttribute(String name, Object attribute) 063 { 064 if (attribute == null) 065 _servletContext.removeAttribute(name); 066 else 067 _servletContext.setAttribute(name, attribute); 068 069 } 070 071 public URL getResource(String path) 072 { 073 try 074 { 075 return _servletContext.getResource(path); 076 } 077 catch (MalformedURLException ex) 078 { 079 LOG.error(WebMessages.errorGettingResource(path, ex), ex); 080 081 return null; 082 } 083 } 084 085 public String getInitParameterValue(String name) 086 { 087 return _servletContext.getInitParameter(name); 088 } 089 090 public List getInitParameterNames() 091 { 092 return WebUtils.toSortedList(_servletContext.getInitParameterNames()); 093 } 094 095 public String getMimeType(String resourcePath) 096 { 097 return _servletContext.getMimeType(resourcePath); 098 } 099 }