All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.ajax4jsf.framework.resource.InternetResourceService Maven / Gradle / Ivy

Go to download

Ajax4jsf is an open source extension to the JavaServer Faces standard that adds AJAX capability to JSF applications without requiring the writing of any JavaScript.

The newest version!
package org.ajax4jsf.framework.resource;

import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.Properties;

import javax.faces.FacesException;
import javax.faces.FactoryFinder;
import javax.faces.context.FacesContext;
import javax.faces.context.FacesContextFactory;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.ajax4jsf.framework.ajax.xmlfilter.BaseFilter;
import org.ajax4jsf.framework.ajax.xmlfilter.CacheContent;
import org.ajax4jsf.framework.util.message.Messages;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.opensymphony.oscache.base.Cache;
import com.opensymphony.oscache.base.NeedsRefreshException;
import com.opensymphony.oscache.web.ServletCacheAdministrator;

public class InternetResourceService {
	private static final Log log = LogFactory
			.getLog(InternetResourceService.class);

	static final String ENABLE_CACHING_PARAMETER = "enable-cache";

	private static final String RESOURCE_LIFECYCLE_PARAMETER = "org.ajax4jsf.RESOURCE_LIFECYCLE";

	private FilterConfig filterConfig;

	private boolean cacheEnabled = true;

	private ServletCacheAdministrator cacheAdmin;

	private FacesContextFactory contextFactory;

	// private RenderKitFactory renderKitFactory;
	private String lifecycleClass;
	private ResourceLifecycle lifecycle ;
	
	private InternetResourceBuilder resourceBuilder;

	public InternetResourceService() {
	}

	public void setCacheEnabled(boolean b) {
		cacheEnabled = b;
	}

	public void init(FilterConfig config) throws ServletException {
		filterConfig = config;
		ServletContext servletContext = config.getServletContext();
		if ("false".equalsIgnoreCase(config
				.getInitParameter(ENABLE_CACHING_PARAMETER))) {
			setCacheEnabled(false);
			// this.cacheEnabled = false;
			this.cacheAdmin = null;
		} else {
			// Load our implementation properties
			Properties cacheProperties = getProperties("oscache.properties");
			cacheProperties.putAll(getProperties("/oscache.properties"));
			this.cacheAdmin = ServletCacheAdministrator.getInstance(servletContext, cacheProperties);
		}
		// Create resource builder for this filter.
		resourceBuilder = InternetResourceBuilder.getInstance();
		resourceBuilder.init(servletContext,config.getFilterName());
		// Create Resource-specific Faces Lifecycle instance.
		lifecycleClass = servletContext.getInitParameter(RESOURCE_LIFECYCLE_PARAMETER);
		if(lifecycleClass != null){
			ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
			try {
				Class clazz = classLoader.loadClass(lifecycleClass);
				lifecycle = (ResourceLifecycle) clazz.newInstance();
			} catch (Exception e) {
				throw new FacesException("Error create instance of resource Lifecycle "+lifecycleClass,e);
			}
		} else {
			lifecycle = new ResourceLifecycle();
		}
		contextFactory = (FacesContextFactory) FactoryFinder
		.getFactory(FactoryFinder.FACES_CONTEXT_FACTORY);
		
	}

