001/* 002 * (C) Copyright 2011 Nuxeo SA (http://nuxeo.com/) and others. 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * http://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 * 016 * Contributors: 017 * Florent Guillaume 018 */ 019package org.nuxeo.theme.html.servlets; 020 021import java.io.InputStream; 022import java.net.MalformedURLException; 023import java.net.URL; 024 025import javax.servlet.ServletContext; 026import javax.servlet.ServletContextEvent; 027import javax.servlet.ServletContextListener; 028 029import org.nuxeo.theme.ResourceResolver; 030 031/** 032 * Resolver for resources that checks the servlet context first. 033 * 034 * @since 5.5 035 */ 036public class ServletResourceResolver extends ResourceResolver implements ServletContextListener { 037 038 protected ServletContext servletContext; 039 040 @Override 041 public URL getResource(String path) { 042 try { 043 URL url = servletContext.getResource("/" + path); 044 if (url != null) { 045 return url; 046 } 047 } catch (MalformedURLException e) { 048 // continue 049 } 050 return super.getResource(path); 051 } 052 053 @Override 054 public InputStream getResourceAsStream(String path) { 055 InputStream is = servletContext.getResourceAsStream("/" + path); 056 if (is != null) { 057 return is; 058 } 059 return super.getResourceAsStream(path); 060 } 061 062 @Override 063 public void contextInitialized(ServletContextEvent sce) { 064 servletContext = sce.getServletContext(); 065 ResourceResolver.setInstance(this); 066 } 067 068 @Override 069 public void contextDestroyed(ServletContextEvent sce) { 070 servletContext = null; 071 ResourceResolver.setInstance(null); 072 } 073 074}