Author: alexsmirnov
Date: 2007-04-17 20:59:13 -0400 (Tue, 17 Apr 2007)
New Revision: 94
Modified:
trunk/a4j-portlet/src/main/java/org/ajax4jsf/portlet/application/PortletViewHandler.java
trunk/framework/src/main/java/org/ajax4jsf/framework/DebugLifecycleFactory.java
trunk/framework/src/main/java/org/ajax4jsf/framework/ajax/AjaxScript.java
trunk/framework/src/main/java/org/ajax4jsf/framework/ajax/AjaxViewHandler.java
trunk/framework/src/main/java/org/ajax4jsf/framework/ajax/xmlfilter/BaseFilter.java
trunk/framework/src/main/java/org/ajax4jsf/framework/ajax/xmlfilter/BaseXMLFilter.java
trunk/framework/src/main/java/org/ajax4jsf/framework/renderer/ChameleonRenderKitFactory.java
trunk/framework/src/main/java/org/ajax4jsf/framework/resource/InternetResourceBuilder.java
trunk/framework/src/main/java/org/ajax4jsf/framework/resource/InternetResourceService.java
trunk/framework/src/main/java/org/ajax4jsf/framework/resource/ResourceBuilderImpl.java
trunk/framework/src/main/java/org/ajax4jsf/framework/resource/cached/CachedResourceBuilder.java
trunk/framework/src/main/java/org/ajax4jsf/framework/util/base64/Codec.java
trunk/framework/src/main/java/org/ajax4jsf/framework/util/config/WebXml.java
Log:
First start of portlet sample.
Modified:
trunk/a4j-portlet/src/main/java/org/ajax4jsf/portlet/application/PortletViewHandler.java
===================================================================
---
trunk/a4j-portlet/src/main/java/org/ajax4jsf/portlet/application/PortletViewHandler.java 2007-04-17
21:04:13 UTC (rev 93)
+++
trunk/a4j-portlet/src/main/java/org/ajax4jsf/portlet/application/PortletViewHandler.java 2007-04-18
00:59:13 UTC (rev 94)
@@ -34,4 +34,8 @@
return super.getActionURL(context, url);
}
}
+
+ protected synchronized void fillChain(FacesContext context) {
+ // Do nothing - chain must be filled in AjaxViewHandler
+ }
}
Modified: trunk/framework/src/main/java/org/ajax4jsf/framework/DebugLifecycleFactory.java
===================================================================
---
trunk/framework/src/main/java/org/ajax4jsf/framework/DebugLifecycleFactory.java 2007-04-17
21:04:13 UTC (rev 93)
+++
trunk/framework/src/main/java/org/ajax4jsf/framework/DebugLifecycleFactory.java 2007-04-18
00:59:13 UTC (rev 94)
@@ -26,12 +26,18 @@
import javax.faces.lifecycle.Lifecycle;
import javax.faces.lifecycle.LifecycleFactory;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
/**
* @author shura (latest modification by $Author: alexsmirnov $)
* @version $Revision: 1.1.2.1 $ $Date: 2007/01/09 18:57:12 $
*
*/
public class DebugLifecycleFactory extends LifecycleFactory {
+
+ private static final Log _log = LogFactory
+ .getLog(DebugLifecycleFactory.class);
private LifecycleFactory _defaultFactory;
@@ -46,7 +52,6 @@
if (_debugLifecycle == null) {
_debugLifecycle = new DebugLifecycle(_defaultFactory);
}
-
return _debugLifecycle;
}
@@ -56,13 +61,19 @@
public DebugLifecycleFactory(LifecycleFactory defaultFactory) {
super();
this._defaultFactory = defaultFactory;
+ if (_log.isDebugEnabled()) {
+ _log.debug("Created Lifecycle instance");
+ }
}
/* (non-Javadoc)
* @see javax.faces.lifecycle.LifecycleFactory#addLifecycle(java.lang.String,
javax.faces.lifecycle.Lifecycle)
*/
- public void addLifecycle(String arg0, Lifecycle arg1) {
- this._defaultFactory.addLifecycle(arg0, arg1);
+ public void addLifecycle(String lifecycleId, Lifecycle lifecycle) {
+ this._defaultFactory.addLifecycle(lifecycleId, lifecycle);
+ if (_log.isDebugEnabled()) {
+ _log.debug("Added lifecycle with ID "+lifecycleId);
+ }
}
/* (non-Javadoc)
Modified: trunk/framework/src/main/java/org/ajax4jsf/framework/ajax/AjaxScript.java
===================================================================
--- trunk/framework/src/main/java/org/ajax4jsf/framework/ajax/AjaxScript.java 2007-04-17
21:04:13 UTC (rev 93)
+++ trunk/framework/src/main/java/org/ajax4jsf/framework/ajax/AjaxScript.java 2007-04-18
00:59:13 UTC (rev 94)
@@ -21,6 +21,9 @@
package org.ajax4jsf.framework.ajax;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
import org.ajax4jsf.framework.resource.ClientScript;
/**
@@ -30,15 +33,18 @@
*
*/
public class AjaxScript extends ClientScript {
+
+ private static final Log _log = LogFactory.getLog(AjaxScript.class);
/**
* Set JavaScript renderer and modification time to application-startup time.
*/
public AjaxScript() {
super();
-// setRenderer(new ScriptRenderer());
-// setLastModified(new Date(InternetResourceBuilder.getInstance().getStartTime()));
+ if (_log.isDebugEnabled()) {
+ _log.debug("AjaxScript() - Created instance of AjaxScript resource");
//$NON-NLS-1$
}
+ }
/**
Modified: trunk/framework/src/main/java/org/ajax4jsf/framework/ajax/AjaxViewHandler.java
===================================================================
---
trunk/framework/src/main/java/org/ajax4jsf/framework/ajax/AjaxViewHandler.java 2007-04-17
21:04:13 UTC (rev 93)
+++
trunk/framework/src/main/java/org/ajax4jsf/framework/ajax/AjaxViewHandler.java 2007-04-18
00:59:13 UTC (rev 94)
@@ -63,6 +63,9 @@
*/
public AjaxViewHandler(ViewHandler parent) {
super(parent);
+ if (_log.isDebugEnabled()) {
+ _log.debug("Create instance of Ajax ViewHandler");
+ }
}
/*
Modified:
trunk/framework/src/main/java/org/ajax4jsf/framework/ajax/xmlfilter/BaseFilter.java
===================================================================
---
trunk/framework/src/main/java/org/ajax4jsf/framework/ajax/xmlfilter/BaseFilter.java 2007-04-17
21:04:13 UTC (rev 93)
+++
trunk/framework/src/main/java/org/ajax4jsf/framework/ajax/xmlfilter/BaseFilter.java 2007-04-18
00:59:13 UTC (rev 94)
@@ -24,6 +24,7 @@
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Date;
+import java.util.Enumeration;
import javax.faces.application.ViewHandler;
import javax.servlet.Filter;
@@ -44,282 +45,316 @@
import org.apache.commons.logging.LogFactory;
/**
- * Base class for request processing filters, with convert Htmp content to
- * XML for ajax requests, and serve request to application off-page resources
+ * Base class for request processing filters, with convert Htmp content to XML
+ * for ajax requests, and serve request to application off-page resources
+ *
* @author shura (latest modification by $Author: alexsmirnov $)
* @version $Revision: 1.1.2.1 $ $Date: 2007/01/09 18:58:21 $
- *
+ *
*/
public abstract class BaseFilter implements Filter {
- private static final Log log = LogFactory.getLog(BaseFilter.class);
- public static final boolean DEBUG = true;
- private FilterConfig filterConfig;
- private static final String FUNCTION_NAME_PARAMETER = "function";
- private String function = "alert('Data
received');JSHttpRequest.dataReady";
- private String attributesNames;
- private boolean rewriteid = false;
- private static final String REWRITEID_PARAMETER = "rewriteid";
- private static final String STYLESHEET_PARAMETER = "xsl";
- private static final String ABSOLUTE_TAGS_PARAMETER = "absolute-attributes";
-// private WebXml webXml;
-// private String xsl;
-// private Templates xslTemplates;
- /**
- *
- */
- private static final long serialVersionUID = -2295534611886142935L;
- public static final String DATA_PARAMETER = "DATA";
- public static final String DEFAULT_SERVLET_PATH = "/resource";
- public static final String RENDERER_PREFIX = "/renderer";
- public static final String CACHEABLE_PREFIX = "/cache";
-// private static final Pattern rendererPattern =
Pattern.compile(RENDERER_PREFIX+"/([^/]+)/([^/]+)/([^/]+)/(.*)");
-// private static final Pattern builderPattern =
Pattern.compile(CACHEABLE_PREFIX+"/(.*)");
- public static final String FILTER_PERFORMED = "com.exade.vcp.Filter.done";
- public static final String RESPONSE_WRAPPER_ATTRIBUTE =
"com.exade.vcp.Filter.ResponseWrapper";
-
- protected BaseXMLFilter xmlFilter = null;
- InternetResourceService resourceService = null;
+ private static final Log log = LogFactory.getLog(BaseFilter.class);
+ public static final boolean DEBUG = true;
- /**
- * Initialize the filter.
- */
- public void init(FilterConfig config) throws ServletException {
- // Save config
- filterConfig = config;
- setFunction((String)
nz(filterConfig.getInitParameter(FUNCTION_NAME_PARAMETER),getFunction()));
- setAttributesNames(filterConfig.getInitParameter(ABSOLUTE_TAGS_PARAMETER));
- // if( null != attributesNames){
- // this.absoluteAttributes = attributesNames.split(",");
- // }
- xmlFilter.init(config);
-// xsl = config.getInitParameter(STYLESHEET_PARAMETER);
-
if("true".equalsIgnoreCase(filterConfig.getInitParameter(REWRITEID_PARAMETER))){
- this.setRewriteid(true);
- }
-
- // TODO - make all parameters configurable ...
- // Get Nekko parser features & properties.
- // Configure faces variables and log.
-// renderKitFactory = (RenderKitFactory)
FactoryFinder.getFactory(FactoryFinder.RENDER_KIT_FACTORY);
- // InternetResourceBuilder.getInstance().setServletContext(getServletContext());
- // Log4J configuration. TODO - test for already configured logging.
-
- String prefix = filterConfig.getServletContext().getRealPath("/");
- String file = filterConfig.getInitParameter("log4j-init-file");
- // if the log4j-init-file is not set, then no point in trying
- if (file != null) {
- Log4JConfigurator log4jconfig = new Log4JConfigurator(prefix);
- log4jconfig.doConfigure(file);
- }
- // init webXml configuration.
-// WebXml.init(config.getServletContext(),config.getFilterName());
-// this.webXml = WebXml.getInstance();
- }
+ private FilterConfig filterConfig;
- /**
- * @param httpServletRequest
- * @throws UnsupportedEncodingException
- */
- protected void setupRequestEncoding(HttpServletRequest httpServletRequest) throws
UnsupportedEncodingException {
- String contentType = httpServletRequest.getHeader("Content-Type");
-
- String characterEncoding = lookupCharacterEncoding(contentType);
-
- if (characterEncoding == null) {
- HttpSession session = httpServletRequest.getSession(false);
-
- if (session != null) {
- characterEncoding = (String)
session.getAttribute(ViewHandler.CHARACTER_ENCODING_KEY);
- }
-
- if (characterEncoding != null) {
- httpServletRequest.setCharacterEncoding(characterEncoding);
- }
- }
- }
+ private static final String FUNCTION_NAME_PARAMETER = "function";
- /**
- * Detect request encoding from Content-Type header
- * @param contentType
- * @return - charset, if present.
- */
- private String lookupCharacterEncoding(String contentType) {
- String characterEncoding = null;
-
- if (contentType != null)
- {
- int charsetFind = contentType.indexOf("charset=");
- if (charsetFind != -1)
- {
- if (charsetFind == 0)
- {
- //charset at beginning of Content-Type, curious
- characterEncoding = contentType.substring(8);
- }
- else
- {
- char charBefore = contentType.charAt(charsetFind - 1);
- if (charBefore == ';' || Character.isWhitespace(charBefore))
- {
- //Correct charset after mime type
- characterEncoding = contentType.substring(charsetFind + 8);
- }
- }
- if (log.isDebugEnabled())
log.debug(Messages.getMessage(Messages.CONTENT_TYPE_ENCODING, characterEncoding));
- }
- else
- {
- if (log.isDebugEnabled())
log.debug(Messages.getMessage(Messages.CONTENT_TYPE_NO_ENCODING, contentType));
- }
+ private String function = "alert('Data
received');JSHttpRequest.dataReady";
+
+ private String attributesNames;
+
+ private boolean rewriteid = false;
+
+ private static final String REWRITEID_PARAMETER = "rewriteid";
+
+ private static final String STYLESHEET_PARAMETER = "xsl";
+
+ private static final String ABSOLUTE_TAGS_PARAMETER =
"absolute-attributes";
+
+ // private WebXml webXml;
+ // private String xsl;
+ // private Templates xslTemplates;
+ /**
+ *
+ */
+ private static final long serialVersionUID = -2295534611886142935L;
+
+ public static final String DATA_PARAMETER = "DATA";
+
+ public static final String DEFAULT_SERVLET_PATH = "/resource";
+
+ public static final String RENDERER_PREFIX = "/renderer";
+
+ public static final String CACHEABLE_PREFIX = "/cache";
+
+ // private static final Pattern rendererPattern =
+ // Pattern.compile(RENDERER_PREFIX+"/([^/]+)/([^/]+)/([^/]+)/(.*)");
+ // private static final Pattern builderPattern =
+ // Pattern.compile(CACHEABLE_PREFIX+"/(.*)");
+ public static final String FILTER_PERFORMED = "com.exade.vcp.Filter.done";
+
+ public static final String RESPONSE_WRAPPER_ATTRIBUTE =
"com.exade.vcp.Filter.ResponseWrapper";
+
+ protected BaseXMLFilter xmlFilter = null;
+
+ InternetResourceService resourceService = null;
+
+ /**
+ * Initialize the filter.
+ */
+ public void init(FilterConfig config) throws ServletException {
+ if(log.isDebugEnabled()){
+ log.debug("Init ajax4jsf filter with nane: "+config.getFilterName());
+ Enumeration parameterNames = config.getInitParameterNames();
+ StringBuffer parameters = new StringBuffer("Init parameters :\n");
+ while (parameterNames.hasMoreElements()) {
+ String name = (String) parameterNames.nextElement();
+ parameters.append(name).append(" :
'").append(config.getInitParameter(name)).append('\n');
}
- return characterEncoding;
+ log.debug(parameters);
+ log.debug("Stack Trace", new Exception());
}
+ // Save config
+ filterConfig = config;
+ setFunction((String) nz(filterConfig
+ .getInitParameter(FUNCTION_NAME_PARAMETER), getFunction()));
+ setAttributesNames(filterConfig
+ .getInitParameter(ABSOLUTE_TAGS_PARAMETER));
+ xmlFilter.init(config);
+ if ("true".equalsIgnoreCase(filterConfig
+ .getInitParameter(REWRITEID_PARAMETER))) {
+ this.setRewriteid(true);
+ }
- /**
- * @param initParameter
- * @param function2
- * @return
- */
- private Object nz(Object param, Object def) {
- return param != null?param:def;
+ String prefix = filterConfig.getServletContext().getRealPath("/");
+ String file = filterConfig.getInitParameter("log4j-init-file");
+ // if the log4j-init-file is not set, then no point in trying
+ if (file != null) {
+ Log4JConfigurator log4jconfig = new Log4JConfigurator(prefix);
+ log4jconfig.doConfigure(file);
}
+ resourceService = new InternetResourceService();
+ // Caching initialization.
+ resourceService.init(filterConfig);
+ }
- /**
- * Execute the filter.
- */
- public void doFilter(ServletRequest request, ServletResponse response, FilterChain
chain) throws IOException, ServletException {
- long startTimeMills =0;
- // Detect case of request - normal, AJAX, AJAX - JavaScript
- // TODO - detect first processing in filter.
- HttpServletRequest httpServletRequest =(HttpServletRequest) request;
- HttpServletResponse httpServletResponse = (HttpServletResponse) response;
- if (log.isDebugEnabled()) {
- startTimeMills = System.currentTimeMillis();
- log.debug(Messages.getMessage(Messages.FILTER_START_INFO, new Date(startTimeMills),
httpServletRequest.getRequestURI()));
- }
+ /**
+ * @param httpServletRequest
+ * @throws UnsupportedEncodingException
+ */
+ protected void setupRequestEncoding(HttpServletRequest httpServletRequest)
+ throws UnsupportedEncodingException {
+ String contentType = httpServletRequest.getHeader("Content-Type");
- if ( request.getAttribute(FILTER_PERFORMED) != Boolean.TRUE) {
- // mark - and not processing same request twice.
- request.setAttribute(FILTER_PERFORMED,Boolean.TRUE);
- // check for resource request
- if ( ! getResourceService().serviceResource( httpServletRequest,
- httpServletResponse) ) {
- // Not request to resource - perform filtering.
- // first stage - detect/set encoding of request. Same as in Myfaces External
Context.
- setupRequestEncoding(httpServletRequest);
- // check ajax request parameter
- // TODO - check for JSF page.
- if (true) {
- if (log.isDebugEnabled()) {
- log.debug(Messages.getMessage(Messages.FILTER_XML_OUTPUT));
- }
+ String characterEncoding = lookupCharacterEncoding(contentType);
- // Execute the rest of the filter chain, including the JSP
- xmlFilter.doXmlFilter(chain, httpServletRequest, httpServletResponse);
- } else {
- // normal request, execute chain ...
- if (log.isDebugEnabled()) {
- log.debug(Messages.getMessage(Messages.FILTER_NO_XML_CHAIN));
- }
- chain.doFilter(request, response);
+ if (characterEncoding == null) {
+ HttpSession session = httpServletRequest.getSession(false);
- }
- }
- } else {
- if (log.isDebugEnabled()) {
- log.debug(Messages.getMessage(Messages.FILTER_NO_XML_CHAIN_2));
- }
- chain.doFilter(request, response);
+ if (session != null) {
+ characterEncoding = (String) session
+ .getAttribute(ViewHandler.CHARACTER_ENCODING_KEY);
+ }
- }
- if (log.isDebugEnabled()) {
- startTimeMills = System.currentTimeMillis()-startTimeMills;
- log.debug(Messages.getMessage(Messages.FILTER_STOP_INFO, "" +
startTimeMills, httpServletRequest.getRequestURI()));
- }
+ if (characterEncoding != null) {
+ httpServletRequest.setCharacterEncoding(characterEncoding);
+ }
}
+ }
- /**
- * @param request
- * @return
- */
- protected boolean isAjaxRequest(ServletRequest request) {
- try {
- return null != request
- .getParameter(AjaxContainerRenderer.AJAX_PARAMETER_NAME);
- } catch (Exception e) {
- // OCJ 10 - throw exception for static resources.
- return false;
+ /**
+ * Detect request encoding from Content-Type header
+ *
+ * @param contentType
+ * @return - charset, if present.
+ */
+ private String lookupCharacterEncoding(String contentType) {
+ String characterEncoding = null;
+
+ if (contentType != null) {
+ int charsetFind = contentType.indexOf("charset=");
+ if (charsetFind != -1) {
+ if (charsetFind == 0) {
+ // charset at beginning of Content-Type, curious
+ characterEncoding = contentType.substring(8);
+ } else {
+ char charBefore = contentType.charAt(charsetFind - 1);
+ if (charBefore == ';' || Character.isWhitespace(charBefore)) {
+ // Correct charset after mime type
+ characterEncoding = contentType
+ .substring(charsetFind + 8);
+ }
}
+ if (log.isDebugEnabled())
+ log.debug(Messages.getMessage(
+ Messages.CONTENT_TYPE_ENCODING, characterEncoding));
+ } else {
+ if (log.isDebugEnabled())
+ log.debug(Messages.getMessage(
+ Messages.CONTENT_TYPE_NO_ENCODING, contentType));
+ }
}
+ return characterEncoding;
+ }
- /**
- * Destroy the filter.
- */
- public void destroy() {
- }
+ /**
+ * @param initParameter
+ * @param function2
+ * @return
+ */
+ private Object nz(Object param, Object def) {
+ return param != null ? param : def;
+ }
- /**
- * @return Returns the servletContext.
- */
- ServletContext getServletContext() {
- return filterConfig.getServletContext();
+ /**
+ * Execute the filter.
+ */
+ public void doFilter(ServletRequest request, ServletResponse response,
+ FilterChain chain) throws IOException, ServletException {
+ long startTimeMills = 0;
+ // Detect case of request - normal, AJAX, AJAX - JavaScript
+ // TODO - detect first processing in filter.
+ HttpServletRequest httpServletRequest = (HttpServletRequest) request;
+ HttpServletResponse httpServletResponse = (HttpServletResponse) response;
+ if (log.isDebugEnabled()) {
+ startTimeMills = System.currentTimeMillis();
+ log.debug(Messages.getMessage(Messages.FILTER_START_INFO, new Date(
+ startTimeMills), httpServletRequest.getRequestURI()));
}
- /**
- * @return the resourceService
- * @throws ServletException
- */
- protected synchronized InternetResourceService getResourceService() throws
ServletException {
- if (resourceService == null) {
- resourceService = new InternetResourceService();
- // Caching initialization.
- resourceService.init(filterConfig);
-
+ if (request.getAttribute(FILTER_PERFORMED) != Boolean.TRUE) {
+ // mark - and not processing same request twice.
+ request.setAttribute(FILTER_PERFORMED, Boolean.TRUE);
+ // check for resource request
+ if (!getResourceService().serviceResource(httpServletRequest,
+ httpServletResponse)) {
+ // Not request to resource - perform filtering.
+ // first stage - detect/set encoding of request. Same as in
+ // Myfaces External Context.
+ setupRequestEncoding(httpServletRequest);
+ // check ajax request parameter
+ // TODO - check for JSF page.
+ if (true) {
+ if (log.isDebugEnabled()) {
+ log.debug(Messages
+ .getMessage(Messages.FILTER_XML_OUTPUT));
+ }
+
+ // Execute the rest of the filter chain, including the
+ // JSP
+ xmlFilter.doXmlFilter(chain, httpServletRequest,
+ httpServletResponse);
+ } else {
+ // normal request, execute chain ...
+ if (log.isDebugEnabled()) {
+ log.debug(Messages
+ .getMessage(Messages.FILTER_NO_XML_CHAIN));
+ }
+ chain.doFilter(request, response);
+
}
- return resourceService;
- }
+ }
+ } else {
+ if (log.isDebugEnabled()) {
+ log.debug(Messages.getMessage(Messages.FILTER_NO_XML_CHAIN_2));
+ }
+ chain.doFilter(request, response);
- /**
- * @param function The function to set.
- */
- protected void setFunction(String function) {
- this.function = function;
}
-
- /**
- * @return Returns the function.
- */
- protected String getFunction() {
- return function;
+ if (log.isDebugEnabled()) {
+ startTimeMills = System.currentTimeMillis() - startTimeMills;
+ log.debug(Messages.getMessage(Messages.FILTER_STOP_INFO, ""
+ + startTimeMills, httpServletRequest.getRequestURI()));
}
+ }
- /**
- * @param rewriteid The rewriteid to set.
- */
- protected void setRewriteid(boolean rewriteid) {
- this.rewriteid = rewriteid;
+ /**
+ * @param request
+ * @return
+ */
+ protected boolean isAjaxRequest(ServletRequest request) {
+ try {
+ return null != request
+ .getParameter(AjaxContainerRenderer.AJAX_PARAMETER_NAME);
+ } catch (Exception e) {
+ // OCJ 10 - throw exception for static resources.
+ return false;
}
+ }
- /**
- * @return Returns the rewriteid.
- */
- protected boolean isRewriteid() {
- return rewriteid;
- }
+ /**
+ * Destroy the filter.
+ */
+ public void destroy() {
+ }
- /**
- * @param attributesNames The attributesNames to set.
- */
- protected void setAttributesNames(String attributesNames) {
- this.attributesNames = attributesNames;
- }
+ /**
+ * @return Returns the servletContext.
+ */
+ ServletContext getServletContext() {
+ return filterConfig.getServletContext();
+ }
- /**
- * @return Returns the attributesNames.
- */
- protected String getAttributesNames() {
- return attributesNames;
- }
+ /**
+ * @return the resourceService
+ * @throws ServletException
+ */
+ protected synchronized InternetResourceService getResourceService()
+ throws ServletException {
+// if (resourceService == null) {
+// resourceService = new InternetResourceService();
+// // Caching initialization.
+// resourceService.init(filterConfig);
+//
+// }
+ return resourceService;
+ }
+
+ /**
+ * @param function
+ * The function to set.
+ */
+ protected void setFunction(String function) {
+ this.function = function;
+ }
+
+ /**
+ * @return Returns the function.
+ */
+ protected String getFunction() {
+ return function;
+ }
+
+ /**
+ * @param rewriteid
+ * The rewriteid to set.
+ */
+ protected void setRewriteid(boolean rewriteid) {
+ this.rewriteid = rewriteid;
+ }
+
+ /**
+ * @return Returns the rewriteid.
+ */
+ protected boolean isRewriteid() {
+ return rewriteid;
+ }
+
+ /**
+ * @param attributesNames
+ * The attributesNames to set.
+ */
+ protected void setAttributesNames(String attributesNames) {
+ this.attributesNames = attributesNames;
+ }
+
+ /**
+ * @return Returns the attributesNames.
+ */
+ protected String getAttributesNames() {
+ return attributesNames;
+ }
}
Modified:
trunk/framework/src/main/java/org/ajax4jsf/framework/ajax/xmlfilter/BaseXMLFilter.java
===================================================================
---
trunk/framework/src/main/java/org/ajax4jsf/framework/ajax/xmlfilter/BaseXMLFilter.java 2007-04-17
21:04:13 UTC (rev 93)
+++
trunk/framework/src/main/java/org/ajax4jsf/framework/ajax/xmlfilter/BaseXMLFilter.java 2007-04-18
00:59:13 UTC (rev 94)
@@ -45,304 +45,366 @@
import org.apache.commons.logging.LogFactory;
public abstract class BaseXMLFilter {
- private static final Log log = LogFactory.getLog(BaseXMLFilter.class);
- public static final String RESPONSE_WRAPPER_ATTRIBUTE =
"com.exade.vcp.Filter.ResponseWrapper";
+ private static final Log log = LogFactory.getLog(BaseXMLFilter.class);
- private String mimetype = "text/xml";
- private String publicid = "-//W3C//DTD XHTML 1.0 Transitional//EN";
- private String systemid =
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd";
- private String namespace = "http://www.w3.org/1999/xhtml";
+ public static final String RESPONSE_WRAPPER_ATTRIBUTE =
"com.exade.vcp.Filter.ResponseWrapper";
- private static final String MIME_TYPE_PARAMETER = "mime-type";
- private static final String PUBLICID_PARAMETER = "publicid";
- private static final String SYSTEMID_PARAMETER = "systemid";
- private static final String NAMESPACE_PARAMETER = "namespace";
-
- private boolean forcexml = false;
- private static final String FORCEXML_PARAMETER = "forceparser";
- public BaseFilter filter;
-
- public void setFilter(BaseFilter filter) {
- this.filter = filter;
- }
+ private String mimetype = "text/xml";
- public void init(FilterConfig config) throws ServletException {
-
if("false".equalsIgnoreCase(config.getInitParameter(FORCEXML_PARAMETER))){
- this.forcexml = false;
- }
-
if("true".equalsIgnoreCase(config.getInitParameter(FORCEXML_PARAMETER))){
- this.forcexml = true;
- }
- setMimetype((String)
nz(config.getInitParameter(MIME_TYPE_PARAMETER),"text/xml"));
- setPublicid((String)
nz(config.getInitParameter(PUBLICID_PARAMETER),getPublicid()));
- setSystemid((String)
nz(config.getInitParameter(SYSTEMID_PARAMETER),getSystemid()));
- setNamespace((String)
nz(config.getInitParameter(NAMESPACE_PARAMETER),getNamespace()));
- }
+ private String publicid = "-//W3C//DTD XHTML 1.0 Transitional//EN";
- /**
- * Perform filter chain with xml parsing and transformation. Subclasses must implement
- * concrete HTML to XML parsing, nesseasary transformations and serialization.
- * @param chain
- * @param httpServletRequest
- * @param httpServletResponse
- * @throws ServletException
- * @throws IOException
- */
- protected void doXmlFilter(FilterChain chain, HttpServletRequest request, final
HttpServletResponse response) throws IOException, ServletException {
- FilterServletResponseWrapper servletResponseWrapper = getWrapper(response);
- // HACK - to avoid MyFaces <f:view> incompabilites and bypass intermediaty
filters
- // in chain, self-rendered region write directly to wrapper stored in request-scope
attribute.
- request.setAttribute(RESPONSE_WRAPPER_ATTRIBUTE,servletResponseWrapper);
- chain.doFilter(request, servletResponseWrapper);
- // TidyParser parser = getParser(servletResponseWrapper.getCharacterEncoding());
- HtmlParser parser = null;
- // setup response
- // Redirect in AJAX request - convert to special response recognized by client.
- String redirectLocation = servletResponseWrapper.getRedirectLocation();
- String characterEncoding = servletResponseWrapper.getCharacterEncoding();
- Writer output;
- if(null != redirectLocation){
- if (isAjaxRequest(request)) {
- // Special handling of redirect - client-side script must
- // Check for response and perform redirect by window.location
- if(log.isDebugEnabled()){
- log.debug("Create AJAX redirect response to url: "+redirectLocation);
- }
- response.reset();
- // Copy response headers
- Map headers = servletResponseWrapper.getHeaders();
- for (Iterator iter = headers.entrySet().iterator(); iter.hasNext();) {
- Map.Entry header = (Map.Entry) iter.next();
- response.setHeader((String)header.getKey(), (String)header.getValue());
- }
- response.setHeader(AjaxContainerRenderer.AJAX_FLAG_HEADER,"redirect");
- // Not caching AJAX request
- response.setHeader("Cache-Control",
- "no-cache, must-revalidate, max_age=0, no-store");
- response.setHeader("Expires", "0");
- response.setHeader("Pragma", "no-cache");
- response.setContentType(getMimetype() + ";charset=UTF-8");
- response.setHeader(AjaxContainerRenderer.AJAX_LOCATION_HEADER,redirectLocation);
- output = createResponseWriter(response, "UTF-8");
- // For buggy XmlHttpRequest realisations repeat headers in <meta>
- output.write("<?xml version=\"1.0\"
encoding=\"UTF-8\"?>\n" +
- "<html
xmlns=\"http://www.w3.org/1999/xhtml\"><head>"+
- "<meta
name=\""+AjaxContainerRenderer.AJAX_FLAG_HEADER+"\"
content=\"redirect\" />"+
- "<meta
name=\""+AjaxContainerRenderer.AJAX_LOCATION_HEADER+"\"
content=\""+redirectLocation+"\" />"+
- "</head></html>"
- );
- output.flush();
- response.flushBuffer();
- } else {
- response.sendRedirect(redirectLocation);
- }
- return;
- } else if
("true".equals(servletResponseWrapper.getHeaders().get(AjaxContainerRenderer.AJAX_FLAG_HEADER)))
{
- if(log.isDebugEnabled()){
- log.debug("Process response to well-formed XML for AJAX XMLHttpRequest
parser");
- }
- // Not caching AJAX request
- response.setHeader("Cache-Control",
- "no-cache, must-revalidate, max_age=0, no-store");
- response.setHeader("Expires", "0");
- response.setHeader("Pragma", "no-cache");
- //response.setCharacterEncoding(servletResponseWrapper
- //.getCharacterEncoding()); // JSContentHandler.DEFAULT_ENCODING);
- // Set the content-type. For AJAX responses default encoding - UTF8.
- // TODO - for null encoding, setup only Output encoding for filter ?
- String outputEncoding = "UTF-8";
- String contentType = getMimetype() + ";charset=" + outputEncoding;
- response.setContentType(contentType);
- parser = getParser(getMimetype(),true);
- if(null == parser){
- throw new
ServletException(Messages.getMessage(Messages.PARSER_NOT_INSTANTIATED_ERROR,
contentType));
- }
- output = createResponseWriter(response, outputEncoding);
- parser.setDoctype(getPublicid());
- parser.setInputEncoding(characterEncoding);
- parser.setOutputEncoding(outputEncoding);
- parser.setViewState((String)
request.getAttribute(AjaxViewHandler.SERIALIZED_STATE_KEY));
- } else {
- // setup conversion reules for output contentType, send directly if content not
- // supported by tidy.
- String contentType = servletResponseWrapper.getContentType();
- if(log.isDebugEnabled()){
- log.debug("create HTML/XML parser for content type: "+contentType);
- }
-// if(contentType == null){
-// contentType = request.getContentType();
-// }
- if(contentType != null){
- if (contentType.indexOf("charset")<0 && null !=
characterEncoding) {
- contentType += ";charset=" + characterEncoding;
- }
- parser = getParser(contentType,false);
- response.setContentType(contentType);
- }
- // null or unsupported content type
- if(null == parser) {
- if(log.isDebugEnabled()){
- log.debug("Parser not have support for the such content type, send response
as-is");
- }
- try {
- if (servletResponseWrapper.isUseWriter()) {
- output = createResponseWriter(response, characterEncoding);
- servletResponseWrapper.sendContent(output);
- } else if (servletResponseWrapper.isUseStream()) {
- ServletOutputStream out = response.getOutputStream();
- servletResponseWrapper.sendContent(out);
- }
- } finally {
- // reuseWrapper(servletResponseWrapper);
- }
- return;
- }
- output = createResponseWriter(response, characterEncoding);
+ private String systemid =
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd";
- parser.setInputEncoding(characterEncoding);
- parser.setOutputEncoding(characterEncoding);
- }
-
- try {
- // Setup scripts and styles
- parser.setScripts((Set) request.getAttribute(AjaxContext.SCRIPTS_PARAMETER));
- parser.setStyles((Set) request.getAttribute(AjaxContext.STYLES_PARAMETER));
- // Process parsing.
- long startTimeMills =System.currentTimeMillis();
- servletResponseWrapper.parseContent(output,parser);
- if (log.isDebugEnabled()) {
- startTimeMills = System.currentTimeMillis()-startTimeMills;
- log.debug(Messages.getMessage(Messages.PARSING_TIME_INFO, "" +
startTimeMills));
- }
- } catch (Exception e) {
- throw new ServletException(Messages.getMessage(Messages.JTIDY_PARSING_ERROR), e);
- } finally {
- reuseParser(parser);
- }
- }
+ private String namespace = "http://www.w3.org/1999/xhtml";
- /**
- * @param response
- * @return
- * @throws ServletException
- */
- protected FilterServletResponseWrapper getWrapper(HttpServletResponse response) throws
ServletException{
- return new FilterServletResponseWrapper(response);
+ private static final String MIME_TYPE_PARAMETER = "mime-type";
+
+ private static final String PUBLICID_PARAMETER = "publicid";
+
+ private static final String SYSTEMID_PARAMETER = "systemid";
+
+ private static final String NAMESPACE_PARAMETER = "namespace";
+
+ private boolean forcexml = false;
+
+ private static final String FORCEXML_PARAMETER = "forceparser";
+
+ public BaseFilter filter;
+
+ public void setFilter(BaseFilter filter) {
+ this.filter = filter;
+ }
+
+ public void init(FilterConfig config) throws ServletException {
+ if (log.isDebugEnabled()) {
+ log.debug("init XML filter service with class "
+ + this.getClass().getName());
}
-
- /**
- * @param request
- * @return
- */
- protected boolean isAjaxRequest(ServletRequest request) {
- try {
- return null != request
- .getParameter(AjaxContainerRenderer.AJAX_PARAMETER_NAME);
- } catch (Exception e) {
- // OCJ 10 - throw exception for static resources.
- return false;
- }
+ if ("false".equalsIgnoreCase(config
+ .getInitParameter(FORCEXML_PARAMETER))) {
+ this.forcexml = false;
}
+ if ("true"
+ .equalsIgnoreCase(config.getInitParameter(FORCEXML_PARAMETER))) {
+ this.forcexml = true;
+ }
+ setMimetype((String) nz(config.getInitParameter(MIME_TYPE_PARAMETER),
+ "text/xml"));
+ setPublicid((String) nz(config.getInitParameter(PUBLICID_PARAMETER),
+ getPublicid()));
+ setSystemid((String) nz(config.getInitParameter(SYSTEMID_PARAMETER),
+ getSystemid()));
+ setNamespace((String) nz(config.getInitParameter(NAMESPACE_PARAMETER),
+ getNamespace()));
+ }
- /**
- * @param response
- * @param characterEncoding
- * @return
- * @throws IOException
- * @throws UnsupportedEncodingException
- */
- private Writer createResponseWriter(final HttpServletResponse response, String
characterEncoding) throws IOException, UnsupportedEncodingException {
- Writer output;
+ /**
+ * Perform filter chain with xml parsing and transformation. Subclasses
+ * must implement concrete HTML to XML parsing, nesseasary
+ * transformations and serialization.
+ *
+ * @param chain
+ * @param httpServletRequest
+ * @param httpServletResponse
+ * @throws ServletException
+ * @throws IOException
+ */
+ protected void doXmlFilter(FilterChain chain, HttpServletRequest request,
+ final HttpServletResponse response) throws IOException,
+ ServletException {
+ if (log.isDebugEnabled()) {
+ log.debug("XML filter service start processing request");
+ }
+ FilterServletResponseWrapper servletResponseWrapper = getWrapper(response);
+ // HACK - to avoid MyFaces <f:view> incompabilites and bypass
+ // intermediaty filters
+ // in chain, self-rendered region write directly to wrapper stored in
+ // request-scope attribute.
+ request
+ .setAttribute(RESPONSE_WRAPPER_ATTRIBUTE,
+ servletResponseWrapper);
+ chain.doFilter(request, servletResponseWrapper);
+ HtmlParser parser = null;
+ // setup response
+ // Redirect in AJAX request - convert to special response recognized by
+ // client.
+ String redirectLocation = servletResponseWrapper.getRedirectLocation();
+ String characterEncoding = servletResponseWrapper
+ .getCharacterEncoding();
+ Writer output;
+ if (null != redirectLocation) {
+ if (isAjaxRequest(request)) {
+ // Special handling of redirect - client-side script must
+ // Check for response and perform redirect by window.location
+ if (log.isDebugEnabled()) {
+ log.debug("Create AJAX redirect response to url: "
+ + redirectLocation);
+ }
+ response.reset();
+ // Copy response headers
+ Map headers = servletResponseWrapper.getHeaders();
+ for (Iterator iter = headers.entrySet().iterator(); iter
+ .hasNext();) {
+ Map.Entry header = (Map.Entry) iter.next();
+ response.setHeader((String) header.getKey(),
+ (String) header.getValue());
+ }
+ response.setHeader(AjaxContainerRenderer.AJAX_FLAG_HEADER,
+ "redirect");
+ // Not caching AJAX request
+ response.setHeader("Cache-Control",
+ "no-cache, must-revalidate, max_age=0, no-store");
+ response.setHeader("Expires", "0");
+ response.setHeader("Pragma", "no-cache");
+ response.setContentType(getMimetype() + ";charset=UTF-8");
+ response.setHeader(AjaxContainerRenderer.AJAX_LOCATION_HEADER,
+ redirectLocation);
+ output = createResponseWriter(response, "UTF-8");
+ // For buggy XmlHttpRequest realisations repeat headers in
+ // <meta>
+ output.write("<?xml version=\"1.0\"
encoding=\"UTF-8\"?>\n"
+ + "<html
xmlns=\"http://www.w3.org/1999/xhtml\"><head>"
+ + "<meta name=\""
+ + AjaxContainerRenderer.AJAX_FLAG_HEADER
+ + "\" content=\"redirect\" />" + "<meta
name=\""
+ + AjaxContainerRenderer.AJAX_LOCATION_HEADER
+ + "\" content=\"" + redirectLocation + "\" />"
+ + "</head></html>");
+ output.flush();
+ response.flushBuffer();
+ } else {
+ response.sendRedirect(redirectLocation);
+ }
+ return;
+ } else if ("true".equals(servletResponseWrapper.getHeaders().get(
+ AjaxContainerRenderer.AJAX_FLAG_HEADER))) {
+ if (log.isDebugEnabled()) {
+ log
+ .debug("Process response to well-formed XML for AJAX XMLHttpRequest
parser");
+ }
+ // Not caching AJAX request
+ response.setHeader("Cache-Control",
+ "no-cache, must-revalidate, max_age=0, no-store");
+ response.setHeader("Expires", "0");
+ response.setHeader("Pragma", "no-cache");
+ // response.setCharacterEncoding(servletResponseWrapper
+ // .getCharacterEncoding()); //
+ // JSContentHandler.DEFAULT_ENCODING);
+ // Set the content-type. For AJAX responses default encoding -
+ // UTF8.
+ // TODO - for null encoding, setup only Output encoding for
+ // filter ?
+ String outputEncoding = "UTF-8";
+ String contentType = getMimetype() + ";charset=" + outputEncoding;
+ response.setContentType(contentType);
+ parser = getParser(getMimetype(), true);
+ if (null == parser) {
+ throw new ServletException(Messages.getMessage(
+ Messages.PARSER_NOT_INSTANTIATED_ERROR, contentType));
+ }
+ output = createResponseWriter(response, outputEncoding);
+ parser.setDoctype(getPublicid());
+ parser.setInputEncoding(characterEncoding);
+ parser.setOutputEncoding(outputEncoding);
+ parser.setViewState((String) request
+ .getAttribute(AjaxViewHandler.SERIALIZED_STATE_KEY));
+ } else {
+ // setup conversion reules for output contentType, send directly
+ // if content not
+ // supported by tidy.
+ String contentType = servletResponseWrapper.getContentType();
+ if (log.isDebugEnabled()) {
+ log.debug("create HTML/XML parser for content type: "
+ + contentType);
+ }
+ // if(contentType == null){
+ // contentType = request.getContentType();
+ // }
+ if (contentType != null) {
+ if (contentType.indexOf("charset") < 0
+ && null != characterEncoding) {
+ contentType += ";charset=" + characterEncoding;
+ }
+ parser = getParser(contentType, false);
+ response.setContentType(contentType);
+ }
+ // null or unsupported content type
+ if (null == parser) {
+ if (log.isDebugEnabled()) {
+ log
+ .debug("Parser not have support for the such content type, send response
as-is");
+ }
try {
- output = response.getWriter();
- } catch (IllegalStateException e) {
- if (null != characterEncoding) {
- output = new OutputStreamWriter(response.getOutputStream(),
- characterEncoding);
- } else {
- output = new OutputStreamWriter(response.getOutputStream());
- }
+ if (servletResponseWrapper.isUseWriter()) {
+ output = createResponseWriter(response,
+ characterEncoding);
+ servletResponseWrapper.sendContent(output);
+ } else if (servletResponseWrapper.isUseStream()) {
+ ServletOutputStream out = response.getOutputStream();
+ servletResponseWrapper.sendContent(out);
+ }
+ } finally {
+ // reuseWrapper(servletResponseWrapper);
}
- return output;
+ return;
+ }
+ output = createResponseWriter(response, characterEncoding);
+
+ parser.setInputEncoding(characterEncoding);
+ parser.setOutputEncoding(characterEncoding);
}
- protected abstract void reuseParser(HtmlParser parser);
+ try {
+ // Setup scripts and styles
+ parser.setScripts((Set) request
+ .getAttribute(AjaxContext.SCRIPTS_PARAMETER));
+ parser.setStyles((Set) request
+ .getAttribute(AjaxContext.STYLES_PARAMETER));
+ // Process parsing.
+ long startTimeMills = System.currentTimeMillis();
+ servletResponseWrapper.parseContent(output, parser);
+ if (log.isDebugEnabled()) {
+ startTimeMills = System.currentTimeMillis() - startTimeMills;
+ log.debug(Messages.getMessage(Messages.PARSING_TIME_INFO, ""
+ + startTimeMills));
+ }
+ } catch (Exception e) {
+ throw new ServletException(Messages
+ .getMessage(Messages.JTIDY_PARSING_ERROR), e);
+ } finally {
+ reuseParser(parser);
+ }
+ }
- protected abstract HtmlParser getParser(String mimetype, boolean isAjax);
+ /**
+ * @param response
+ * @return
+ * @throws ServletException
+ */
+ protected FilterServletResponseWrapper getWrapper(
+ HttpServletResponse response) throws ServletException {
+ return new FilterServletResponseWrapper(response);
+ }
- /**
- * @param publicid The publicid to set.
- */
- protected void setPublicid(String publicid) {
- this.publicid = publicid;
+ /**
+ * @param request
+ * @return
+ */
+ protected boolean isAjaxRequest(ServletRequest request) {
+ try {
+ return null != request
+ .getParameter(AjaxContainerRenderer.AJAX_PARAMETER_NAME);
+ } catch (Exception e) {
+ // OCJ 10 - throw exception for static resources.
+ return false;
}
+ }
- /**
- * @return Returns the publicid.
- */
- public String getPublicid() {
- return publicid;
+ /**
+ * @param response
+ * @param characterEncoding
+ * @return
+ * @throws IOException
+ * @throws UnsupportedEncodingException
+ */
+ private Writer createResponseWriter(final HttpServletResponse response,
+ String characterEncoding) throws IOException,
+ UnsupportedEncodingException {
+ Writer output;
+ try {
+ output = response.getWriter();
+ } catch (IllegalStateException e) {
+ if (null != characterEncoding) {
+ output = new OutputStreamWriter(response.getOutputStream(),
+ characterEncoding);
+ } else {
+ output = new OutputStreamWriter(response.getOutputStream());
+ }
}
+ return output;
+ }
- /**
- * @param systemid The systemid to set.
- */
- protected void setSystemid(String systemid) {
- this.systemid = systemid;
- }
+ protected abstract void reuseParser(HtmlParser parser);
- /**
- * @return Returns the systemid.
- */
- public String getSystemid() {
- return systemid;
- }
+ protected abstract HtmlParser getParser(String mimetype, boolean isAjax);
- /**
- * @param namespace The namespace to set.
- */
- protected void setNamespace(String namespace) {
- this.namespace = namespace;
- }
+ /**
+ * @param publicid
+ * The publicid to set.
+ */
+ protected void setPublicid(String publicid) {
+ this.publicid = publicid;
+ }
- /**
- * @return Returns the namespace.
- */
- public String getNamespace() {
- return namespace;
- }
+ /**
+ * @return Returns the publicid.
+ */
+ public String getPublicid() {
+ return publicid;
+ }
- /**
- * @param mimetype The mimetype to set.
- */
- protected void setMimetype(String mimetype) {
- this.mimetype = mimetype;
- }
+ /**
+ * @param systemid
+ * The systemid to set.
+ */
+ protected void setSystemid(String systemid) {
+ this.systemid = systemid;
+ }
- /**
- * @return Returns the mimetype.
- */
- protected String getMimetype() {
- return mimetype;
- }
+ /**
+ * @return Returns the systemid.
+ */
+ public String getSystemid() {
+ return systemid;
+ }
- /**
- * @return Returns the forcexml.
- */
- public boolean isForcexml() {
- return this.forcexml;
- }
+ /**
+ * @param namespace
+ * The namespace to set.
+ */
+ protected void setNamespace(String namespace) {
+ this.namespace = namespace;
+ }
- /**
- * @param forcexml The forcexml to set.
- */
- protected void setForcexml(boolean forcexml) {
- this.forcexml = forcexml;
- }
+ /**
+ * @return Returns the namespace.
+ */
+ public String getNamespace() {
+ return namespace;
+ }
+ /**
+ * @param mimetype
+ * The mimetype to set.
+ */
+ protected void setMimetype(String mimetype) {
+ this.mimetype = mimetype;
+ }
- private Object nz(Object param, Object def) {
- return param != null?param:def;
- }
+ /**
+ * @return Returns the mimetype.
+ */
+ protected String getMimetype() {
+ return mimetype;
+ }
+ /**
+ * @return Returns the forcexml.
+ */
+ public boolean isForcexml() {
+ return this.forcexml;
+ }
+
+ /**
+ * @param forcexml
+ * The forcexml to set.
+ */
+ protected void setForcexml(boolean forcexml) {
+ this.forcexml = forcexml;
+ }
+
+ private Object nz(Object param, Object def) {
+ return param != null ? param : def;
+ }
+
}
Modified:
trunk/framework/src/main/java/org/ajax4jsf/framework/renderer/ChameleonRenderKitFactory.java
===================================================================
---
trunk/framework/src/main/java/org/ajax4jsf/framework/renderer/ChameleonRenderKitFactory.java 2007-04-17
21:04:13 UTC (rev 93)
+++
trunk/framework/src/main/java/org/ajax4jsf/framework/renderer/ChameleonRenderKitFactory.java 2007-04-18
00:59:13 UTC (rev 94)
@@ -29,78 +29,103 @@
import javax.faces.render.RenderKit;
import javax.faces.render.RenderKitFactory;
+import org.ajax4jsf.framework.resource.InternetResourceBuilder;
import org.ajax4jsf.framework.util.message.Messages;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
-
/**
* @author shura (latest modification by $Author: alexsmirnov $)
* @version $Revision: 1.1.2.1 $ $Date: 2007/01/09 18:58:50 $
- *
+ *
*/
public class ChameleonRenderKitFactory extends RenderKitFactory {
RenderKitFactory defaultFactory;
-// private static final String AJAX_BASE_RENDER_KIT_PARAMETER =
"AJAX_BASE_RENDERKIT_ID";
-// private static final String AJAX_RENDER_KIT_PARAMETER =
"AJAX_RENDER_KIT_ID";
- private static final Log _log = LogFactory.getLog(ChameleonRenderKitFactory.class);
+ // private static final String AJAX_BASE_RENDER_KIT_PARAMETER =
+ // "AJAX_BASE_RENDERKIT_ID";
+ // private static final String AJAX_RENDER_KIT_PARAMETER =
+ // "AJAX_RENDER_KIT_ID";
+
+ private static final Log _log = LogFactory
+ .getLog(ChameleonRenderKitFactory.class);
+
/**
- * @param defaultFactory
- */
+ * @param defaultFactory
+ */
public ChameleonRenderKitFactory(RenderKitFactory defaultFactory) {
- this.defaultFactory = defaultFactory;
+ if (_log.isDebugEnabled()) {
+ _log.debug("ChameleonRenderKitFactory(RenderKitFactory) - Chameleon RenderKit
factory instantiated"); //$NON-NLS-1$
+ }
+ this.defaultFactory = defaultFactory;
+ // Init resources builder before use.
+ InternetResourceBuilder.getInstance().init();
}
+
/**
- * @param renderKitId
- * @param renderKit
- */
+ * @param renderKitId
+ * @param renderKit
+ */
public void addRenderKit(String renderKitId, RenderKit renderKit) {
- if (renderKit instanceof ChameleonRenderKit) {
-// ChameleonRenderKit chameleonRenderKit = (ChameleonRenderKit) renderKit;
-// chameleonRenderKit.setConfiguration(ConfigurationFactory.getRendererConfigurationInstance(renderKitId)) ;
- }
- defaultFactory.addRenderKit(renderKitId, renderKit);
+ if (_log.isDebugEnabled()) {
+ _log.debug("addRenderKit(String, RenderKit) - Added RenderKit with id -
renderKitId=" + renderKitId); //$NON-NLS-1$
+ }
+ if (renderKit instanceof ChameleonRenderKit) {
+ // ChameleonRenderKit chameleonRenderKit = (ChameleonRenderKit)
+ // renderKit;
+ //
chameleonRenderKit.setConfiguration(ConfigurationFactory.getRendererConfigurationInstance(renderKitId))
+ // ;
+ }
+ defaultFactory.addRenderKit(renderKitId, renderKit);
}
+
/**
- * @param context
- * @param renderKitId
- * @return
- */
+ * @param context
+ * @param renderKitId
+ * @return
+ */
public RenderKit getRenderKit(FacesContext context, String renderKitId) {
- RenderKit renderKit = defaultFactory.getRenderKit(context, renderKitId);
- if (renderKit instanceof ChameleonRenderKit) {
- if (_log.isDebugEnabled()) {
- _log.debug(Messages.getMessage(Messages.REQUEST_CHAMELEON_RENDER_KIT_INFO,
renderKitId));
- }
- String baseRenderKitId = null;
- // TODO - get DefaultRenderKitId from ViewHandler ?
- try {
- // IN JSF-RI verifications, context may be null !
- if(null != context) {
- baseRenderKitId = context.getApplication()
- .getDefaultRenderKitId();
- } else {
- ApplicationFactory appFactory =(ApplicationFactory)
FactoryFinder.getFactory(FactoryFinder.APPLICATION_FACTORY);
- baseRenderKitId = appFactory.getApplication().getDefaultRenderKitId();
- }
- } catch (Exception e) {
- _log.warn(Messages.getMessage(Messages.GET_DEFAULT_RENDER_KIT_ERROR), e);
- }
- if(baseRenderKitId == null ){
- baseRenderKitId = RenderKitFactory.HTML_BASIC_RENDER_KIT;
- }
- if (_log.isDebugEnabled()) {
- _log.debug(Messages.getMessage(Messages.DEFAULT_RENDER_KIT_INFO, baseRenderKitId));
- }
- ((ChameleonRenderKit)
renderKit).setDefaultRenderKit(defaultFactory.getRenderKit(context, baseRenderKitId));
- }
- return renderKit;
+ RenderKit renderKit = defaultFactory.getRenderKit(context, renderKitId);
+ if (renderKit instanceof ChameleonRenderKit) {
+ if (_log.isDebugEnabled()) {
+ _log.debug(Messages
+ .getMessage(Messages.REQUEST_CHAMELEON_RENDER_KIT_INFO,
+ renderKitId));
+ }
+ String baseRenderKitId = null;
+ // TODO - get DefaultRenderKitId from ViewHandler ?
+ try {
+ // IN JSF-RI verifications, context may be null !
+ if (null != context) {
+ baseRenderKitId = context.getApplication()
+ .getDefaultRenderKitId();
+ } else {
+ ApplicationFactory appFactory = (ApplicationFactory) FactoryFinder
+ .getFactory(FactoryFinder.APPLICATION_FACTORY);
+ baseRenderKitId = appFactory.getApplication()
+ .getDefaultRenderKitId();
+ }
+ } catch (Exception e) {
+ _log.warn(Messages
+ .getMessage(Messages.GET_DEFAULT_RENDER_KIT_ERROR), e);
+ }
+ if (baseRenderKitId == null) {
+ baseRenderKitId = RenderKitFactory.HTML_BASIC_RENDER_KIT;
+ }
+ if (_log.isDebugEnabled()) {
+ _log.debug(Messages.getMessage(
+ Messages.DEFAULT_RENDER_KIT_INFO, baseRenderKitId));
+ }
+ ((ChameleonRenderKit) renderKit).setDefaultRenderKit(defaultFactory
+ .getRenderKit(context, baseRenderKitId));
+ }
+ return renderKit;
}
+
/**
- * @return
- */
+ * @return
+ */
public Iterator getRenderKitIds() {
- return defaultFactory.getRenderKitIds();
+ return defaultFactory.getRenderKitIds();
}
}
Modified:
trunk/framework/src/main/java/org/ajax4jsf/framework/resource/InternetResourceBuilder.java
===================================================================
---
trunk/framework/src/main/java/org/ajax4jsf/framework/resource/InternetResourceBuilder.java 2007-04-17
21:04:13 UTC (rev 93)
+++
trunk/framework/src/main/java/org/ajax4jsf/framework/resource/InternetResourceBuilder.java 2007-04-18
00:59:13 UTC (rev 94)
@@ -39,139 +39,137 @@
public abstract class InternetResourceBuilder {
- protected static Log log = LogFactory.getLog(InternetResourceBuilder.class);
+ private static final Log log = LogFactory.getLog(InternetResourceBuilder.class);
- /**
- * Get application start time for check resources modification time.
- * @return application start time in msec's
- */
- public abstract long getStartTime();
+ /**
+ * Get application start time for check resources modification time.
+ *
+ * @return application start time in msec's
+ */
+ public abstract long getStartTime();
- /**
- * @param cacheable
- * @param session
- * @param mime
- * @return
- * @throws FacesException
- */
- public abstract InternetResource createUserResource(boolean cacheable,
- boolean session, String mime) throws FacesException;
+ /**
+ * @param cacheable
+ * @param session
+ * @param mime
+ * @return
+ * @throws FacesException
+ */
+ public abstract InternetResource createUserResource(boolean cacheable,
+ boolean session, String mime) throws FacesException;
- /**
- * @param request
- * @return
- */
- public abstract String getFacesResourceKey(HttpServletRequest request);
+ /**
+ * @param key
+ * @param resource
+ */
+ public abstract void addResource(String key, InternetResource resource);
- /**
- * @param key
- * @param resource
- */
- public abstract void addResource(String key, InternetResource resource);
+ /**
+ * @param path
+ * @return
+ * @throws ResourceNotFoundException
+ */
+ public abstract InternetResource getResource(String path)
+ throws ResourceNotFoundException;
- /**
- * @param path
- * @return
- * @throws ResourceNotFoundException
- */
- public abstract InternetResource getResource(String path)
- throws ResourceNotFoundException;
+ /**
+ * @param key
+ * @return
+ */
+ public abstract Object getResourceDataForKey(String key);
- /**
- * @param key
- * @return
- */
- public abstract Object getResourceDataForKey(String key);
+ /**
+ * @param key
+ * @return
+ * @throws ResourceNotFoundException
+ */
+ public abstract InternetResource getResourceForKey(String key)
+ throws ResourceNotFoundException;
- /**
- * @param key
- * @return
- * @throws ResourceNotFoundException
- */
- public abstract InternetResource getResourceForKey(String key)
- throws ResourceNotFoundException;
+ /**
+ * @param resource
+ * @param context
+ * @param storeData
+ * @return
+ */
+ public abstract String getUri(InternetResource resource,
+ FacesContext context, Object storeData);
- /**
- * @param resource
- * @param context
- * @param storeData
- * @return
- */
- public abstract String getUri(InternetResource resource,
- FacesContext context, Object storeData);
+ /**
+ * @param base
+ * @param path
+ * @return
+ * @throws FacesException
+ */
+ public abstract InternetResource createResource(Object base, String path)
+ throws FacesException;
- /**
- * @param base
- * @param path
- * @return
- * @throws FacesException
- */
- public abstract InternetResource createResource(Object base, String path)
- throws FacesException;
+ /**
+ * @throws ServletException
+ */
+ public abstract void init()
+ throws FacesException;
- /**
- * @param servletContext
- * @param filterName
- * @throws ServletException
- */
- public abstract void init(ServletContext servletContext, String filterName)
- throws ServletException;
+ /**
+ * static instance variable.
+ */
+ private static Map instances = Collections.synchronizedMap(new HashMap());
- /**
- * static instance variable.
- */
- private static Map instances = Collections.synchronizedMap(new HashMap());
-
- /**
- * Get ( or create if nessesary ) instance of builder for current loader.
- * check content of file
META-INF/services/org.ajax4jsf.framework.resource.InternetResourceBuilder for
- * name of class to instantiate, othrthise create {@link ResourceBuilderImpl} instance.
- * @return current builder instance.
- */
- public static InternetResourceBuilder getInstance() {
- ClassLoader loader = Thread.currentThread().getContextClassLoader();
- InternetResourceBuilder instance = (InternetResourceBuilder) instances
- .get(loader);
- if (null == instance) {
- try {
- String resource = "META-INF/services/"
- + InternetResourceBuilder.class.getName();
- InputStream in = loader.getResourceAsStream(resource);
- BufferedReader reader = new BufferedReader(
- new InputStreamReader(in));
- String serviceClassName = reader.readLine();
- reader.close();
- Class builderClass = loader.loadClass(serviceClassName);
- instance = (InternetResourceBuilder) builderClass.newInstance();
- if (log.isDebugEnabled()) {
- log.debug("Create instance of InternetBuilder from class "
- + serviceClassName);
- }
- } catch (Exception e) {
- if (log.isDebugEnabled()) {
- log
- .debug(
- "Create default implementation instance of InternetBuilder");
- }
- instance = new ResourceBuilderImpl();
- }
- instances.put(loader, instance);
+ /**
+ * Get ( or create if nessesary ) instance of builder for current
+ * loader. check content of file
+ * META-INF/services/org.ajax4jsf.framework.resource.InternetResourceBuilder
+ * for name of class to instantiate, othrthise create
+ * {@link ResourceBuilderImpl} instance.
+ *
+ * @return current builder instance.
+ */
+ public static InternetResourceBuilder getInstance() {
+ ClassLoader loader = Thread.currentThread().getContextClassLoader();
+ InternetResourceBuilder instance = (InternetResourceBuilder) instances
+ .get(loader);
+ if (null == instance) {
+ try {
+ String resource = "META-INF/services/"
+ + InternetResourceBuilder.class.getName();
+ InputStream in = loader.getResourceAsStream(resource);
+ BufferedReader reader = new BufferedReader(
+ new InputStreamReader(in));
+ String serviceClassName = reader.readLine();
+ reader.close();
+ Class builderClass = loader.loadClass(serviceClassName);
+ instance = (InternetResourceBuilder) builderClass.newInstance();
+ if (log.isDebugEnabled()) {
+ log.debug("Create instance of InternetBuilder from class "
+ + serviceClassName);
}
- return instance;
+ } catch (Exception e) {
+ if (log.isDebugEnabled()) {
+ log
+ .debug("Create default implementation instance of InternetBuilder");
+ }
+ instance = new ResourceBuilderImpl();
+ }
+ instances.put(loader, instance);
}
-
- /**
- * Package-wide method for reset instance in Junit tests.
- *
- * @param instance
- */
- public static void setInstance(InternetResourceBuilder instance) {
- ClassLoader loader = Thread.currentThread().getContextClassLoader();
- instances.put(loader, instance);
+ if(log.isDebugEnabled()){
+ log.debug("Return instance of internet resource builder
"+instance.toString());
}
+ return instance;
+ }
- public InternetResourceBuilder() {
- super();
- }
+ /**
+ * Package-wide method for reset instance in Junit tests.
+ *
+ * @param instance
+ */
+ public static void setInstance(InternetResourceBuilder instance) {
+ ClassLoader loader = Thread.currentThread().getContextClassLoader();
+ instances.put(loader, instance);
+ }
+ public InternetResourceBuilder() {
+ super();
+ }
+
}
\ No newline at end of file
Modified:
trunk/framework/src/main/java/org/ajax4jsf/framework/resource/InternetResourceService.java
===================================================================
---
trunk/framework/src/main/java/org/ajax4jsf/framework/resource/InternetResourceService.java 2007-04-17
21:04:13 UTC (rev 93)
+++
trunk/framework/src/main/java/org/ajax4jsf/framework/resource/InternetResourceService.java 2007-04-18
00:59:13 UTC (rev 94)
@@ -40,6 +40,7 @@
import org.ajax4jsf.framework.ajax.xmlfilter.BaseFilter;
import org.ajax4jsf.framework.ajax.xmlfilter.CacheContent;
+import org.ajax4jsf.framework.util.config.WebXml;
import org.ajax4jsf.framework.util.message.Messages;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
@@ -49,261 +50,285 @@
import com.opensymphony.oscache.web.ServletCacheAdministrator;
public class InternetResourceService {
- private static final Log log = LogFactory
- .getLog(InternetResourceService.class);
+ private static final Log log = LogFactory
+ .getLog(InternetResourceService.class);
- static final String ENABLE_CACHING_PARAMETER = "enable-cache";
+ static final String ENABLE_CACHING_PARAMETER = "enable-cache";
- private static final String RESOURCE_LIFECYCLE_PARAMETER =
"org.ajax4jsf.RESOURCE_LIFECYCLE";
+ private static final String RESOURCE_LIFECYCLE_PARAMETER =
"org.ajax4jsf.RESOURCE_LIFECYCLE";
- private FilterConfig filterConfig;
+ private FilterConfig filterConfig;
- private boolean cacheEnabled = true;
+ private boolean cacheEnabled = true;
- private ServletCacheAdministrator cacheAdmin;
+ private ServletCacheAdministrator cacheAdmin;
- private FacesContextFactory contextFactory;
+ private FacesContextFactory contextFactory;
- // private RenderKitFactory renderKitFactory;
- private String lifecycleClass;
- private ResourceLifecycle lifecycle ;
-
- private InternetResourceBuilder resourceBuilder;
+ // private RenderKitFactory renderKitFactory;
+ private String lifecycleClass;
- public InternetResourceService() {
+ private ResourceLifecycle lifecycle;
+
+ private InternetResourceBuilder resourceBuilder;
+
+ private WebXml webXml;
+
+ 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-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();
+ }
+ webXml = new WebXml();
+ webXml.init(servletContext,filterConfig.getFilterName());
+ if (log.isDebugEnabled()) {
+ log.debug("Resources service initialized");
+ }
+ }
- public void setCacheEnabled(boolean b) {
- cacheEnabled = b;
+ public boolean serviceResource(HttpServletRequest httpServletRequest,
+ HttpServletResponse httpServletResponse) throws ServletException,
+ IOException {
+ String resourceKey = webXml
+ .getFacesResourceKey(httpServletRequest);
+ if (null != resourceKey) {
+ serviceResource(resourceKey, httpServletRequest,
+ httpServletResponse);
+ return true;
}
+ return false;
+ }
- 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);
+ public void serviceResource(String resourceKey, HttpServletRequest request,
+ HttpServletResponse response) throws ServletException, IOException {
+ InternetResource resource;// getInternetResource(request);
+ try {
+ resource = getResourceBuilder().getResourceForKey(resourceKey);
+ } catch (ResourceNotFoundException e) {
+ throw new ServletException(e);
+ }
+ Object resourceDataForKey = getResourceBuilder()
+ .getResourceDataForKey(resourceKey);
+ if (resource.isCacheable(null) && 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(null)
+ .getTime() - 1000;
+ if (lastModified <= ifModifiedSince) {
+ response.setStatus(304);
+ return;
+ }
}
- // 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);
- }
+ } 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(null);
+ if (expired != null) {
+ response.setDateHeader("Expires", expired.getTime());
} else {
- lifecycle = new ResourceLifecycle();
+ response.setDateHeader("Expires", System
+ .currentTimeMillis()
+ + InternetResource.DEFAULT_EXPIRE);
}
- 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;
+ if (!request.getMethod().equals("HEAD")) {
+ content.send(response);
}
- 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);
+ } 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);
}
- Object resourceDataForKey = resourceBuilder.getResourceDataForKey(resourceKey);
- if (resource.isCacheable(null) && 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(null).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(null);
- 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);
- }
+ }
+ } 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
+ * @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(null) && this.cacheEnabled) {
+ resourceContext = new CachedResourceContext(resourceContext);
+ }
+ 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);
+ /**
+ * 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
}
- if (resource.isCacheable(null) && this.cacheEnabled) {
- resourceContext = new CachedResourceContext(resourceContext);
- }
- return resourceContext;
+ }
}
+ return properties;
- /**
- * 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 Returns the servletContext.
- */
- protected ServletContext getServletContext() {
- return filterConfig.getServletContext();
- }
+ /**
+ * @return the lifecycle
+ * @throws ServletException
+ */
+ protected ResourceLifecycle getLifecycle() throws FacesException {
+ return lifecycle;
+ }
-
-
- /**
- * @return the lifecycle
- * @throws ServletException
- */
- protected ResourceLifecycle getLifecycle() throws FacesException {
- return lifecycle;
+ /**
+ * @return the contextFactory
+ */
+ protected synchronized FacesContextFactory getContextFactory() {
+ if (contextFactory == null) {
+ contextFactory = (FacesContextFactory) FactoryFinder
+ .getFactory(FactoryFinder.FACES_CONTEXT_FACTORY);
}
-
-
- /**
- * @return the contextFactory
- */
- protected FacesContextFactory getContextFactory() {
- return contextFactory;
- }
+ return contextFactory;
+ }
- protected FacesContext getFacesContext(ServletRequest request,
- ServletResponse response) throws FacesException {
- return getContextFactory().getFacesContext(getServletContext(), request,
- response, getLifecycle());
- }
+ protected FacesContext getFacesContext(ServletRequest request,
+ ServletResponse response) throws FacesException {
+ return getContextFactory().getFacesContext(getServletContext(),
+ request, response, getLifecycle());
+ }
- /**
- * @return the resourceBuilder
- */
- protected InternetResourceBuilder getResourceBuilder() {
- return resourceBuilder;
+ /**
+ * @return the resourceBuilder
+ */
+ protected InternetResourceBuilder getResourceBuilder() {
+ if (resourceBuilder == null) {
+ // Create resource builder for this filter.
+ resourceBuilder = InternetResourceBuilder.getInstance();
}
+ return resourceBuilder;
+ }
}
Modified:
trunk/framework/src/main/java/org/ajax4jsf/framework/resource/ResourceBuilderImpl.java
===================================================================
---
trunk/framework/src/main/java/org/ajax4jsf/framework/resource/ResourceBuilderImpl.java 2007-04-17
21:04:13 UTC (rev 93)
+++
trunk/framework/src/main/java/org/ajax4jsf/framework/resource/ResourceBuilderImpl.java 2007-04-18
00:59:13 UTC (rev 94)
@@ -49,521 +49,534 @@
import org.ajax4jsf.framework.util.config.WebXml;
import org.ajax4jsf.framework.util.message.Messages;
import org.apache.commons.digester.Digester;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
import org.xml.sax.EntityResolver;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
/**
- * Produce instances of InternetResource's for any types -
- * jar resource, dynamic created image, component-incapsulated etc.
- * Realised as singleton class to support cache, configuration etc.
+ * Produce instances of InternetResource's for any types - jar resource, dynamic
+ * created image, component-incapsulated etc. Realised as singleton class to
+ * support cache, configuration etc.
*
* @author shura (latest modification by $Author: alexsmirnov $)
* @version $Revision: 1.1.2.1 $ $Date: 2007/01/09 18:56:58 $
- *
+ *
*/
public class ResourceBuilderImpl extends InternetResourceBuilder {
-
- private static final String DATA_SEPARATOR = "/DATA/";
- private static Map renderers;
- private static ResourceRenderer defaultRenderer = new MimeRenderer(null);
-
- /**
- * keep resources instances .
- * TODO - put this map to application-scope attribute, for support clastering
environment.
- */
- private Map resources = Collections.synchronizedMap(new HashMap());
-
- private long _startTime;
-
- private ServletContext servletContext;
-
- private WebXml webXml;
- private Codec codec;
-
- static {
- renderers = new HashMap();
- // append known renderers for extentions.
- renderers.put(".gif",new GifRenderer());
- ResourceRenderer renderer = new JpegRenderer();
- renderers.put(".jpeg",renderer);
- renderers.put(".jpg",renderer);
- renderers.put(".png",new PngRenderer());
- renderers.put(".js",new ScriptRenderer());
- renderers.put(".css",new StyleRenderer());
- renderers.put(".log",new LogfileRenderer());
- renderers.put(".html",new HTMLRenderer());
- renderers.put(".xhtml",new MimeRenderer("application/xhtml+xml"));
- renderers.put(".xml",new MimeRenderer("text/xml"));
- renderers.put(".xcss", new TemplateCSSRenderer());
-// renderers.put(".htc",new BehaviorRenderer());
- // set in-memory caching ImageIO
- ImageIO.setUseCache(false);
- }
-
- public WebXml getWebXml() {
- if(null == webXml){
- throw new FacesException("Resources framework is not initialised, check web.xml
for Filter configuration");
- }
- return webXml;
- }
+ private static final Log log = LogFactory.getLog(ResourceBuilderImpl.class);
- public void setWebXml(WebXml webXml) {
- this.webXml = webXml;
- }
-
- public ResourceBuilderImpl() {
- super();
- _startTime = System.currentTimeMillis();
- InternetResourceBuilder.setInstance(this);
- registerResources();
- }
+ private static final String DATA_SEPARATOR = "/DATA/";
- private void registerConfig(
- URL resourceConfig)
- {
- try
- {
- InputStream in = resourceConfig.openStream();
- try
- {
- Digester digester = new Digester();
- digester.setValidating(false);
- digester.setEntityResolver(new EntityResolver(){
- // Dummi resolver - alvays do nothing
- public InputSource resolveEntity(String publicId, String systemId) throws
SAXException, IOException {
- return new InputSource(new StringReader(""));
- }
- });
- digester.setNamespaceAware(false);
- digester.setUseContextClassLoader(true);
- digester.push(this);
- digester.addObjectCreate("resource-config/resource",
"class", JarResource.class);
- digester.addObjectCreate("resource-config/resource/renderer",
"class", HTMLRenderer.class);
-
digester.addCallMethod("resource-config/resource/renderer/content-type",
- "setContentType", 0);
- digester.addSetNext("resource-config/resource/renderer",
"setRenderer", ResourceRenderer.class.getName());
- digester.addCallMethod("resource-config/resource/name",
- "setKey", 0);
- digester.addCallMethod("resource-config/resource/path",
- "setPath", 0);
- digester.addCallMethod("resource-config/resource/cacheable",
- "setCacheable", 0);
- digester.addCallMethod("resource-config/resource/session-aware",
- "setSessionAware", 0);
- digester.addCallMethod("resource-config/resource/property",
- "setProperty", 2);
- digester.addCallParam("resource-config/resource/property/name", 0);
- digester.addCallParam("resource-config/resource/property/value",
1);
- digester.addCallMethod("resource-config/resource/content-type",
- "setContentType", 0);
- digester.addSetNext("resource-config/resource",
"addResource", InternetResource.class.getName());
- digester.parse(in);
- }
- finally
- {
- in.close();
- }
- }
- catch (IOException e)
- {
- throw new FacesException(e);
- }
- catch (SAXException e)
- {
- throw new FacesException(e);
- }
- }
- /**
- * @param servletContext
- */
- public void init(ServletContext servletContext, String filterName) throws
ServletException {
- this.servletContext = servletContext;
- setWebXml(new WebXml(servletContext,filterName));
- if ("true".equals(servletContext
- .getInitParameter(InternetResource.ENCODE_URI_PARAMETER))) {
- String random = servletContext
- .getInitParameter(InternetResource.ENCODE_PASS_PARAMETER);
- if (null == random) {
- random = "";
- for (int i = 0; i < 25; i++) {
- random += (char) (65 + 26 * Math.random());
- }
- }
- try {
- codec = new Codec(random);
- } catch (Exception e) {
- throw new ServletException("Error initialisation codec for resource
data",e);
- }
- } else {
- codec = new Codec();
- }
- _startTime = System.currentTimeMillis();
+ private static Map renderers;
+
+ private static ResourceRenderer defaultRenderer = new MimeRenderer(null);
+
+ /**
+ * keep resources instances . TODO - put this map to application-scope
+ * attribute, for support clastering environment.
+ */
+ private Map resources = Collections.synchronizedMap(new HashMap());
+
+ private long _startTime;
+
+ private Codec codec;
+
+ static {
+ renderers = new HashMap();
+ // append known renderers for extentions.
+ renderers.put(".gif", new GifRenderer());
+ ResourceRenderer renderer = new JpegRenderer();
+ renderers.put(".jpeg", renderer);
+ renderers.put(".jpg", renderer);
+ renderers.put(".png", new PngRenderer());
+ renderers.put(".js", new ScriptRenderer());
+ renderers.put(".css", new StyleRenderer());
+ renderers.put(".log", new LogfileRenderer());
+ renderers.put(".html", new HTMLRenderer());
+ renderers.put(".xhtml", new MimeRenderer("application/xhtml+xml"));
+ renderers.put(".xml", new MimeRenderer("text/xml"));
+ renderers.put(".xcss", new TemplateCSSRenderer());
+ // renderers.put(".htc",new BehaviorRenderer());
+ // set in-memory caching ImageIO
+ ImageIO.setUseCache(false);
+
+ }
+
+ public WebXml getWebXml(FacesContext context) {
+ WebXml webXml = (WebXml)
context.getExternalContext().getApplicationMap().get(WebXml.CONTEXT_ATTRIBUTE);
+ if (null == webXml) {
+ throw new FacesException(
+ "Resources framework is not initialised, check web.xml for Filter
configuration");
}
+ return webXml;
+ }
- /**
- * @throws FacesException
- */
- protected void registerResources() throws FacesException {
- try
- {
- ClassLoader loader = Thread.currentThread().getContextClassLoader();
- Enumeration e = loader.getResources("META-INF/resources-config.xml");
- while (e.hasMoreElements())
- {
- URL resource = (URL)e.nextElement();
- registerConfig(resource);
- }
+ public ResourceBuilderImpl() {
+ super();
+ _startTime = System.currentTimeMillis();
+ codec = new Codec();
+ }
+
+ /**
+ * @throws FacesException
+ */
+ protected void registerResources() throws FacesException {
+ try {
+ ClassLoader loader = Thread.currentThread().getContextClassLoader();
+ Enumeration e = loader
+ .getResources("META-INF/resources-config.xml");
+ while (e.hasMoreElements()) {
+ URL resource = (URL) e.nextElement();
+ registerConfig(resource);
+ }
+ } catch (IOException e) {
+ throw new FacesException(e);
+ }
+ }
+
+ private void registerConfig(URL resourceConfig) {
+ try {
+ if (log.isDebugEnabled()) {
+ log.debug("Process resources configuration file
"+resourceConfig.toExternalForm());
}
- catch (IOException e)
- {
- throw new FacesException(e);
+
+ InputStream in = resourceConfig.openStream();
+ try {
+ Digester digester = new Digester();
+ digester.setValidating(false);
+ digester.setEntityResolver(new EntityResolver() {
+ // Dummi resolver - alvays do nothing
+ public InputSource resolveEntity(String publicId,
+ String systemId) throws SAXException, IOException {
+ return new InputSource(new StringReader(""));
+ }
+ });
+ digester.setNamespaceAware(false);
+ digester.setUseContextClassLoader(true);
+ digester.push(this);
+ digester.addObjectCreate("resource-config/resource", "class",
+ JarResource.class);
+ digester.addObjectCreate("resource-config/resource/renderer",
+ "class", HTMLRenderer.class);
+ digester.addCallMethod(
+ "resource-config/resource/renderer/content-type",
+ "setContentType", 0);
+ digester.addSetNext("resource-config/resource/renderer",
+ "setRenderer", ResourceRenderer.class.getName());
+ digester.addCallMethod("resource-config/resource/name",
+ "setKey", 0);
+ digester.addCallMethod("resource-config/resource/path",
+ "setPath", 0);
+ digester.addCallMethod("resource-config/resource/cacheable",
+ "setCacheable", 0);
+ digester.addCallMethod(
+ "resource-config/resource/session-aware",
+ "setSessionAware", 0);
+ digester.addCallMethod("resource-config/resource/property",
+ "setProperty", 2);
+ digester.addCallParam("resource-config/resource/property/name",
+ 0);
+ digester.addCallParam(
+ "resource-config/resource/property/value", 1);
+ digester.addCallMethod("resource-config/resource/content-type",
+ "setContentType", 0);
+ digester.addSetNext("resource-config/resource", "addResource",
+ InternetResource.class.getName());
+ digester.parse(in);
+ } finally {
+ in.close();
}
+ } catch (IOException e) {
+ throw new FacesException(e);
+ } catch (SAXException e) {
+ throw new FacesException(e);
}
+ }
- /**
- * Base point for creating resource. Must detect type and build
- * appropriate instance. Currently - make static resource for ordinary
- * request, or instance of class.
- * @param base base object for resource ( resourcess in classpath will be get relative
to it package )
- * @param path key - path to resource, resource class name etc.
- * @return
- * @throws FacesException
- */
- public InternetResource createResource(Object base, String path) throws FacesException
{
- // TODO - detect type of resource ( for example, resources location path in Skin
- try {
- return getResource(path);
- } catch (ResourceNotFoundException e) {
- try {
- return getResource(buildKey(base,path));
- } catch (ResourceNotFoundException e1) {
- if(log.isDebugEnabled()){
- log.debug(Messages.getMessage(Messages.BUILD_RESOURCE_INFO, path));
- }
- }
- }
- // path - is class name ?
- InternetResource res;
- try {
- Class resourceClass = Class.forName(path);
- res = createDynamicResource(path,resourceClass);
- } catch (Exception e) {
- try {
- res = createJarResource(base, path);
- } catch (ResourceNotFoundException ex) {
- res = createStaticResource(path);
- }
- // TODO - if resource not found, create static ?
- }
- return res;
- }
-
-
- private String buildKey(Object base, String path) {
- if( path.startsWith("/")) {
- return path.substring(1);
- }
- if(null==base ){
- return path;
- }
- StringBuffer packageName = new
StringBuffer(base.getClass().getPackage().getName().replace('.','/'));
- return packageName.append("/").append(path).toString();
- }
-
- public String getUri(InternetResource resource, FacesContext context, Object
storeData){
- StringBuffer uri = new StringBuffer();//
ResourceServlet.DEFAULT_SERVLET_PATH).append("/");
- uri.append(resource.getKey());
- // append serialized data as Base-64 encoded request string.
- if (storeData != null) {
- try {
- byte[] objectData;
- if( !(storeData instanceof byte[])){
- ByteArrayOutputStream dataSteram = new ByteArrayOutputStream(
- 1024);
- ObjectOutputStream objStream = new ObjectOutputStream(
- dataSteram);
- objStream.writeObject(storeData);
- objStream.flush();
- objStream.close();
- dataSteram.close();
- objectData = dataSteram.toByteArray();
- } else {
- objectData = (byte[]) storeData;
- }
- uri.append(DATA_SEPARATOR);
- byte[] dataArray = encrypt(objectData);
- uri.append(new String(dataArray, "ISO-8859-1"));
+ /**
+ */
+ public void init()
+ throws FacesException {
+ // TODO - mace codec configurable.
+ registerResources();
+ }
- // / byte[] objectData = dataSteram.toByteArray();
- // / uri.append("?").append(new
- // String(Base64.encodeBase64(objectData),
- // / "ISO-8859-1"));
- } catch (Exception e) {
- // Ignore errors, log it
- log.error(Messages
- .getMessage(Messages.QUERY_STRING_BUILDING_ERROR), e);
- }
- }
- String resourceURL = getWebXml().getFacesResourceURL(context,
- uri.toString());//
context.getApplication().getViewHandler().getResourceURL(context,uri.toString());
- if (resource.isSessionAware()) {
- resourceURL = context.getExternalContext().encodeResourceURL(
- resourceURL);
- }
+ /**
+ * Base point for creating resource. Must detect type and build
+ * appropriate instance. Currently - make static resource for ordinary
+ * request, or instance of class.
+ *
+ * @param base
+ * base object for resource ( resourcess in classpath
+ * will be get relative to it package )
+ * @param path
+ * key - path to resource, resource class name etc.
+ * @return
+ * @throws FacesException
+ */
+ public InternetResource createResource(Object base, String path)
+ throws FacesException {
+ // TODO - detect type of resource ( for example, resources location path
+ // in Skin
+ try {
+ return getResource(path);
+ } catch (ResourceNotFoundException e) {
+ try {
+ return getResource(buildKey(base, path));
+ } catch (ResourceNotFoundException e1) {
if (log.isDebugEnabled()) {
- log.debug(Messages.getMessage(Messages.BUILD_RESOURCE_URI_INFO,
- resource.getKey(), resourceURL));
+ log.debug(Messages.getMessage(Messages.BUILD_RESOURCE_INFO,
+ path));
}
- return resourceURL;// context.getExternalContext().encodeResourceURL(resourceURL);
-
+ }
}
-
- /**
- * @param key
- * @return
- */
- public InternetResource getResourceForKey(String key) throws ResourceNotFoundException
{
-
- int data = key.indexOf(DATA_SEPARATOR);
- if(data>=0){
- key = key.substring(0,data);
- }
- return getResource(key);
+ // path - is class name ?
+ InternetResource res;
+ try {
+ Class resourceClass = Class.forName(path);
+ res = createDynamicResource(path, resourceClass);
+ } catch (Exception e) {
+ try {
+ res = createJarResource(base, path);
+ } catch (ResourceNotFoundException ex) {
+ res = createStaticResource(path);
+ }
+ // TODO - if resource not found, create static ?
}
-
- public Object getResourceDataForKey(String key){
- Object data = null;
- String dataString = null;
- int dataStart = key.indexOf(DATA_SEPARATOR);
- if(dataStart>=0){
- dataString = key.substring(dataStart+DATA_SEPARATOR.length());
- }
- if (log.isDebugEnabled()) {
- log.debug(Messages.getMessage(
- Messages.RESTORE_DATA_FROM_RESOURCE_URI_INFO, key,
- dataString));
- }
- if (dataString != null) {
- // dataString =
- // dataString.substring(dataStart+ResourceServlet.DATA_PARAMETER.length()+1);
- byte[] objectArray = null;
- try {
- byte[] dataArray = dataString.getBytes("ISO-8859-1");
- objectArray = decrypt(dataArray);
+ return res;
+ }
- ObjectInputStream in = new ObjectInputStream(
- new ByteArrayInputStream(objectArray));
- data = in.readObject();
- } catch (StreamCorruptedException e) {
- data = objectArray;
- } catch (IOException e) {
- log.error(Messages
- .getMessage(Messages.DESERIALIZE_DATA_INPUT_ERROR), e);
- } catch (ClassNotFoundException e) {
- log.error(Messages
- .getMessage(Messages.DATA_CLASS_NOT_FOUND_ERROR), e);
- }
- }
- return data;
+ private String buildKey(Object base, String path) {
+ if (path.startsWith("/")) {
+ return path.substring(1);
}
+ if (null == base) {
+ return path;
+ }
+ StringBuffer packageName = new StringBuffer(base.getClass()
+ .getPackage().getName().replace('.', '/'));
+ return packageName.append("/").append(path).toString();
+ }
- public InternetResource getResource(String path) throws ResourceNotFoundException {
-
- InternetResource internetResource = (InternetResource)resources.get(path);
- if (null == internetResource) {
- throw new ResourceNotFoundException("Resource not registered : "+path);
+ public String getUri(InternetResource resource, FacesContext context,
+ Object storeData) {
+ StringBuffer uri = new StringBuffer();//
ResourceServlet.DEFAULT_SERVLET_PATH).append("/");
+ uri.append(resource.getKey());
+ // append serialized data as Base-64 encoded request string.
+ if (storeData != null) {
+ try {
+ byte[] objectData;
+ if (!(storeData instanceof byte[])) {
+ ByteArrayOutputStream dataSteram = new ByteArrayOutputStream(
+ 1024);
+ ObjectOutputStream objStream = new ObjectOutputStream(
+ dataSteram);
+ objStream.writeObject(storeData);
+ objStream.flush();
+ objStream.close();
+ dataSteram.close();
+ objectData = dataSteram.toByteArray();
} else {
- return internetResource;
+ objectData = (byte[]) storeData;
}
+ uri.append(DATA_SEPARATOR);
+ byte[] dataArray = encrypt(objectData);
+ uri.append(new String(dataArray, "ISO-8859-1"));
+
+ // / byte[] objectData = dataSteram.toByteArray();
+ // / uri.append("?").append(new
+ // String(Base64.encodeBase64(objectData),
+ // / "ISO-8859-1"));
+ } catch (Exception e) {
+ // Ignore errors, log it
+ log.error(Messages
+ .getMessage(Messages.QUERY_STRING_BUILDING_ERROR), e);
+ }
}
-
- public void addResource(InternetResource resource){
- resources.put(resource.getKey(), resource);
+ String resourceURL = getWebXml(context).getFacesResourceURL(context,
+ uri.toString());//
context.getApplication().getViewHandler().getResourceURL(context,uri.toString());
+ if (resource.isSessionAware()) {
+ resourceURL = context.getExternalContext().encodeResourceURL(
+ resourceURL);
}
-
- public void addResource(String key, InternetResource resource){
- resources.put(key,resource);
- resource.setKey(key);
- // TODO - set renderer ?
+ if (log.isDebugEnabled()) {
+ log.debug(Messages.getMessage(Messages.BUILD_RESOURCE_URI_INFO,
+ resource.getKey(), resourceURL));
}
+ return resourceURL;// context.getExternalContext().encodeResourceURL(resourceURL);
-
-
- public String getFacesResourceKey(HttpServletRequest request) {
- return getWebXml().getFacesResourceKey(request);
+ }
+
+ /**
+ * @param key
+ * @return
+ */
+ public InternetResource getResourceForKey(String key)
+ throws ResourceNotFoundException {
+
+ int data = key.indexOf(DATA_SEPARATOR);
+ if (data >= 0) {
+ key = key.substring(0, data);
}
+ return getResource(key);
+ }
- public String getFacesResourceURL(FacesContext context, String Url) {
- return getWebXml().getFacesResourceURL(context, Url);
+ public Object getResourceDataForKey(String key) {
+ Object data = null;
+ String dataString = null;
+ int dataStart = key.indexOf(DATA_SEPARATOR);
+ if (dataStart >= 0) {
+ dataString = key.substring(dataStart + DATA_SEPARATOR.length());
}
+ if (log.isDebugEnabled()) {
+ log.debug(Messages.getMessage(
+ Messages.RESTORE_DATA_FROM_RESOURCE_URI_INFO, key,
+ dataString));
+ }
+ if (dataString != null) {
+ // dataString =
+ // dataString.substring(dataStart+ResourceServlet.DATA_PARAMETER.length()+1);
+ byte[] objectArray = null;
+ try {
+ byte[] dataArray = dataString.getBytes("ISO-8859-1");
+ objectArray = decrypt(dataArray);
- /**
- * Build resource for link to static context in webapp.
- * @param path
- * @return
- * @throws FacesException
- */
- protected InternetResource createStaticResource(String path) throws
ResourceNotFoundException, FacesException {
- FacesContext context = FacesContext.getCurrentInstance();
- if(null != context){
- if (context.getExternalContext().getContext() instanceof ServletContext) {
- ServletContext servletContext = (ServletContext)
context.getExternalContext().getContext();
- InputStream in = servletContext.getResourceAsStream(path);
- if(null != in){
- InternetResourceBase res = new StaticResource(path);
- setRenderer(res,path);
- res.setLastModified(new Date(getStartTime()));
- addResource(path,res);
- try {
- in.close();
- } catch (IOException e) {
- }
- return res;
- }
- }
- }
- throw new
ResourceNotFoundException(Messages.getMessage(Messages.STATIC_RESOURCE_NOT_FOUND_ERROR,
path));
+ ObjectInputStream in = new ObjectInputStream(
+ new ByteArrayInputStream(objectArray));
+ data = in.readObject();
+ } catch (StreamCorruptedException e) {
+ data = objectArray;
+ } catch (IOException e) {
+ log.error(Messages
+ .getMessage(Messages.DESERIALIZE_DATA_INPUT_ERROR), e);
+ } catch (ClassNotFoundException e) {
+ log.error(Messages
+ .getMessage(Messages.DATA_CLASS_NOT_FOUND_ERROR), e);
+ }
}
+ return data;
+ }
- private void setRenderer(InternetResourceBase res, String path) throws FacesException {
- int lastPoint = path.lastIndexOf('.');
- if(lastPoint > 0){
- String ext = path.substring(lastPoint);
- ResourceRenderer resourceRenderer = (ResourceRenderer) renderers.get(ext);
- if(null != resourceRenderer){
- res.setRenderer(resourceRenderer);
- } else {
- if(log.isDebugEnabled()){
- log.debug(Messages.getMessage(Messages.NO_RESOURCE_REGISTERED_ERROR_2, path,
renderers.keySet()));
- }
-
-// String mimeType = servletContext.getMimeType(path);
- res.setRenderer(defaultRenderer);
- }
- }
+ public InternetResource getResource(String path)
+ throws ResourceNotFoundException {
+
+ InternetResource internetResource = (InternetResource) resources
+ .get(path);
+ if (null == internetResource) {
+ throw new ResourceNotFoundException("Resource not registered : "
+ + path);
+ } else {
+ return internetResource;
}
+ }
- /**
- * Create resurce to send from classpath relative to base class.
- * @param base
- * @param path
- * @return
- * @throws FacesException
- */
- protected InternetResource createJarResource(Object base, String path) throws
ResourceNotFoundException, FacesException {
- String key = buildKey(base,path);
- ClassLoader loader = Thread.currentThread().getContextClassLoader();
- if(null != loader.getResource(key)){
- JarResource res = new JarResource(key);
- setRenderer(res,path);
- res.setLastModified(new Date(getStartTime()));
- addResource(key,res);
- return res;
- } else {
- throw new
ResourceNotFoundException(Messages.getMessage(Messages.NO_RESOURCE_EXISTS_ERROR, key));
+ public void addResource(InternetResource resource) {
+ resources.put(resource.getKey(), resource);
+ }
+
+ public void addResource(String key, InternetResource resource) {
+ resources.put(key, resource);
+ resource.setKey(key);
+ // TODO - set renderer ?
+ }
+
+// public String getFacesResourceKey(HttpServletRequest request) {
+// return getWebXml(context).getFacesResourceKey(request);
+// }
+
+ public String getFacesResourceURL(FacesContext context, String Url) {
+ return getWebXml(context).getFacesResourceURL(context, Url);
+ }
+
+ /**
+ * Build resource for link to static context in webapp.
+ *
+ * @param path
+ * @return
+ * @throws FacesException
+ */
+ protected InternetResource createStaticResource(String path)
+ throws ResourceNotFoundException, FacesException {
+ FacesContext context = FacesContext.getCurrentInstance();
+ if (null != context) {
+ if (context.getExternalContext().getContext() instanceof ServletContext) {
+ ServletContext servletContext = (ServletContext) context
+ .getExternalContext().getContext();
+ InputStream in = servletContext.getResourceAsStream(path);
+ if (null != in) {
+ InternetResourceBase res = new StaticResource(path);
+ setRenderer(res, path);
+ res.setLastModified(new Date(getStartTime()));
+ addResource(path, res);
+ try {
+ in.close();
+ } catch (IOException e) {
+ }
+ return res;
}
-
+ }
}
-
- /**
- * Create resource by instatiate given class.
- * @param path
- * @param instatiate
- * @return
- */
- protected InternetResource createDynamicResource(String path, Class instatiate) throws
ResourceNotFoundException {
- if(InternetResource.class.isAssignableFrom(instatiate) ){
- InternetResource resource;
- try {
- resource = (InternetResource) instatiate.newInstance();
- addResource(path,resource);
- } catch (Exception e) {
- String message = Messages.getMessage(Messages.INSTANTIATE_RESOURCE_ERROR,
instatiate.toString());
- log.error(message, e);
- throw new ResourceNotFoundException(message, e);
- }
- return resource;
+ throw new ResourceNotFoundException(Messages.getMessage(
+ Messages.STATIC_RESOURCE_NOT_FOUND_ERROR, path));
+ }
+
+ private void setRenderer(InternetResourceBase res, String path)
+ throws FacesException {
+ int lastPoint = path.lastIndexOf('.');
+ if (lastPoint > 0) {
+ String ext = path.substring(lastPoint);
+ ResourceRenderer resourceRenderer = (ResourceRenderer) renderers
+ .get(ext);
+ if (null != resourceRenderer) {
+ res.setRenderer(resourceRenderer);
+ } else {
+ if (log.isDebugEnabled()) {
+ log.debug(Messages.getMessage(
+ Messages.NO_RESOURCE_REGISTERED_ERROR_2, path,
+ renderers.keySet()));
}
- throw new FacesException(Messages.getMessage(Messages.INSTANTIATE_CLASS_ERROR));
+
+ // String mimeType = servletContext.getMimeType(path);
+ res.setRenderer(defaultRenderer);
+ }
}
+ }
- /**
- * Create resource by instatiate {@link UserResource} class with given properties ( or
got from cache ).
- * @param cacheable
- * @param session
- * @param mime
- * @return
- * @throws FacesException
- */
- public InternetResource createUserResource(boolean cacheable, boolean session, String
mime) throws FacesException {
- String path = getUserResourceKey(cacheable, session, mime);
- InternetResource userResource;
- try {
- userResource = getResource(path);
- } catch (ResourceNotFoundException e) {
- userResource = new UserResource(cacheable,session,mime);
- addResource(path,userResource);
- }
- return userResource;
+ /**
+ * Create resurce to send from classpath relative to base class.
+ *
+ * @param base
+ * @param path
+ * @return
+ * @throws FacesException
+ */
+ protected InternetResource createJarResource(Object base, String path)
+ throws ResourceNotFoundException, FacesException {
+ String key = buildKey(base, path);
+ ClassLoader loader = Thread.currentThread().getContextClassLoader();
+ if (null != loader.getResource(key)) {
+ JarResource res = new JarResource(key);
+ setRenderer(res, path);
+ res.setLastModified(new Date(getStartTime()));
+ addResource(key, res);
+ return res;
+ } else {
+ throw new ResourceNotFoundException(Messages.getMessage(
+ Messages.NO_RESOURCE_EXISTS_ERROR, key));
}
- /**
- * Generate resource key for user-generated resource with given properties.
- * @param cacheable
- * @param session
- * @param mime
- * @return
- */
- private String getUserResourceKey(boolean cacheable, boolean session, String mime) {
- StringBuffer pathBuffer = new StringBuffer(UserResource.class.getName());
- pathBuffer.append(cacheable?"/c":"/n");
- pathBuffer.append(session?"/s":"/n");
- if(null != mime){
- pathBuffer.append('/').append(mime.hashCode());
- }
- String path = pathBuffer.toString();
- return path;
+ }
+
+ /**
+ * Create resource by instatiate given class.
+ *
+ * @param path
+ * @param instatiate
+ * @return
+ */
+ protected InternetResource createDynamicResource(String path,
+ Class instatiate) throws ResourceNotFoundException {
+ if (InternetResource.class.isAssignableFrom(instatiate)) {
+ InternetResource resource;
+ try {
+ resource = (InternetResource) instatiate.newInstance();
+ addResource(path, resource);
+ } catch (Exception e) {
+ String message = Messages.getMessage(
+ Messages.INSTANTIATE_RESOURCE_ERROR, instatiate
+ .toString());
+ log.error(message, e);
+ throw new ResourceNotFoundException(message, e);
+ }
+ return resource;
}
- /**
- * @return Returns the startTime for application.
- */
- public long getStartTime() {
- return _startTime;
+ throw new FacesException(Messages
+ .getMessage(Messages.INSTANTIATE_CLASS_ERROR));
+ }
+
+ /**
+ * Create resource by instatiate {@link UserResource} class with given
+ * properties ( or got from cache ).
+ *
+ * @param cacheable
+ * @param session
+ * @param mime
+ * @return
+ * @throws FacesException
+ */
+ public InternetResource createUserResource(boolean cacheable,
+ boolean session, String mime) throws FacesException {
+ String path = getUserResourceKey(cacheable, session, mime);
+ InternetResource userResource;
+ try {
+ userResource = getResource(path);
+ } catch (ResourceNotFoundException e) {
+ userResource = new UserResource(cacheable, session, mime);
+ addResource(path, userResource);
}
+ return userResource;
+ }
- protected byte[] encrypt(byte[] src) {
- try {
- Deflater compressor = new Deflater(Deflater.BEST_SPEED);
- byte[] compressed = new byte[src.length + 100];
- compressor.setInput(src);
- compressor.finish();
- int totalOut = compressor.deflate(compressed);
- byte[] zipsrc = new byte[totalOut];
- System.arraycopy(compressed, 0, zipsrc, 0, totalOut);
- return codec.encode(zipsrc);
- } catch (Exception e) {
- throw new FacesException("Error encode resource data",e);
- }
+ /**
+ * Generate resource key for user-generated resource with given
+ * properties.
+ *
+ * @param cacheable
+ * @param session
+ * @param mime
+ * @return
+ */
+ private String getUserResourceKey(boolean cacheable, boolean session,
+ String mime) {
+ StringBuffer pathBuffer = new StringBuffer(UserResource.class.getName());
+ pathBuffer.append(cacheable ? "/c" : "/n");
+ pathBuffer.append(session ? "/s" : "/n");
+ if (null != mime) {
+ pathBuffer.append('/').append(mime.hashCode());
}
+ String path = pathBuffer.toString();
+ return path;
+ }
- protected byte[] decrypt(byte[] src) {
- try {
- byte[] zipsrc = codec.decode(src);
- Inflater decompressor = new Inflater();
- byte[] uncompressed = new byte[zipsrc.length * 5];
- decompressor.setInput(zipsrc);
- int totalOut = decompressor.inflate(uncompressed);
- decompressor.end();
- byte[] out = new byte[totalOut];
- System.arraycopy(uncompressed, 0, out, 0, totalOut);
- return out;
- } catch (Exception e) {
- throw new FacesException("Error decode resource data",e);
- }
+ /**
+ * @return Returns the startTime for application.
+ */
+ public long getStartTime() {
+ return _startTime;
+ }
+
+ protected byte[] encrypt(byte[] src) {
+ try {
+ Deflater compressor = new Deflater(Deflater.BEST_SPEED);
+ byte[] compressed = new byte[src.length + 100];
+ compressor.setInput(src);
+ compressor.finish();
+ int totalOut = compressor.deflate(compressed);
+ byte[] zipsrc = new byte[totalOut];
+ System.arraycopy(compressed, 0, zipsrc, 0, totalOut);
+ return codec.encode(zipsrc);
+ } catch (Exception e) {
+ throw new FacesException("Error encode resource data", e);
}
+ }
-
-
+ protected byte[] decrypt(byte[] src) {
+ try {
+ byte[] zipsrc = codec.decode(src);
+ Inflater decompressor = new Inflater();
+ byte[] uncompressed = new byte[zipsrc.length * 5];
+ decompressor.setInput(zipsrc);
+ int totalOut = decompressor.inflate(uncompressed);
+ decompressor.end();
+ byte[] out = new byte[totalOut];
+ System.arraycopy(uncompressed, 0, out, 0, totalOut);
+ return out;
+ } catch (Exception e) {
+ throw new FacesException("Error decode resource data", e);
+ }
+ }
+
}
Modified:
trunk/framework/src/main/java/org/ajax4jsf/framework/resource/cached/CachedResourceBuilder.java
===================================================================
---
trunk/framework/src/main/java/org/ajax4jsf/framework/resource/cached/CachedResourceBuilder.java 2007-04-17
21:04:13 UTC (rev 93)
+++
trunk/framework/src/main/java/org/ajax4jsf/framework/resource/cached/CachedResourceBuilder.java 2007-04-18
00:59:13 UTC (rev 94)
@@ -25,6 +25,7 @@
import java.io.InputStream;
import java.util.Properties;
+import javax.faces.FacesException;
import javax.faces.context.FacesContext;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
@@ -33,144 +34,166 @@
import org.ajax4jsf.framework.resource.ResourceBuilderImpl;
import org.ajax4jsf.framework.resource.ResourceNotFoundException;
import org.ajax4jsf.framework.util.message.Messages;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
-
/**
* @author shura
- *
+ *
*/
public class CachedResourceBuilder extends ResourceBuilderImpl {
- private static final int DEFAULT_CAPACITY = 10000;
+ private static final Log log = LogFactory
+ .getLog(CachedResourceBuilder.class);
- private ServletContext servletContext;
-
- private long counter = 0;
-
- private DualLRUMap cache ;
-
- /* (non-Javadoc)
- * @see org.ajax4jsf.framework.resource.ResourceBuilderImpl#decrypt(byte[])
- */
- protected byte[] decrypt(byte[] data) {
- // dummy - data not send via internet.
- return data;
- }
+ private static final int DEFAULT_CAPACITY = 10000;
- /* (non-Javadoc)
- * @see org.ajax4jsf.framework.resource.ResourceBuilderImpl#encrypt(byte[])
- */
- protected byte[] encrypt(byte[] data) {
- // dummy - data not send via internet.
- return data;
+ private long counter = 0;
+
+ private DualLRUMap cache;
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.ajax4jsf.framework.resource.ResourceBuilderImpl#decrypt(byte[])
+ */
+ protected byte[] decrypt(byte[] data) {
+ // dummy - data not send via internet.
+ return data;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.ajax4jsf.framework.resource.ResourceBuilderImpl#encrypt(byte[])
+ */
+ protected byte[] encrypt(byte[] data) {
+ // dummy - data not send via internet.
+ return data;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see
org.ajax4jsf.framework.resource.ResourceBuilderImpl#getResourceDataForKey(java.lang.String)
+ */
+ public Object getResourceDataForKey(String key) {
+ ResourceBean bean = (ResourceBean) cache.get(key);
+ if (null == bean) {
+ throw new ResourceNotFoundException("Resource for key " + key
+ + "not present in cache");
}
+ return bean.getData();
+ }
- /* (non-Javadoc)
- * @see
org.ajax4jsf.framework.resource.ResourceBuilderImpl#getResourceDataForKey(java.lang.String)
- */
- public Object getResourceDataForKey(String key) {
- ResourceBean bean = (ResourceBean) cache.get(key);
- if(null == bean){
- throw new ResourceNotFoundException("Resource for key "+key+"not
present in cache");
- }
- return bean.getData();
+ /*
+ * (non-Javadoc)
+ *
+ * @see
org.ajax4jsf.framework.resource.ResourceBuilderImpl#getResourceForKey(java.lang.String)
+ */
+ public InternetResource getResourceForKey(String key)
+ throws ResourceNotFoundException {
+ ResourceBean bean = (ResourceBean) cache.get(key);
+ if (null == bean) {
+ throw new ResourceNotFoundException("Resource for key " + key
+ + "not present in cache");
}
+ return super.getResourceForKey(bean.getKey());
+ }
- /* (non-Javadoc)
- * @see
org.ajax4jsf.framework.resource.ResourceBuilderImpl#getResourceForKey(java.lang.String)
- */
- public InternetResource getResourceForKey(String key) throws ResourceNotFoundException
{
- ResourceBean bean = (ResourceBean) cache.get(key);
- if(null == bean){
- throw new ResourceNotFoundException("Resource for key "+key+"not
present in cache");
- }
- return super.getResourceForKey(bean.getKey());
+ /*
+ * (non-Javadoc)
+ *
+ * @see
org.ajax4jsf.framework.resource.ResourceBuilderImpl#getUri(org.ajax4jsf.framework.resource.InternetResource,
+ * javax.faces.context.FacesContext, java.lang.Object)
+ */
+ public String getUri(InternetResource resource, FacesContext facesContext,
+ Object data) {
+ ResourceBean bean;
+ if (null == data) {
+ bean = new ResourceBean(resource.getKey());
+ } else {
+ if (data instanceof byte[]) {
+ // Special case for simple bytes array data.
+ bean = new ResourceBytesDataBean(resource.getKey(),
+ (byte[]) data);
+ } else {
+ bean = new ResourceDataBean(resource.getKey(), data);
+ }
}
+ String key = (String) cache.getKey(bean);
+ if (null == key) {
+ synchronized (this) {
+ counter++;
+ key = bean.hashCode() + "c" + counter;
+ }
+ cache.put(key, bean);
+ } else {
+ // Refresh LRU
+ cache.get(key);
+ }
+ String resourceURL = getFacesResourceURL(facesContext, key);
+ if (resource.isSessionAware()) {
+ resourceURL = facesContext.getExternalContext().encodeResourceURL(
+ resourceURL);
+ }
+ if (log.isDebugEnabled()) {
+ log.debug(Messages.getMessage(Messages.BUILD_RESOURCE_URI_INFO,
+ resource.getKey(), resourceURL));
+ }
+ return resourceURL;// context.getExternalContext().encodeResourceURL(resourceURL);
+ }
- /* (non-Javadoc)
- * @see
org.ajax4jsf.framework.resource.ResourceBuilderImpl#getUri(org.ajax4jsf.framework.resource.InternetResource,
javax.faces.context.FacesContext, java.lang.Object)
- */
- public String getUri(InternetResource resource, FacesContext facesContext, Object data)
{
- ResourceBean bean;
- if(null == data){
- bean = new ResourceBean(resource.getKey());
- } else {
- if (data instanceof byte[]) {
- // Special case for simple bytes array data.
- bean = new ResourceBytesDataBean(resource.getKey(),(byte[])data);
- } else {
- bean = new ResourceDataBean(resource.getKey(),data);
- }
- }
- String key = (String) cache.getKey(bean);
- if(null == key){
- synchronized (this) {
- counter++;
- key = bean.hashCode()+"c"+counter;
- }
- cache.put(key, bean);
- } else {
- // Refresh LRU
- cache.get(key);
- }
- String resourceURL = getFacesResourceURL(facesContext, key);
- if (resource.isSessionAware()) {
- resourceURL = facesContext.getExternalContext().encodeResourceURL(
- resourceURL);
- }
- if (log.isDebugEnabled()) {
- log.debug(Messages.getMessage(Messages.BUILD_RESOURCE_URI_INFO,
- resource.getKey(), resourceURL));
- }
- return resourceURL;// context.getExternalContext().encodeResourceURL(resourceURL);
+ /*
+ * (non-Javadoc)
+ *
+ * @see
org.ajax4jsf.framework.resource.ResourceBuilderImpl#init(javax.servlet.ServletContext,
+ * java.lang.String)
+ */
+ public void init()
+ throws FacesException {
+ super.init();
+ // Create cache manager.
+ Properties properties = getProperties("cache.properties");
+ int capacity = DEFAULT_CAPACITY;
+ String capacityString = properties.getProperty("cache.capacity");
+ if (null != capacityString) {
+ try {
+ capacity = Integer.parseInt(capacityString);
+ } catch (NumberFormatException e) {
+ log.warn("Error parsing value of parameters cache capacity, use default value
"+DEFAULT_CAPACITY, e);
+ }
}
+ cache = new DualLRUMap(capacity);
+ counter = getStartTime() - 1158760000000L;
+ }
- /* (non-Javadoc)
- * @see
org.ajax4jsf.framework.resource.ResourceBuilderImpl#init(javax.servlet.ServletContext,
java.lang.String)
- */
- public void init(ServletContext servletContext, String filterName) throws
ServletException {
- // TODO Auto-generated method stub
- super.init(servletContext, filterName);
- // Create cache manager.
- Properties properties = getProperties("cache.properties");
- int capacity = DEFAULT_CAPACITY;
- String capacityString = properties.getProperty("cache.capacity");
- if(null != capacityString){
- try {
- capacity = Integer.parseInt(capacityString);
- } catch (NumberFormatException e) {
- // use default.
- }
+ /**
+ * Get properties file from classpath
+ *
+ * @param name
+ * @return
+ */
+ protected Properties getProperties(String name) {
+ Properties properties = new Properties();
+ InputStream props = CachedResourceBuilder.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
}
- cache = new DualLRUMap(capacity);
- this.servletContext = servletContext;
- counter = getStartTime()-1158760000000L;
+ }
}
- /**
- * Get properties file from classpath
- *
- * @param name
- * @return
- */
- protected Properties getProperties(String name) {
- Properties properties = new Properties();
- InputStream props = CachedResourceBuilder.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 properties;
- }
+ }
}
Modified: trunk/framework/src/main/java/org/ajax4jsf/framework/util/base64/Codec.java
===================================================================
--- trunk/framework/src/main/java/org/ajax4jsf/framework/util/base64/Codec.java 2007-04-17
21:04:13 UTC (rev 93)
+++ trunk/framework/src/main/java/org/ajax4jsf/framework/util/base64/Codec.java 2007-04-18
00:59:13 UTC (rev 94)
@@ -21,12 +21,18 @@
package org.ajax4jsf.framework.util.base64;
+import java.io.UnsupportedEncodingException;
+import java.security.InvalidKeyException;
+import java.security.NoSuchAlgorithmException;
+import java.security.spec.InvalidKeySpecException;
import java.security.spec.KeySpec;
import javax.crypto.Cipher;
+import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
+import javax.faces.FacesException;
/**
* @author shura (latest modification by $Author: alexsmirnov $)
@@ -43,33 +49,43 @@
*
*/
public Codec() {
- super();
- // TODO Auto-generated constructor stub
}
/**
*
*/
public Codec( String p ) throws Exception {
- byte[] s = {
- (byte)0xA9, (byte)0x9B, (byte)0xC8, (byte)0x32,
- (byte)0x56, (byte)0x34, (byte)0xE3, (byte)0x03
- };
-// try {
- KeySpec keySpec = new DESKeySpec(p.getBytes("UTF8"));
- SecretKey key = SecretKeyFactory.getInstance("DES")
- .generateSecret(keySpec);
- e = Cipher.getInstance(key.getAlgorithm());
- d = Cipher.getInstance(key.getAlgorithm());
+ setPassword(p);
+ }
- // Prepare the parameters to the cipthers
+ /**
+ * @param p
+ * @throws InvalidKeyException
+ * @throws UnsupportedEncodingException
+ * @throws InvalidKeySpecException
+ * @throws NoSuchAlgorithmException
+ * @throws NoSuchPaddingException
+ */
+ public void setPassword(String p) throws FacesException {
+ byte[] s = {
+ (byte)0xA9, (byte)0x9B, (byte)0xC8, (byte)0x32,
+ (byte)0x56, (byte)0x34, (byte)0xE3, (byte)0x03
+ };
+ try {
+ KeySpec keySpec = new DESKeySpec(p.getBytes("UTF8"));
+ SecretKey key = SecretKeyFactory.getInstance("DES")
+ .generateSecret(keySpec);
+ e = Cipher.getInstance(key.getAlgorithm());
+ d = Cipher.getInstance(key.getAlgorithm());
+
+ // Prepare the parameters to the cipthers
// AlgorithmParameterSpec paramSpec = new IvParameterSpec(s);
- e.init(Cipher.ENCRYPT_MODE, key);
- d.init(Cipher.DECRYPT_MODE, key);
-// } catch (Exception e) {
-// // TODO: handle exception
-// }
+ e.init(Cipher.ENCRYPT_MODE, key);
+ d.init(Cipher.DECRYPT_MODE, key);
+ } catch (Exception e) {
+ throw new FacesException("Error set encryption key",e);
+ }
}
public String decode(String str) throws Exception {
Modified: trunk/framework/src/main/java/org/ajax4jsf/framework/util/config/WebXml.java
===================================================================
---
trunk/framework/src/main/java/org/ajax4jsf/framework/util/config/WebXml.java 2007-04-17
21:04:13 UTC (rev 93)
+++
trunk/framework/src/main/java/org/ajax4jsf/framework/util/config/WebXml.java 2007-04-18
00:59:13 UTC (rev 94)
@@ -23,6 +23,7 @@
import java.io.IOException;
import java.io.InputStream;
+import java.io.Serializable;
import java.io.StringReader;
import java.util.HashMap;
import java.util.Iterator;
@@ -51,11 +52,19 @@
* @version $Revision: 1.1.2.1 $ $Date: 2007/01/09 18:58:59 $
*
*/
-public class WebXml {
+public class WebXml implements Serializable {
+ public static final String CONTEXT_ATTRIBUTE = WebXml.class.getName();
+
+ /**
+ *
+ */
+ private static final long serialVersionUID = -9042908418843695017L;
+
private static final Log _log = LogFactory.getLog(WebXml.class);
static final String WEB_XML = "/WEB-INF/web.xml";
+
public static final String RESOURCE_URI_PREFIX = "a4j.res/";
@@ -87,90 +96,89 @@
*/
private String _resourcePrefix = RESOURCE_URI_PREFIX_WITH_SLASH;
+
/**
* Parse application web.xml configuration and detect mapping for resources
* and logs.
- *
* @param context
- * Current servlet context.
* @param filterName
- * name for Chameleon support filter.
+ * @throws ServletException
*/
- public WebXml(ServletContext context, String filterName)
- throws ServletException {
- super();
- InputStream webXml = context.getResourceAsStream(WEB_XML);
- if (null == webXml) {
- throw new ServletException(Messages.getMessage(
- Messages.GET_RESOURCE_AS_STREAM_ERROR, WEB_XML));
- }
- Digester dig = new Digester();
- dig.setDocumentLocator(new LocatorImpl());
- // Disable xml validations at all - web.xml already validated by
- // container
- dig.setValidating(false);
- dig.setEntityResolver(new EntityResolver() {
- // Dummi resolver - alvays do nothing
- public InputSource resolveEntity(String publicId, String systemId)
- throws SAXException, IOException {
- return new InputSource(new StringReader(""));
- }
+ public void init(ServletContext context, String filterName) throws ServletException {
+ InputStream webXml = context.getResourceAsStream(WEB_XML);
+ if (null == webXml) {
+ throw new ServletException(Messages.getMessage(
+ Messages.GET_RESOURCE_AS_STREAM_ERROR, WEB_XML));
+ }
+ Digester dig = new Digester();
+ dig.setDocumentLocator(new LocatorImpl());
+ // Disable xml validations at all - web.xml already validated by
+ // container
+ dig.setValidating(false);
+ dig.setEntityResolver(new EntityResolver() {
+ // Dummi resolver - alvays do nothing
+ public InputSource resolveEntity(String publicId, String systemId)
+ throws SAXException, IOException {
+ return new InputSource(new StringReader(""));
+ }
- });
- dig.setNamespaceAware(false);
- // dig.setUseContextClassLoader(true);
- dig.setClassLoader(this.getClass().getClassLoader());
- // Parsing rules.
- // Servlets.
- String path = "web-app/servlet";
- dig.addObjectCreate(path, ServletBean.class);
- dig.addBeanPropertySetter(path + "/servlet-name", "servletName");
- dig.addBeanPropertySetter(path + "/servlet-class",
"servletClass");
- dig.addBeanPropertySetter(path + "/display-name", "displayName");
- dig.addBeanPropertySetter(path + "/description");
- dig.addSetNext(path, "addServlet");
- // Filters
- path = "web-app/filter";
- dig.addObjectCreate(path, FilterBean.class);
- dig.addBeanPropertySetter(path + "/filter-name", "filterName");
- dig.addBeanPropertySetter(path + "/filter-class", "filterClass");
- dig.addBeanPropertySetter(path + "/display-name", "displayName");
- dig.addBeanPropertySetter(path + "/description");
- dig.addSetNext(path, "addFilter");
- // Servlet mappings
- path = "web-app/servlet-mapping";
- dig.addCallMethod(path, "addServletMapping", 2);
- dig.addCallParam(path + "/servlet-name", 0);
- dig.addCallParam(path + "/url-pattern", 1);
- // Filter mappings
- // TODO - parse dispatcher.
- path = "web-app/filter-mapping";
- dig.addCallMethod(path, "addFilterMapping", 3);
- dig.addCallParam(path + "/filter-name", 0);
- dig.addCallParam(path + "/url-pattern", 1);
- dig.addCallParam(path + "/servlet-name", 2);
- dig.push(this);
- try {
- dig.parse(webXml);
- this.setFilterName(filterName);
- } catch (IOException e) {
- String message = Messages
- .getMessage(Messages.PARSING_WEB_XML_IO_ERROR);
- _log.error(message, e);
- throw new ServletException(message, e);
- } catch (SAXException e) {
- String message = Messages
- .getMessage(Messages.PARSING_WEB_XML_SAX_ERROR);
- _log.error(message, e);
- throw new ServletException(message, e);
- } finally {
- try {
- webXml.close();
- } catch (IOException e) {
- // this exception don't affect any aspects of work and can be
- // ignored.
- }
- }
+ });
+ dig.setNamespaceAware(false);
+ // dig.setUseContextClassLoader(true);
+ dig.setClassLoader(this.getClass().getClassLoader());
+ // Parsing rules.
+ // Servlets.
+ String path = "web-app/servlet";
+ dig.addObjectCreate(path, ServletBean.class);
+ dig.addBeanPropertySetter(path + "/servlet-name",
"servletName");
+ dig.addBeanPropertySetter(path + "/servlet-class",
"servletClass");
+ dig.addBeanPropertySetter(path + "/display-name",
"displayName");
+ dig.addBeanPropertySetter(path + "/description");
+ dig.addSetNext(path, "addServlet");
+ // Filters
+ path = "web-app/filter";
+ dig.addObjectCreate(path, FilterBean.class);
+ dig.addBeanPropertySetter(path + "/filter-name", "filterName");
+ dig.addBeanPropertySetter(path + "/filter-class",
"filterClass");
+ dig.addBeanPropertySetter(path + "/display-name",
"displayName");
+ dig.addBeanPropertySetter(path + "/description");
+ dig.addSetNext(path, "addFilter");
+ // Servlet mappings
+ path = "web-app/servlet-mapping";
+ dig.addCallMethod(path, "addServletMapping", 2);
+ dig.addCallParam(path + "/servlet-name", 0);
+ dig.addCallParam(path + "/url-pattern", 1);
+ // Filter mappings
+ // TODO - parse dispatcher.
+ path = "web-app/filter-mapping";
+ dig.addCallMethod(path, "addFilterMapping", 3);
+ dig.addCallParam(path + "/filter-name", 0);
+ dig.addCallParam(path + "/url-pattern", 1);
+ dig.addCallParam(path + "/servlet-name", 2);
+ dig.push(this);
+ try {
+ dig.parse(webXml);
+ this.setFilterName(filterName);
+ // Store Instance to context attribute.
+ context.setAttribute(CONTEXT_ATTRIBUTE,this);
+ } catch (IOException e) {
+ String message = Messages
+ .getMessage(Messages.PARSING_WEB_XML_IO_ERROR);
+ _log.error(message, e);
+ throw new ServletException(message, e);
+ } catch (SAXException e) {
+ String message = Messages
+ .getMessage(Messages.PARSING_WEB_XML_SAX_ERROR);
+ _log.error(message, e);
+ throw new ServletException(message, e);
+ } finally {
+ try {
+ webXml.close();
+ } catch (IOException e) {
+ // this exception don't affect any aspects of work and can be
+ // ignored.
+ }
+ }
}
public void addServlet(ServletBean bean) {
@@ -362,7 +370,7 @@
_log.warn(Messages.getMessage(Messages.FILTER_NOT_FOUND_ERROR,
_filterName));
throw new IllegalStateException(Messages.getMessage(
- Messages.FILTER_NOT_CONFIGURED_ERROR, filterName));
+ Messages.FILTER_NOT_FOUND_ERROR, filterName));
}
// find faces servlet
checkMapping(filter.getMappings());