	public boolean serviceResource(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws ServletException, IOException {
		String resourceKey = resourceBuilder.getFacesResourceKey(httpServletRequest);
		if(null != resourceKey){
			serviceResource(resourceKey,httpServletRequest, httpServletResponse);
			return true;
		}
		return false;
	}

	public void serviceResource(String resourceKey, HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		InternetResource resource;// getInternetResource(request);
		try{
		resource = resourceBuilder.getResourceForKey(resourceKey);
		} catch (ResourceNotFoundException e) {
			throw new ServletException(e);
		}
		Object resourceDataForKey = resourceBuilder.getResourceDataForKey(resourceKey);
		if (resource.isCacheable() && this.cacheEnabled) {
			// Test for client request modification time.
			try {
				long ifModifiedSince = request
						.getDateHeader("If-Modified-Since");
				if (ifModifiedSince >= 0) {
					// Test for modification. 1000 ms due to round modification
					// time to seconds.
					long lastModified = resource.getLastModified().getTime() - 1000;
					if (lastModified <= ifModifiedSince) {
						response.setStatus(304);
						return;
					}
				}
			} catch (IllegalArgumentException e) {
				log
						.warn(
								Messages
										.getMessage(Messages.PARSING_IF_MODIFIED_SINCE_WARNING),
								e);
			}
			String cacheKey = resourceKey ;//+ "?" + request.getQueryString();
			// TODO - select session/application scope.
			Cache cache = cacheAdmin.getAppScopeCache(getServletContext());
			try {
				// TODO - use last modified/expires time
				CacheContent content = (CacheContent) cache
						.getFromCache(cacheKey);
				if (log.isDebugEnabled()) {
					log.debug(Messages.getMessage(
							Messages.GET_CONTENT_FROM_CACHE_INFO, cacheKey));
				}
				content.sendHeaders(response);
				// Correct expires date for resource.
				Date expired = resource.getExpired();
				if (expired != null) {
					response.setDateHeader("Expires", expired.getTime());
				} else {
					response.setDateHeader("Expires", System.currentTimeMillis()
							+ InternetResource.DEFAULT_EXPIRE);
				}
				if (!request.getMethod().equals("HEAD")) {
					content.send(response);
				}
			} catch (NeedsRefreshException e) {
				try {
					if (log.isDebugEnabled()) {
						log.debug(Messages.getMessage(
								Messages.CONTENT_NOT_FOUND_ERROR, cacheKey));
					}
					CachedResourceContext context = (CachedResourceContext) sendResource(
							resource, request, response, resourceDataForKey);
					// TODO - set refresh interval ?
					cache.putInCache(cacheKey, context.getContent());
				} catch (Exception ex) {
					cache.cancelUpdate(cacheKey);
					log.error(
							Messages.getMessage(Messages.SEND_RESOURCE_ERROR),
							ex);
					throw new ServletException(Messages.getMessage(
							Messages.SEND_RESOURCE_ERROR_2, ex.getMessage()),
							ex);
				}
			}
		} else {
			sendResource(resource, request, response, resourceDataForKey);
		}
	}

	/**
	 * @param resource
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	protected ResourceContext sendResource(InternetResource resource,
			HttpServletRequest request, HttpServletResponse response, Object data)
			throws IOException {
		ResourceContext resourceContext = getResourceContext(resource, request, response);
		resourceContext.setResourceData(data);
		getLifecycle().send(resourceContext, resource);
		resourceContext.release();
		return resourceContext;
	}

	/**
	 * @param resource
	 * @param request
	 * @param response
	 * @return
	 * @throws ServletException 
	 * @throws FacesException 
	 */
	protected ResourceContext getResourceContext(InternetResource resource, HttpServletRequest request, HttpServletResponse response) throws FacesException {
		FacesContext facesContext = null;
		ResourceContext resourceContext;
		if (resource.requireFacesContext()) {
			facesContext = getFacesContext(request, response);
			resourceContext = new FacesResourceContext(facesContext);
		} else {
			resourceContext = new ServletResourceContext(getServletContext(),
					request, response);
		}
		if (resource.isCacheable() && this.cacheEnabled) {
			resourceContext = new CachedResourceContext(resourceContext);
		}
		return resourceContext;
	}

	/**
	 * Get properties file from classpath
	 * 
	 * @param name
	 * @return
	 */
	protected Properties getProperties(String name) {
		Properties properties = new Properties();
		InputStream props = BaseFilter.class.getResourceAsStream(name);
		if (null != props) {
			try {
				properties.load(props);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				log.warn(Messages.getMessage(Messages.READING_PROPERTIES_ERROR,
						name), e);
			} finally {
				try {
					props.close();
				} catch (IOException e) {
					// Can be ignored
				}
			}
		}
		return properties;

	}

	/**
	 * @return Returns the servletContext.
	 */
	protected ServletContext getServletContext() {
		return filterConfig.getServletContext();
	}

	
	
	/**
	 * @return the lifecycle
	 * @throws ServletException 
	 */
	protected  ResourceLifecycle getLifecycle() throws FacesException {
		return lifecycle;
	}
	
	

	/**
	 * @return the contextFactory
	 */
	protected FacesContextFactory getContextFactory() {
		return contextFactory;
	}

	protected FacesContext getFacesContext(ServletRequest request,
			ServletResponse response) throws FacesException {
		return getContextFactory().getFacesContext(getServletContext(), request,
				response, getLifecycle());
	}

	/**
	 * @return the resourceBuilder
	 */
	protected  InternetResourceBuilder getResourceBuilder() {
		return resourceBuilder;
	}

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy