package com.hammurapi.web;

import java.io.IOException;
import java.io.InputStream;

import javax.servlet.ServletContext;

import org.onemind.jxp.CachedJxpPage;
import org.onemind.jxp.CachingPageSource;

public class ServletContextResourceStreamPageSource extends CachingPageSource {

    private ServletContext context;
	private String contextPath;

    public ServletContextResourceStreamPageSource(ServletContext context) {
        this.context = context;
        this.contextPath = context.getContextPath();
    }

    protected boolean isExpired(CachedJxpPage page) {
        return false;
    }

    protected boolean hasStream(String pageName) {
    	return context.getResourceAsStream(normalizePageName(pageName))!=null;
    }

	private String normalizePageName(String pageName) {
		String normalized = "/".equals(contextPath)? pageName : pageName.substring(contextPath.length()+1);
		return normalized.startsWith("/") ? normalized : "/"+normalized;
	}

    protected InputStream loadStream(CachedJxpPage page) throws IOException {
    	return context.getResourceAsStream(normalizePageName(page.getName()));
    }
}