001 package com.khubla.pragmatach.framework.resourceloader;
002
003 import java.io.InputStream;
004 import java.util.Map;
005
006 import javax.servlet.ServletContext;
007
008 import org.slf4j.Logger;
009 import org.slf4j.LoggerFactory;
010
011 import com.khubla.pragmatach.framework.api.PragmatachException;
012 import com.khubla.pragmatach.framework.plugin.PluginDescriptor;
013 import com.khubla.pragmatach.framework.plugin.PluginDescriptors;
014
015 /**
016 * @author tome
017 */
018 public class DefaultResourceLoaderImpl implements ResourceLoader {
019 /**
020 * logger
021 */
022 private final Logger logger = LoggerFactory.getLogger(this.getClass());
023 /**
024 * servlet context
025 */
026 private final ServletContext servletContext;
027
028 /**
029 * ctor
030 */
031 public DefaultResourceLoaderImpl(ServletContext servletContext) {
032 this.servletContext = servletContext;
033 }
034
035 /**
036 * get a resource using the servlet's class loader
037 */
038 @Override
039 public InputStream getResource(String resource) throws PragmatachException {
040 try {
041 if ((resource.contains("WEB-INF")) || (resource.contains("META-INF")) || (resource.startsWith("."))) {
042 return null;
043 } else {
044 String resourcePath = resource;
045 if (false == resourcePath.startsWith("/")) {
046 resourcePath = "/" + resourcePath;
047 }
048 /*
049 * try loading from the web app
050 */
051 InputStream ret = servletContext.getResourceAsStream(resourcePath);
052 /*
053 * try loading locally
054 */
055 if (null == ret) {
056 ret = DefaultResourceLoaderImpl.class.getResourceAsStream(resourcePath);
057 }
058 /*
059 * ok, can't find, try the plugins
060 */
061 if (null == ret) {
062 /*
063 * get the plugins
064 */
065 final Map<String, PluginDescriptor> plugins = PluginDescriptors.getPlugins();
066 if (null != plugins) {
067 for (final PluginDescriptor plugin : plugins.values()) {
068 ret = plugin.getResource(resource);
069 if (null != ret) {
070 /*
071 * found it!
072 */
073 break;
074 }
075 }
076 }
077 }
078 /*
079 * unable to find, log that
080 */
081 if (null == ret) {
082 logger.info("Unable to load resource '" + resource + "'");
083 }
084 /*
085 * done
086 */
087 return ret;
088 }
089 } catch (final Exception e) {
090 throw new PragmatachException("Exception in getResource", e);
091 }
092 }
093 }